Última atividade 1 month ago

vps-agentctl.sh Bruto
1#!/usr/bin/env bash
2set -Eeuo pipefail
3IFS=$'\n\t'
4
5readonly PROGRAM="vps-agent"
6readonly BINARY="/usr/local/bin/vps-agent"
7readonly PREVIOUS="/usr/local/lib/vps-agent/vps-agent.previous"
8readonly CONFIG_DIR="/etc/vps-agent"
9readonly CREDENTIAL_DIR="${CONFIG_DIR}/credentials"
10readonly STATE_DIR="/var/lib/vps-agent"
11readonly UNIT="/etc/systemd/system/vps-agent.service"
12readonly DEFAULT_RELEASES="https://gitea.hyperdog.dev/dizyaka/vps-control/releases"
13
14VERSION="latest"
15RELEASES_URL="${VPS_AGENT_RELEASES_URL:-$DEFAULT_RELEASES}"
16PURGE=false
17ASSUME_YES=false
18TMP_DIR=""
19DOWNLOADED_BINARY=""
20
21usage() {
22 printf '%s\n' "Usage: $0 <install|update|remove|rollback|status|restart|version> [options]" \
23 " --version VERSION release tag, or latest" \
24 " --releases-url URL releases root (default: VPS_AGENT_RELEASES_URL)" \
25 " --purge remove configuration and credentials" \
26 " --yes confirm destructive purge"
27}
28
29die() { printf 'error: %s\n' "$*" >&2; exit 1; }
30info() { printf '==> %s\n' "$*"; }
31
32cleanup() {
33 if [[ -n "$TMP_DIR" && -d "$TMP_DIR" ]]; then
34 rm -rf -- "$TMP_DIR"
35 fi
36}
37trap cleanup EXIT
38
39require_root() { [[ ${EUID:-$(id -u)} -eq 0 ]] || die "run this action as root"; }
40
41check_host() {
42 [[ "$(uname -s)" == "Linux" ]] || die "only Linux is supported"
43 command -v systemctl >/dev/null || die "systemd is required"
44 [[ -d /run/systemd/system ]] || die "systemd is not running"
45}
46
47release_arch() {
48 case "$(uname -m)" in
49 x86_64|amd64) printf 'amd64\n' ;;
50 aarch64|arm64) printf 'arm64\n' ;;
51 *) die "unsupported architecture: $(uname -m)" ;;
52 esac
53}
54
55download_release() {
56 command -v curl >/dev/null || die "curl is required"
57 command -v sha256sum >/dev/null || die "sha256sum is required"
58 TMP_DIR="$(mktemp -d -t vps-agent.XXXXXXXX)"
59 chmod 700 "$TMP_DIR"
60 local artifact="vps-agent-linux-$(release_arch)"
61 local release_url
62 if [[ "$VERSION" == "latest" ]]; then
63 release_url="${RELEASES_URL%/}/latest/download"
64 else
65 [[ "$VERSION" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+([.-][A-Za-z0-9.-]+)?$ ]] || die "invalid release version"
66 release_url="${RELEASES_URL%/}/download/${VERSION}"
67 fi
68 info "downloading ${artifact} (${VERSION})"
69 curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
70 --output "$TMP_DIR/$artifact" "$release_url/$artifact"
71 curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
72 --output "$TMP_DIR/SHA256SUMS" "$release_url/SHA256SUMS"
73
74 local expected actual
75 expected="$(awk -v name="$artifact" '$2 == name || $2 == "*" name { print $1; exit }' "$TMP_DIR/SHA256SUMS")"
76 [[ "$expected" =~ ^[a-fA-F0-9]{64}$ ]] || die "artifact checksum is absent or malformed"
77 actual="$(sha256sum "$TMP_DIR/$artifact" | awk '{print $1}')"
78 [[ "$actual" == "$expected" ]] || die "checksum verification failed"
79
80 if [[ -n "${VPS_AGENT_MINISIGN_PUBLIC_KEY:-}" ]]; then
81 command -v minisign >/dev/null || die "minisign is required when a public key is configured"
82 curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
83 --output "$TMP_DIR/SHA256SUMS.minisig" "$release_url/SHA256SUMS.minisig"
84 minisign -Vm "$TMP_DIR/SHA256SUMS" -P "$VPS_AGENT_MINISIGN_PUBLIC_KEY"
85 fi
86 chmod 0755 "$TMP_DIR/$artifact"
87 "$TMP_DIR/$artifact" --version >/dev/null || die "downloaded binary self-check failed"
88 DOWNLOADED_BINARY="$TMP_DIR/$artifact"
89}
90
91install_unit() {
92 if [[ -f "$(cd "$(dirname "$0")" && pwd)/../agent/packaging/vps-agent.service" ]]; then
93 install -o root -g root -m 0644 \
94 "$(cd "$(dirname "$0")" && pwd)/../agent/packaging/vps-agent.service" "$UNIT"
95 return
96 fi
97 install -o root -g root -m 0644 /dev/null "$UNIT"
98 tee "$UNIT" >/dev/null <<'EOF'
99[Unit]
100Description=VPS Control monitoring agent
101After=network-online.target
102Wants=network-online.target
103[Service]
104Type=simple
105User=vps-agent
106Group=vps-agent
107ExecStart=/usr/local/bin/vps-agent --config /etc/vps-agent/config.toml
108Restart=on-failure
109RestartSec=5s
110TimeoutStopSec=15s
111MemoryHigh=48M
112MemoryMax=64M
113CPUQuota=10%
114TasksMax=64
115NoNewPrivileges=true
116PrivateTmp=true
117PrivateDevices=true
118ProtectHome=true
119ProtectSystem=strict
120ProtectKernelTunables=true
121ProtectKernelModules=true
122ProtectKernelLogs=true
123ProtectControlGroups=true
124ProtectClock=true
125ProtectHostname=true
126RestrictSUIDSGID=true
127LockPersonality=true
128RestrictRealtime=true
129RestrictNamespaces=true
130CapabilityBoundingSet=
131AmbientCapabilities=
132SystemCallArchitectures=native
133UMask=0077
134ProcSubset=all
135ProtectProc=invisible
136RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
137[Install]
138WantedBy=multi-user.target
139EOF
140}
141
142create_config() {
143 [[ -f "$CONFIG_DIR/config.toml" ]] && return
144 install -o root -g vps-agent -m 0640 /dev/null "$CONFIG_DIR/config.toml"
145 tee "$CONFIG_DIR/config.toml" >/dev/null <<'EOF'
146[server]
147listen = "127.0.0.1:9105"
148[auth]
149mode = "token"
150token_file = "/etc/vps-agent/credentials/control-plane.token"
151[limits]
152max_concurrent_requests = 32
153request_timeout_seconds = 5
154max_body_bytes = 65536
155read_requests_per_second = 10.0
156write_requests_per_second = 2.0
157burst = 20.0
158command_timeout_seconds = 4
159[services]
160allowed = []
161[firewall]
162management_enabled = false
163rollback_timeout_seconds = 60
164max_snapshots = 5
165[logging]
166level = "info"
167[telemetry]
168connections_enabled = true
169process_info_enabled = true
170[logs]
171enabled = false
172allowed_units = ["vps-agent.service"]
173max_entries_per_request = 200
174max_message_bytes = 16384
175[tls]
176enabled = false
177certificate_file = ""
178private_key_file = ""
179EOF
180}
181
182create_token() {
183 local token_file="$CREDENTIAL_DIR/control-plane.token"
184 [[ -f "$token_file" ]] && return
185 if command -v openssl >/dev/null; then
186 umask 077
187 openssl rand -hex 32 > "$token_file"
188 else
189 umask 077
190 od -An -N32 -tx1 /dev/urandom | tr -d ' \n' > "$token_file"
191 printf '\n' >> "$token_file"
192 fi
193 chown vps-agent:vps-agent "$token_file"
194 chmod 0600 "$token_file"
195 info "created agent token at $token_file; copy it through a secure channel"
196}
197
198wait_healthy() {
199 local attempts=15
200 while (( attempts > 0 )); do
201 if systemctl is-active --quiet vps-agent.service; then
202 return 0
203 fi
204 sleep 1
205 attempts=$((attempts - 1))
206 done
207 systemctl status --no-pager vps-agent.service || true
208 return 1
209}
210
211do_install() {
212 require_root; check_host
213 [[ ! -e "$BINARY" ]] || die "$BINARY already exists; use update"
214 local downloaded
215 download_release
216 downloaded="$DOWNLOADED_BINARY"
217 getent group vps-agent >/dev/null || groupadd --system vps-agent
218 id -u vps-agent >/dev/null 2>&1 || useradd --system --gid vps-agent --home-dir /nonexistent --shell /usr/sbin/nologin vps-agent
219 install -d -o root -g vps-agent -m 0750 "$CONFIG_DIR" "$CREDENTIAL_DIR"
220 install -d -o vps-agent -g vps-agent -m 0700 "$STATE_DIR"
221 install -d -o root -g root -m 0755 "$(dirname "$PREVIOUS")"
222 install -o root -g root -m 0755 "$downloaded" "$BINARY"
223 create_config
224 create_token
225 install_unit
226 systemctl daemon-reload
227 systemctl enable --now vps-agent.service
228 wait_healthy || die "agent failed to become healthy"
229 systemctl status --no-pager vps-agent.service
230}
231
232do_update() {
233 require_root; check_host
234 [[ -x "$BINARY" ]] || die "agent is not installed"
235 local downloaded staged
236 download_release
237 downloaded="$DOWNLOADED_BINARY"
238 staged="$(dirname "$BINARY")/.vps-agent.new"
239 install -o root -g root -m 0755 "$downloaded" "$staged"
240 install -o root -g root -m 0755 "$BINARY" "$PREVIOUS"
241 mv -f -- "$staged" "$BINARY"
242 systemctl restart vps-agent.service
243 if ! wait_healthy; then
244 info "health check failed; restoring previous binary"
245 install -o root -g root -m 0755 "$PREVIOUS" "$BINARY"
246 systemctl restart vps-agent.service
247 wait_healthy || die "rollback also failed; inspect systemctl status"
248 die "update rolled back"
249 fi
250 info "updated to $($BINARY --version)"
251}
252
253do_rollback() {
254 require_root; check_host
255 [[ -x "$PREVIOUS" ]] || die "no previous binary is available"
256 local current="$(dirname "$BINARY")/.vps-agent.current"
257 install -o root -g root -m 0755 "$BINARY" "$current"
258 install -o root -g root -m 0755 "$PREVIOUS" "$BINARY"
259 mv -f -- "$current" "$PREVIOUS"
260 systemctl restart vps-agent.service
261 wait_healthy || die "rolled-back version did not become healthy"
262}
263
264do_remove() {
265 require_root; check_host
266 if [[ "$PURGE" == true && "$ASSUME_YES" != true ]]; then
267 [[ -t 0 ]] || die "--purge requires an interactive terminal or --yes"
268 read -r -p "Permanently delete $CONFIG_DIR and credentials? [y/N] " answer
269 [[ "$answer" == "y" || "$answer" == "Y" ]] || die "purge cancelled"
270 fi
271 systemctl disable --now vps-agent.service 2>/dev/null || true
272 rm -f -- "$UNIT" "$BINARY" "$PREVIOUS"
273 rm -rf -- "$STATE_DIR"
274 systemctl daemon-reload
275 if [[ "$PURGE" == true ]]; then
276 rm -rf -- "$CONFIG_DIR"
277 info "removed configuration and credentials; this cannot be recovered"
278 else
279 info "preserved $CONFIG_DIR (use remove --purge to delete it)"
280 fi
281 userdel vps-agent 2>/dev/null || true
282 groupdel vps-agent 2>/dev/null || true
283}
284
285[[ $# -ge 1 ]] || { usage; exit 2; }
286ACTION="$1"; shift
287while [[ $# -gt 0 ]]; do
288 case "$1" in
289 --version) [[ $# -ge 2 ]] || die "--version needs a value"; VERSION="$2"; shift 2 ;;
290 --releases-url) [[ $# -ge 2 ]] || die "--releases-url needs a value"; RELEASES_URL="$2"; shift 2 ;;
291 --purge) PURGE=true; shift ;;
292 --yes) ASSUME_YES=true; shift ;;
293 -h|--help) usage; exit 0 ;;
294 *) die "unknown option: $1" ;;
295 esac
296done
297
298case "$ACTION" in
299 install) do_install ;;
300 update) do_update ;;
301 remove) do_remove ;;
302 rollback) do_rollback ;;
303 status) systemctl status --no-pager vps-agent.service ;;
304 restart) require_root; systemctl restart vps-agent.service; wait_healthy ;;
305 version) [[ -x "$BINARY" ]] && "$BINARY" --version || die "agent is not installed" ;;
306 *) usage; exit 2 ;;
307esac
308