From 1c8b8580d788ab467a82f2441a65e54effb1f0c0 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Thu, 5 Nov 2026 11:14:54 -0600 Subject: [PATCH] Add OCI edge restart and agent recovery checks --- .../edge/files/oracle-agent-watchdog.service | 8 ++ bootstrap/edge/files/oracle-agent-watchdog.sh | 20 +++++ .../edge/files/oracle-agent-watchdog.timer | 10 +++ bootstrap/edge/main.tf | 27 ++++++ bootstrap/oci/README.md | 27 ++++++ bootstrap/oci/main.tf | 4 + jeannie | 8 +- lib/jeannie/commands.sh | 86 ++++++++++++++++++- scripts/oci-foundation-resolve.py | 28 +++++- 9 files changed, 213 insertions(+), 5 deletions(-) create mode 100644 bootstrap/edge/files/oracle-agent-watchdog.service create mode 100644 bootstrap/edge/files/oracle-agent-watchdog.sh create mode 100644 bootstrap/edge/files/oracle-agent-watchdog.timer diff --git a/bootstrap/edge/files/oracle-agent-watchdog.service b/bootstrap/edge/files/oracle-agent-watchdog.service new file mode 100644 index 0000000..b696e63 --- /dev/null +++ b/bootstrap/edge/files/oracle-agent-watchdog.service @@ -0,0 +1,8 @@ +[Unit] +Description=Recover the native Oracle Cloud Agent if it is stopped +After=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/jeannie-oracle-agent-watchdog +TimeoutStartSec=90 diff --git a/bootstrap/edge/files/oracle-agent-watchdog.sh b/bootstrap/edge/files/oracle-agent-watchdog.sh new file mode 100644 index 0000000..661a37c --- /dev/null +++ b/bootstrap/edge/files/oracle-agent-watchdog.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# Recover a native Oracle Cloud Agent service without installing packages. +set -eu + +unit=oracle-cloud-agent.service +load_state=$(systemctl show "$unit" --property=LoadState --value 2>/dev/null || true) +if [ "$load_state" != loaded ]; then + echo "Oracle Cloud Agent native service is absent; automatic restart is unavailable." >&2 + exit 1 +fi + +if systemctl is-active --quiet "$unit"; then + echo "Oracle Cloud Agent native service is active." + exit 0 +fi + +echo "Oracle Cloud Agent native service is inactive; attempting restart." +systemctl reset-failed "$unit" +systemctl start "$unit" +systemctl is-active --quiet "$unit" diff --git a/bootstrap/edge/files/oracle-agent-watchdog.timer b/bootstrap/edge/files/oracle-agent-watchdog.timer new file mode 100644 index 0000000..b2f225b --- /dev/null +++ b/bootstrap/edge/files/oracle-agent-watchdog.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Periodically check the native Oracle Cloud Agent + +[Timer] +OnBootSec=5min +OnUnitActiveSec=5min +Unit=oracle-agent-watchdog.service + +[Install] +WantedBy=timers.target diff --git a/bootstrap/edge/main.tf b/bootstrap/edge/main.tf index 6feab2b..d7cd6c1 100644 --- a/bootstrap/edge/main.tf +++ b/bootstrap/edge/main.tf @@ -126,6 +126,11 @@ resource "null_resource" "edge_services" { lab_schedule_enabled = tostring(var.lab_schedule_enabled) lab_schedule_api_url = var.lab_schedule_api_url lab_schedule_timezone = var.lab_schedule_timezone + agent_watchdog_hash = sha256(join("", [ + filesha256("${path.module}/files/oracle-agent-watchdog.sh"), + filesha256("${path.module}/files/oracle-agent-watchdog.service"), + filesha256("${path.module}/files/oracle-agent-watchdog.timer"), + ])) config_hash = local.config_hash } @@ -153,6 +158,21 @@ resource "null_resource" "edge_services" { destination = "/tmp/homelab-edge/docker-compose.yml" } + provisioner "file" { + source = "${path.module}/files/oracle-agent-watchdog.sh" + destination = "/tmp/homelab-edge/oracle-agent-watchdog.sh" + } + + provisioner "file" { + source = "${path.module}/files/oracle-agent-watchdog.service" + destination = "/tmp/homelab-edge/oracle-agent-watchdog.service" + } + + provisioner "file" { + source = "${path.module}/files/oracle-agent-watchdog.timer" + destination = "/tmp/homelab-edge/oracle-agent-watchdog.timer" + } + provisioner "file" { content = local.default_conf destination = "/tmp/homelab-edge/config_files/default.conf" @@ -248,6 +268,13 @@ install_missing_packages() { edge_stage packages install_missing_packages ca-certificates curl openssl prometheus-node-exporter +edge_stage oracle-agent-watchdog +sudo install -m 0755 /tmp/homelab-edge/oracle-agent-watchdog.sh /usr/local/sbin/jeannie-oracle-agent-watchdog +sudo install -m 0644 /tmp/homelab-edge/oracle-agent-watchdog.service /etc/systemd/system/oracle-agent-watchdog.service +sudo install -m 0644 /tmp/homelab-edge/oracle-agent-watchdog.timer /etc/systemd/system/oracle-agent-watchdog.timer +sudo systemctl daemon-reload +sudo systemctl enable --now oracle-agent-watchdog.timer + edge_stage tailscale if ! command -v tailscale >/dev/null 2>&1; then curl -fsSL https://tailscale.com/install.sh | sudo sh diff --git a/bootstrap/oci/README.md b/bootstrap/oci/README.md index 0883892..7371f56 100644 --- a/bootstrap/oci/README.md +++ b/bootstrap/oci/README.md @@ -1,5 +1,32 @@ # OCI foundation +## Edge agent recovery + +`./jeannie oci agent-status` reads the managed edge identity from the selected +foundation state and reports OCI agent configuration and key plugin statuses. +It is also available as `./jeannie remote oci agent-status`. An `INVALID` or +stale plugin status does not identify which guest component failed. + +`./jeannie oci restart-edge` requests an OCI `SOFTRESET` for the edge instance +recorded in the selected foundation state, after checking the instance is +`RUNNING`. It does not replace the instance or require SSH. OCI can power-cycle +the VM if the guest has not shut down after its grace period. The command +reports request acceptance, not completion; check the edge and agent status +afterward. Run it on Debian or through a direct private API route: the public +API route through the edge will be interrupted by the reboot. + +The managed edge definition explicitly enables the Compute Instance Run Command +plugin. Edge bootstrap installs a five-minute systemd watchdog for a native +`oracle-cloud-agent.service`: if the unit exists but is stopped, it tries to +start it. It does not install an agent or use Snap. A missing unit is reported +in the watchdog journal. A running service does not prove it can reach OCI; the +watchdog cannot repair an unresponsive running service or missing plugin. + +The existing `./jeannie edge apply` installs the watchdog over its configured +SSH transport; it cannot install it on an unreachable instance. Review the +foundation plan for agent configuration changes before applying it. Do not +replace a working edge simply to install the watchdog. + This independent, opt-in stack creates the OCI foundation for the learning environment: a child compartment (or uses an existing one), VCN, internet and NAT gateways, public/private subnets, NSGs, and separate edge and email VMs. diff --git a/bootstrap/oci/main.tf b/bootstrap/oci/main.tf index 2d237df..073ddb5 100644 --- a/bootstrap/oci/main.tf +++ b/bootstrap/oci/main.tf @@ -471,6 +471,10 @@ resource "oci_core_instance" "edge" { agent_config { is_management_disabled = false is_monitoring_disabled = false + plugins_config { + name = "Compute Instance Run Command" + desired_state = "ENABLED" + } plugins_config { name = "Bastion" desired_state = "ENABLED" diff --git a/jeannie b/jeannie index fa00c72..8ea4db5 100755 --- a/jeannie +++ b/jeannie @@ -152,10 +152,10 @@ Observability And GitOps edge Deploy/check the OCI edge stack only. email-vm {status|plan|apply|setup|status-server|destroy --yes} Manage the OCI email VM and its mail-server baseline. - oci-foundation {verify|status|plan|apply|destroy --yes} + oci-foundation {verify|status|plan|review-edge-plan PLAN|apply|destroy --yes} Create the opt-in OCI compartment, network, edge VM, and email VM. oci-auth {install|init [--force]|check} Install/check OCI CLI and API-key authentication on Debian. - oci {status|doctor|bastion ssh [--print-command]|cleanup} + oci {status|doctor|agent-status|restart-edge|bastion ssh [--print-command]|cleanup} Inspect OCI resources, open Bastion SSH, or clean up infrastructure. edge-cache-flush Clear Nginx, Varnish, and Squid edge caches. edge diagnose Inspect edge startup errors and port listeners. @@ -448,9 +448,11 @@ case "${1:-}" in case "${2:-status}" in status) oci_status ;; doctor) oci_doctor ;; + agent-status) oci_agent_status "${@:3}" ;; + restart-edge) record_change_journal "oci-restart-edge" "$@"; oci_restart_edge "${@:3}" ;; bastion) oci_bastion_ssh "${@:3}" ;; cleanup) oci_cleanup "${@:3}" ;; - *) echo "Usage: ./jeannie oci {status|doctor|bastion ssh|cleanup plan|cleanup apply --confirm TENANCY-CLEANUP}" >&2; exit 2 ;; + *) echo "Usage: ./jeannie oci {status|doctor|agent-status|restart-edge|bastion ssh|cleanup plan|cleanup apply --confirm TENANCY-CLEANUP}" >&2; exit 2 ;; esac ;; edge-cache-flush) diff --git a/lib/jeannie/commands.sh b/lib/jeannie/commands.sh index 2c7a2c5..bfb62d4 100644 --- a/lib/jeannie/commands.sh +++ b/lib/jeannie/commands.sh @@ -4116,6 +4116,19 @@ oci_foundation_manage() { tofu -chdir="${stack}" show -no-color || return 1 fi ;; + review-edge-plan) + if [[ $# -ne 1 || "$1" != /* || ! -f "$1" ]]; then + echo "Usage: ./jeannie oci-foundation review-edge-plan /absolute/path/to/saved-plan" >&2 + return 2 + fi + local reviewed_state="${state_file:-${stack}/terraform.tfstate}" + if [[ ! -f "${reviewed_state}" ]]; then + echo "OCI foundation state file not found: ${reviewed_state}" >&2 + return 1 + fi + tofu -chdir="${stack}" show -json "$1" | + python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" review-edge-plan --state "${reviewed_state}" + ;; plan|apply) # Serialize generated import declarations as well as state access. local foundation_lock @@ -4269,7 +4282,7 @@ oci_foundation_manage() { tofu -chdir="${stack}" destroy "${tofu_state_args[@]}" "$@" -auto-approve ;; *) - echo "Usage: ./jeannie oci-foundation {verify|status|plan|apply|destroy --yes}" >&2 + echo "Usage: ./jeannie oci-foundation {verify|status|plan|review-edge-plan PLAN|apply|destroy --yes}" >&2 return 2 ;; esac @@ -4358,6 +4371,77 @@ oci_discover_active_bastion_id() { --kind bastion --name "$2" --root "$1" } +oci_managed_edge_id() { + local state_file="${LAB_OCI_FOUNDATION_STATE_FILE:-${REPO_ROOT}/bootstrap/oci/terraform.tfstate}" + python3 -c 'import json,sys +with open(sys.argv[1]) as f: state=json.load(f) +ids=[i.get("attributes",{}).get("id") for r in state.get("resources",[]) if r.get("mode")=="managed" and r.get("type")=="oci_core_instance" and r.get("name")=="edge" for i in r.get("instances",[]) if not i.get("deposed")] +if len(ids)!=1 or not ids[0] or not ids[0].startswith("ocid1.instance."): raise SystemExit("Expected one managed edge instance in state") +print(ids[0])' "${state_file}" +} + +oci_restart_edge() { + require_debian_server "oci restart-edge" + oci_foundation_load_config || return 1 + if [[ $# -ne 0 ]]; then + echo "Usage: ./jeannie oci restart-edge" >&2 + return 2 + fi + local oci_bin edge_id instance_json lifecycle observed_id + local -a oci_options=() + oci_bin="$(oci_cli_resolve)" || { echo "OCI CLI is not installed." >&2; return 1; } + [[ -z "${LAB_OCI_CONFIG_PROFILE:-${OCI_CLI_PROFILE:-}}" ]] || oci_options+=(--profile "${LAB_OCI_CONFIG_PROFILE:-${OCI_CLI_PROFILE}}") + [[ -z "${LAB_OCI_REGION:-}" ]] || oci_options+=(--region "${LAB_OCI_REGION}") + edge_id="$(oci_managed_edge_id)" || return 1 + instance_json="$("${oci_bin}" "${oci_options[@]}" compute instance get --instance-id "${edge_id}" --output json)" || return 1 + observed_id="$(printf '%s' "${instance_json}" | python3 -c 'import json,sys; print(json.load(sys.stdin)["data"]["id"])')" || return 1 + lifecycle="$(printf '%s' "${instance_json}" | python3 -c 'import json,sys; print(json.load(sys.stdin)["data"]["lifecycle-state"])')" || return 1 + if [[ "${observed_id}" != "${edge_id}" || "${lifecycle}" != RUNNING ]]; then + echo "Refusing restart: managed edge identity or RUNNING state does not match OCI." >&2 + return 1 + fi + printf 'Requesting OCI SOFTRESET for managed edge %s. Public edge services will be unavailable during reboot.\n' "${edge_id}" + "${oci_bin}" "${oci_options[@]}" compute instance action --instance-id "${edge_id}" \ + --action SOFTRESET --no-retry --query 'data."lifecycle-state"' --raw-output || return 1 + echo "Restart request accepted. OCI RUNNING alone does not confirm a reboot or service recovery." + echo "After the edge returns, run ./jeannie oci agent-status and check the public services." +} + +oci_agent_status() { + require_debian_server "oci agent-status" + oci_foundation_load_config || return 1 + if [[ $# -ne 0 ]]; then + echo "Usage: ./jeannie oci agent-status" >&2 + return 2 + fi + local oci_bin edge_id instance_json compartment_id + local -a oci_options=() + oci_bin="$(oci_cli_resolve)" || { echo "OCI CLI is not installed." >&2; return 1; } + [[ -z "${LAB_OCI_CONFIG_PROFILE:-${OCI_CLI_PROFILE:-}}" ]] || oci_options+=(--profile "${LAB_OCI_CONFIG_PROFILE:-${OCI_CLI_PROFILE}}") + [[ -z "${LAB_OCI_REGION:-}" ]] || oci_options+=(--region "${LAB_OCI_REGION}") + edge_id="$(oci_managed_edge_id)" || return 1 + instance_json="$("${oci_bin}" "${oci_options[@]}" compute instance get --instance-id "${edge_id}" --output json)" || return 1 + compartment_id="$(printf '%s' "${instance_json}" | python3 -c 'import json,sys; print(json.load(sys.stdin)["data"]["compartment-id"])')" || return 1 + printf 'Edge instance: %s\n' "${edge_id}" + printf '%s' "${instance_json}" | python3 -c 'import json,sys +c=json.load(sys.stdin)["data"].get("agent-config") or {} +print("All plugins disabled:", c.get("are-all-plugins-disabled")) +print("Management plugins disabled:", c.get("is-management-disabled")) +for p in c.get("plugins-config") or []: + if p.get("name") in ("Bastion", "Compute Instance Run Command"): + print("Configured:", p.get("name"), p.get("desired-state"))' || return 1 + "${oci_bin}" "${oci_options[@]}" instance-agent plugin list \ + --compartment-id "${compartment_id}" --instanceagent-id "${edge_id}" --output json | + python3 -c 'import json,sys +items=json.load(sys.stdin).get("data",[]) +for p in items: + if p.get("name") in ("Compute Instance Run Command", "Compute Instance Monitoring", "Bastion"): + print("Observed:", p.get("name"), p.get("status"), p.get("time-last-updated-utc")) +if not any(p.get("name")=="Compute Instance Run Command" and p.get("status")=="RUNNING" for p in items): + print("Run Command is not confirmed running; guest watchdog cannot repair a missing agent or OCI connectivity.") + sys.exit(1)' +} + oci_status() { require_debian_server "oci status" oci_foundation_load_config diff --git a/scripts/oci-foundation-resolve.py b/scripts/oci-foundation-resolve.py index 2558b1d..db71a2d 100644 --- a/scripts/oci-foundation-resolve.py +++ b/scripts/oci-foundation-resolve.py @@ -424,6 +424,27 @@ def validate_plan(plan): raise ValueError("Foundation would delete/replace: " + ", ".join(destructive)) +def review_edge_replacement(plan, state): + """Review only; this never authorizes or applies a replacement.""" + if plan.get("errored") or plan.get("complete") is False: + raise ValueError("Plan is errored or incomplete") + changes = [item for item in plan.get("resource_changes", []) + if item.get("change", {}).get("actions") != ["no-op"]] + if len(changes) != 1 or changes[0].get("address") != "oci_core_instance.edge[0]": + raise ValueError("Plan must change only oci_core_instance.edge[0]") + change = changes[0]["change"] + if change.get("actions") not in (["delete", "create"], ["create", "delete"]): + raise ValueError("Plan must replace the managed edge instance") + if change.get("importing"): + raise ValueError("Plan includes an import") + recorded_edge = resources(state).get("oci_core_instance.edge", {}).get("id") + planned_edge = (change.get("before") or {}).get("id") + if not recorded_edge or planned_edge != recorded_edge: + raise ValueError("Planned edge identity does not match the selected state") + print(f"Review only: plan replaces managed edge {recorded_edge}; no other resource actions.") + print("This does not authorize apply. Edge bootstrap, secure credentials, and DNS recovery remain required.") + + def reconcile(args): values = {k: v for k, v in os.environ.items() if k.startswith("LAB_")} state = read_state(state_path(values, args.repo)) @@ -649,7 +670,7 @@ def reconcile(args): def main(): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("action", choices=("load", "save", "reconcile", "edge", "discover", "check-plan")) + parser.add_argument("action", choices=("load", "save", "reconcile", "edge", "discover", "check-plan", "review-edge-plan")) parser.add_argument("--config", type=Path, default=Path.home() / ".config/homelab/oci-foundation.env") parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--names", nargs="*", default=[]) @@ -657,6 +678,7 @@ def main(): parser.add_argument("--kind", choices=("instance", "vcn", "bastion")) parser.add_argument("--name") parser.add_argument("--root") + parser.add_argument("--state", type=Path) args = parser.parse_args() names = set(args.names) if args.action == "load": @@ -677,6 +699,10 @@ def main(): print(found["id"]) else: sys.exit(1) + elif args.action == "review-edge-plan": + if args.state is None: + parser.error("review-edge-plan requires --state and plan JSON on stdin") + review_edge_replacement(json.load(sys.stdin), read_state(args.state)) else: validate_plan(json.loads(args.plan.read_text()))