71 Commits

Author SHA1 Message Date
taylanbakircioglu 64d42663cd fix(agent): stop installer self-kill in pre-installation cleanup (v1.8.4)
The Linux/macOS agent installer could abort during "pre-installation cleanup"
(terminal showed `Killing processes matching: haproxy-agent` then `Killed`,
returning to the prompt) when the install script's own command line contained
"haproxy-agent". The cleanup killed processes via `pgrep -f "$pattern"` starting
with the bare string "haproxy-agent", which also matched the running installer's
own command line and a sudo/PAM ancestor that the $$/$PPID self-exclusion did not
cover, so the installer terminated itself before installing.

- linux_install.sh / macos_install.sh: the cleanup kill loop now targets ONLY
  the installed agent - "$INSTALL_DIR/haproxy-agent" (the daemon binary path) and
  the agent service/label ("haproxy-agent.service" / "com.haproxy.agent") - never
  the bare "haproxy-agent" substring. Neither pattern can match the installer's
  own command line. The redundant bare pattern is dropped (the service is stopped
  separately, and the binary-path pattern still catches a running daemon).
- frontend (AgentManagement.js): name the downloaded scripts
  install-agent-<platform>.sh / uninstall-agent-<platform>.sh (matching the
  backend's suggested filename) - defense in depth so this cannot resurface.

Installer-only change. The running agent and its privilege model are unchanged
(it runs as root for HAProxy reload, config writes, keepalived, and self-upgrade).
The cleanup runs only on a full interactive install (gated by SKIP_TO_DAEMON), so
daemon mode, self-upgrade, and config/version apply are unaffected. Both agent
scripts kept in sync. Scripts parse on bash 4.2-5.2; full backend suite green.

Addresses #31.
2026-06-27 13:49:59 +03:00
taylanbakircioglu 27fbe48c4b fix(agent): tolerate empty system_info in heartbeat JSON (v1.8.3)
A self-hosted agent could fail every heartbeat with HTTP 400
`Invalid JSON: Expecting property name enclosed in double quotes` when the
system-info block it collects came back empty on an unusual host. The agent
builds the heartbeat JSON as text, so an empty `$system_info` collapsed the
`$system_info,` line to a bare comma and broke the payload.

- Agent script (linux + macos, kept in sync): guard the fragment-form
  register_agent and send_heartbeat builders so an empty system_info falls back
  to a valid key and can never emit a bare comma. Uses the most portable bash
  glob test (no POSIX class / pattern substitution; verified on bash 3.2-5.2 and
  on Ubuntu/Debian/Rocky/Alpine/Amazon Linux). True no-op for healthy agents.
- Backend heartbeat endpoint: parse the body as-is first and only run the
  malformed-JSON repair when parsing fails, so a valid heartbeat from any agent
  version is byte-for-byte untouched. The repair (now a testable helper) recovers
  a leading or doubled comma (the empty-system_info artifact) in addition to the
  existing empty-value / trailing-comma fixes.

No agent version bump; self-upgrade and daemon mode are unaffected. Healthy
agents of every version behave identically. Full backend suite green.

Addresses #31.
2026-06-25 14:42:34 +03:00
taylanbakircioglu c492b26bb1 feat(acme): DNS-01 challenge support with pluggable DNS providers (v1.8.0)
Add ACME DNS-01 (TXT-record) validation alongside the existing HTTP-01,
for internal/isolated clusters with no public port 80 and for wildcard
certificates. Opt-in via a global kill-switch (default off); HTTP-01 is
byte-for-byte unchanged, with zero agent or rendered-config changes.

- Pluggable DNS provider interface (Manual + Cloudflare). Per-account
  credentials are Fernet-encrypted at rest, verified on save, and never
  returned by the API or written to logs/events/error_detail.
- Non-blocking per-cycle orchestrator: publish (CAS) -> propagation grace
  (across cycles, no in-loop sleep) -> respond -> finalize/download, with a
  bounded fresh-order retry chain (1 original + 3 retries) on propagation lag.
- Manual flow: user publishes the TXT record and confirms; manual DNS-01
  cannot auto-renew unattended (auto-renew forced off and surfaced in the UI).
- Migration v8: additive, idempotent columns on letsencrypt_accounts/orders
  and acme_challenges, plus a new letsencrypt_account_dns_credentials table.
- Challenge-type-aware diagnostics (port80/routing/DNS checks skipped for
  DNS-01) and a DNS-01 event timeline in the order detail.
- Frontend: DNS-01 account + credentials management, cert wizard adaptation,
  order-detail TXT records + verify, orders/renewal Method columns, and a
  Settings kill-switch. README, release notes, and API docs updated.

Implements #35.
2026-06-24 02:24:33 +03:00
taylanbakircioglu a1192e602d feat: HA / VIP (Keepalived) management from the UI (#27)
Manage highly-available virtual IPs backed by Keepalived (VRRP) directly from the OpenManager
UI — no more SSHing into nodes to install/configure Keepalived by hand. Builds on the agent
pull-architecture: define the VIP centrally, click Apply, and the agents converge.

Highlights:
- New "HA / VIP" tab: create a virtual IP, pick a per-node interface, select which pool nodes
  participate (MASTER/BACKUP roles + priorities); live MASTER/BACKUP/FAULT per node.
- On Apply, agents install & configure Keepalived (unicast VRRP, cloud-safe default) across the
  major distros (Debian/Ubuntu, RHEL/CentOS/Alma/Rocky, Fedora, SUSE/openSUSE, Alpine) with a
  HAProxy health-check, so the VIP fails over automatically when HAProxy drops.
- Single-node (a managed floating IP without failover) and multi-node VRRP failover both work.
- VIP changes ride the standard Apply Management flow with the standard "View Change" diff.
- Approval-gated deletion (safety): deleting a running VIP is staged for approval and the VIP
  keeps running, untouched, until you approve it — an agent never tears a VIP down without an
  explicit human approval. Per-VIP Diagnostics view; opt-in package uninstall (only on nodes
  where OpenManager installed it). A node already running a hand-managed Keepalived is detected
  and never overwritten ("externally managed").
- Fully opt-in and backward compatible: nodes/clusters without a VIP are unaffected. Adds
  vip_instances + vip_members tables (idempotent SCHEMA_VERSION bump; existing data and
  passwords unaffected) and a `vip` RBAC permission group.
- Also includes a HAProxy config-generator robustness fix: auto-inject a stick-table when a
  frontend uses a stick counter (track-sc / sc_*_rate) but declares none.

On-prem / L2 (VRRP) scope; the UI notes the cloud caveat.
2026-06-07 01:52:20 +03:00
taylanbakircioglu f3d4fb11bb fix(agent): accept agent token (X-API-Key) on cluster read endpoints (Issue #22)
Assigning a HAProxy agent failed with '401: Authorization header missing'
on GET /api/clusters. A cluster-read hardening had made GET /api/clusters and
GET /api/clusters/{id} accept only a user JWT in the Authorization header;
agents authenticate with their agent token in the X-API-Key header, so the
token was never read.

Both endpoints now accept either a user JWT (Authorization) or an agent token
(X-API-Key via validate_agent_api_key), mirroring the existing dual-auth on
POST /api/agents/generate-install-script. Anonymous access is still rejected,
so the original hardening is preserved. The auth guard is placed before the
try block so the failure surfaces as a clean 401 (not the 500-wrapped-401 in
the report). Agent install scripts now consistently send the token via
X-API-Key (pre-flight cluster check on linux/macos, and macOS get_cluster_paths
which previously used the wrong Authorization: Bearer header).

Also normalizes the platform in the uninstall-script generator so macOS agents
(which report platform 'darwin') no longer get a 400 from
GET /api/agents/generate-uninstall-script/darwin.

version 1.6.0 -> 1.6.2.
2026-05-30 19:09:26 +03:00
taylanbakircioglu 02b1cb2bca feat: v1.5.0 — Site Wizard (Issue #14) + ACME Diagnostic Panel (Issue #13)
Closes #13, Closes #14.

This release squashes the v1.4.0 → v1.5.0 development line. v1.4.0
shipped the ACME stability & enterprise audit (Issues #10/#11/#12).
v1.5.0 builds on that foundation with two co-equal headline features
plus a 22-round audit campaign hardening the prior configuration
surface. License remains MIT for v1.5.0 (relicense to AGPL-3.0
lands in v1.5.2).

------------------------------------------------------------------
HEADLINE FEATURE A — ACME Diagnostic Panel (Issue #13)
------------------------------------------------------------------
A live pre-flight + post-failure diagnostic surface for every ACME
order, reachable from the ACME Automation page. The panel exists
to make ACME failures legible to operators who do NOT have shell
access to the API host.

Endpoints (`backend/routers/acme_diagnostics.py`):
  POST /api/letsencrypt/orders/{order_id}/diagnostics
       Run the full 5-check suite (DNS / port-80 / routing /
       account / agents) and humanize the order's `error_detail`
       (>=11 RFC-8555 problem types, backwards compatible with
       legacy plain-string failures).
  POST /api/letsencrypt/orders/{order_id}/diagnostics/
                                {check_id}/rerun
       Re-run a single check in place — used by the "Re-run"
       button on every row of the modal's pre-flight table.
  GET  /api/letsencrypt/orders/{order_id}/events
       Merged event timeline combining the typed
       `acme_order_events` rows with correlated
       `user_activity_logs` entries (resource_type =
       'letsencrypt_order' AND resource_id = order_id). The
       diagnostic modal auto-tails this timeline every 5 seconds
       while open.

Service-level checks (`backend/services/acme_diagnostics.py`):
  * DNS resolution via stdlib socket.gethostbyname_ex through
    run_in_executor (intentionally avoiding an aiodns runtime
    dep for v1.5.0).
  * Port-80 HEAD probe, target locked to the order's domains,
    success on HTTP 200 OR 404, warns on egress timeout
    (corp egress policies routinely blackhole outbound 80 —
    fail-hard would be too noisy).
  * SSRF guard: probe refuses non-public IPs and surfaces the
    skip in the diagnostic result; IPv4-mapped IPv6 normalisation
    closes the `::ffff:169.254.169.254` cloud-metadata vector.
  * HAProxy routing presence check: matches the order's
    cluster_ids to a port-80 HTTP frontend.
  * ACME account validity check against `letsencrypt_accounts`.
  * Agent presence check (>=1 active agent in target cluster).
  * Every sub-check wrapped in a wall-clock timeout to bound
    impact on the API event loop.

RBAC: ssl.read for run, ssl.read for events. Per-user 5/min rate
limit on both run and rerun, backed by the (user_id, action,
created_at DESC) composite index.

Frontend (`frontend/src/components/ACMEAutomation.js`):
  * "Diagnose" button on every order row + the existing
    "stuck order" warning row.
  * Modal with two tabs:
    - Pre-flight Checks (Antd Table with status pills + Re-run
      buttons + humanized error banner)
    - Event Log (Antd Timeline with auto-tail polling, scroll-
      to-bottom, pause-on-hover)
  * Correlation IDs surfaced in error banners and individual
    check fail details for backend-log lookup.

------------------------------------------------------------------
HEADLINE FEATURE B — Site Setup Wizard (Issue #14)
------------------------------------------------------------------
A single guided flow that creates a Backend + Servers + HTTP
Frontend (and optional HTTPS Frontend) in one atomic transaction.

Endpoints (`backend/routers/site_wizard.py`):
  POST /api/site-wizard/preview     — diff-preview the changeset
  POST /api/site-wizard/create      — atomic execute
  POST /api/site-wizard/reject      — clean rollback (including
                                       any wizard_staged ACME
                                       orders)
  GET  /api/site-wizard/drafts      — draft persistence
  PUT  /api/site-wizard/drafts/{id} — save/update
  DELETE /api/site-wizard/drafts/{id}

Feature surface:
  * One screen captures both backend (mode + servers) AND
    frontend (http + optional https + SSL mode) inputs.
  * SSL modes: ACME (new order, HTTP-01 only for v1.5.0),
    Upload (existing PEM), Existing (link to a stored cert),
    or None.
  * ACME-staged path: wizard_staged_until watermark on the
    `letsencrypt_orders` row defers finalisation until agent
    confirmation; per-mode reject cleanly cancels and rolls
    back the staged order.
  * Live diff preview against the cluster's current generated
    config (renderer-evolution noise stripped — track-sc<N>
    dedup, per-server cookie strip, defaults-cookie
    inheritance, listen-block flattening).
  * Draft persistence with PEM stripped at save time (private
    keys never round-trip through the drafts table).
  * Per-cluster multi-tenancy: drafts and wizard_staged orders
    are isolated to the creating user's cluster scope.

Frontend (`frontend/src/components/SiteWizard.js`):
  * 4-step Antd Steps flow: Backend → Frontend → SSL → Review.
  * Render the live diff preview inline before commit.
  * Antd Form-level validation mirrors backend Pydantic
    validators (numeric bounds, HAProxy reserved keywords, ALPN
    consistency, IPv6 scope-id, domain regex, server name
    dedup).

------------------------------------------------------------------
AUDIT CAMPAIGN — Rounds 1 → 22 (Bulgu #1#82)
------------------------------------------------------------------
v1.5.0 includes 22 adversarial review passes. Each round produced
its own commit set in the corporate development line; this squash
collapses those into the v1.5.0 release artefact. Highlights:

  Round 1-4   Site Wizard core: dry-run parity, single-line
              value injection guard, ACL -f pattern-file block,
              SSL parity, timeout regex, form-state pin.
  Round 5-7   defaults-cookie inheritance, server-named-cookie
              guard, fe/be mode mismatch, duplicate server
              names, health_check_uri + server_address
              validators.
  Round 8-10  cookie_name / cookie_options newline-injection
              guard, dry-run parity (round 9), TCP-mode HTTP-only
              feature blockers.
  Round 11    SSL name path traversal + health-check >= 1.
  Round 12-13 SSL & ACME deep dive (Bulgu #23-#32).
  Round 14    single-line value injection (Bulgu #33).
  Round 15-17 ACME multi-tenant UX, numeric bounds, HAProxy
              reserved keywords, ALPN/TLS consistency,
              all-backup, multi-domain & multi-user enterprise
              edges, drain/HSTS/post-completion (Bulgu
              #34-#53).
  Round 18-21 concurrency, agent state, TCP-mode HTTP-only,
              list size caps, IPv6 scope-id, preview account
              validation, TCP backend + balance uri reject
              (Bulgu #54-#61).
  Round 22    FE error visibility + 3x stale-data lockouts,
              referential integrity + cascade safety,
              authentication & authorization, multi-cluster
              isolation, apply_pending_changes concurrency,
              script injection + bulk import multi-tenancy,
              prefix-stripped signature comparison
              (Bulgu #62-#82).

------------------------------------------------------------------
NO CORPORATE-SPECIFIC ARTIFACTS
------------------------------------------------------------------
This squash deliberately sanitises corporate hostnames, container
registry references, and TLS secret names into generic
placeholders (`your-registry.example.com/your-org`,
`haproxy-openmanager*.example.com`, `wildcard-tls`,
`taylanbakircioglu/haproxy-openmanager-*`) so the public artefact
contains no internal infrastructure detail. Pilot / development
history that retained those values stays in the corporate fork
and is NOT part of this commit.
2026-05-14 00:04:19 +03:00
taylanbakircioglu 07942a82e8 feat: ACME stability & enterprise audit (v1.4.0) — fixes #10 #11 #12
Issue #10 — Silent timezone failure on ACME certificate save
- Normalize tz-aware expiry_date to UTC tz-naive before INSERT/UPDATE in
  ssl_certificates (TIMESTAMP WITHOUT TIME ZONE) — restores ACME download path

Issue #11 — Duplicate _acme_challenge_backend in generated config
- Generator guard: skip auto-append when backend already rendered
- Agent-sync filter: _should_sync_backend() drops system-managed backends and
  detaches their server rows to prevent orphans
- Restore filter: IGNORED_BACKENDS skips reserved names during cluster restore
- Parser warning: reserved_backend_names blocks accidental manual import
- Cleanup migration: removes orphan rows + cascading server entries (idempotent)

Issue #12 — Validated orders required manual completion
- New 60s background task complete_pending_acme_orders, flag-independent,
  multi-replica safe via FOR UPDATE SKIP LOCKED + 30s updated_at watermark
- Per-order pg_advisory_lock(0x41434D45, order_id) serializes UI-Complete and
  auto-task races; idempotency guard returns existing certificate cleanly
- retry_order endpoint reports in_progress: true within 30s window so the UI
  surfaces an info toast instead of duplicating CA requests
- ACMEAutomation surfaces stuck orders (status=valid && !ssl_certificate_id)
  with a one-click Complete action and Cancel fallback; conditional 30s polling

Other hardening
- ACME state machine error_detail persisted as structured JSON across challenge,
  finalize, download stages for actionable post-mortems
- CertificateRequest Pydantic model: domain regex + min_length/max_length and
  cluster_ids defaulting to all ACME-enabled clusters when "global" is selected
- Renewal cluster fallback now requires acme_enabled=TRUE in addition to active
- _complete_certificate preserves manual cluster assignments on renewal,
  surfaces cluster_errors, raises explicit error on missing private key
- Audit logging covers acme_certificate_requested/revoked, ca_chain_imported,
  account created/deactivated/purged, order retried/cancelled
- Settings UI exposes acme.staging_url_override for private test CAs (Pebble)
- Schema additions: acme_challenges.attempts (default 0) and last_attempt_at,
  index idx_letsencrypt_orders_status_updated; all migrations idempotent

Tests (41/41 passing)
- test_acme_expiry_normalize, test_acme_duplicate_backend,
  test_acme_state_machine, test_acme_pydantic_validation,
  test_acme_audit_logging, test_acme_concurrency

CI / packaging
- docker-build.yml reads version.json and pushes additional product-version
  tag (e.g. 1.4.0) alongside latest and timestamp build id

Closes #10
Closes #11
Closes #12
2026-05-06 23:53:43 +03:00
taylanbakircioglu cd4a94beb1 feat: agent IP/VIP live update + script update detection banner
- Agent scripts now detect and send ip_address in DAEMON heartbeat (Linux: ip route, macOS: ifconfig)
- Backend validates agent-reported IPs via ipaddress stdlib, COALESCE preserves existing on NULL
- IP/VIP change logging (non-critical, try/except wrapped) for operational visibility
- New source_file_hash column on agent_script_templates for reliable update detection
- Migration changed to ON CONFLICT DO NOTHING to prevent overwriting UI-customized scripts on restart
- GET /versions returns script_update_available flag (disk hash vs DB hash comparison with fallback)
- Frontend Alert banner warns users of new agent script versions and directs to Reset to Defaults
- Reset to Defaults and Popconfirm modals explicitly warn about custom script edit loss
- Full backward compatibility: old agents without ip_address field continue working unchanged

Made-with: Cursor
2026-04-17 10:50:51 +03:00
taylanbakircioglu 71c717364c fix: allow dot character in entity names for UI and backend validation
Bulk import accepted dots in frontend/backend/server names but UI and
backend validators rejected them with ^[a-zA-Z0-9_-]+$. After import,
entities with dots could not be edited. HAProxy itself allows dots in
section names, so the regex is expanded to ^[a-zA-Z0-9_.-]+$ across
all 12 validation points (5 React form rules, 1 ACL char-strip,
3 Pydantic validators, 1 WAF validator, 2 config-validator warnings).
2026-04-14 01:26:03 +03:00
taylanbakircioglu 7fffaddaf8 fix: bulk import should not inject hardcoded timeout defaults
When a backend block in haproxy.cfg does not specify explicit timeout
values, the bulk import was injecting hardcoded defaults (connect 10s,
server 60s, queue 60s) into the database. These then appeared in the
generated config and overrode the agent's defaults section. Now, only
explicitly declared timeouts are stored; omitted ones remain NULL so
the agent's existing defaults section stays in effect.
2026-04-13 05:52:31 +03:00
taylanbakircioglu 36fdba52bc fix: ACME setup guide accuracy, reject rollback, and UX improvements
- Step 3 (Enable ACME on Cluster) now shows a process icon instead of
  a misleading green checkmark when ACME is enabled but not yet applied.
  Per-cluster "(pending apply)" annotation for multi-cluster setups.
- Step 4 button and all /apply-management navigation buttons now say
  "Apply Changes" instead of "Configure" for clearer guidance.
- Setup Guide auto-selects the correct cluster before navigating to
  Apply Management, showing pending cluster names in alerts.
- Pending ACME disable changes are now correctly detected in Step 4
  even when acme_enabled is already FALSE in the database.
- Entity snapshot rollback for cluster ACME settings: reject correctly
  restores acme_enabled/acme_backend_url to pre-change values.
- Deduplication logic prevents "last wins" bug when multiple ACME
  toggles are rejected in sequence.
- Connection leak prevention with try/finally around conn2 in ACME
  config version creation.
- Step 4 branching uses boolean has_enabled instead of fragile string
  truthiness check.

Made-with: Cursor
2026-04-04 16:57:57 +03:00
taylanbakircioglu fabe7aba4c fix: prevent empty HAPROXY_CONFIG_PATH when get_cluster_paths() fails
Agent startup left HAPROXY_CONFIG_PATH empty when the /api/clusters jq
select() returned no output (e.g. transient API failure or cluster_id
mismatch). This caused "No existing HAProxy config found at: " errors
and partial config merge failures for newly added agents.

Three-layer fix:
1. Load HAProxy paths from config.json as baseline before get_cluster_paths()
2. Use local variables in get_cluster_paths() - only override globals when
   API returns non-empty values (defensive against jq select() empty output)
3. Dynamically update paths from /api/agents/{name}/config response in
   check_config_updates() - allows cluster path changes without reinstall

Applied to both linux_install.sh and macos_install.sh.

Made-with: Cursor
2026-04-03 00:42:58 +03:00
taylanbakircioglu 4082152312 fix: resolve stale keepalive state when keepalived stops
- Fix DB: COALESCE(NULLIF) prevented clearing stale MASTER/BACKUP state.
  Use CASE WHEN IS NOT NULL to distinguish absent fields (old agents)
  from empty fields (keepalived stopped) and properly clear to NULL.
- Fix Redis: explicitly delete cache key when keepalived stops instead
  of relying on 90s TTL expiry, preventing stale dashboard data.
- Fix agent scripts: SKIP_TO_DAEMON send_heartbeat now always sends
  keepalive_state/keepalive_ip fields (even empty) so backend can
  detect stopped keepalived and clear stale data.
- Fix legacy heartbeat endpoint: POST /{agent_id}/heartbeat now also
  updates keepalive_state and keepalive_ip fields.
- UI: add horizontal scroll to ClusterManagement table to prevent
  column overflow with new Keepalive column.
- UI: add VIP tooltip to Dashboard AgentStatusCard keepalive tag.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-18 20:41:17 +03:00
taylanbakircioglu b0feca3c2e feat: add keepalived VRRP state (MASTER/BACKUP) detection to agent heartbeat
- Add keepalive_state and keepalive_ip columns to agents table (migration + schema)
- Add keepalive fields to AgentHeartbeat Pydantic model (backward compatible)
- Update heartbeat endpoint to persist keepalive data to DB and cache in Redis
- Add multi-method keepalived detection in agent scripts (journalctl, log files, VIP check)
- Update dashboard-stats agents/status API with Redis-first keepalive lookup
- Update GET /api/agents to include keepalive_state and keepalive_ip
- Show MASTER/BACKUP tag in Dashboard AgentStatusCard
- Show keepalive info in Agent Management registered agents table
- Add Keepalive column to Cluster Management table with VIP search support

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-18 20:41:17 +03:00
taylanbakircioglu 0be3c299dd fix: serialize new_values in entity snapshot to prevent silent JSON failure
Root cause: SSL update passes expiry_date as Python datetime object in
new_values. json.dumps() fails on datetime, causing save_entity_snapshot
to return {} (empty). Entity snapshot is never saved in config_version
metadata, so reject/rollback can never find it to restore old values.

Fix: Apply same JSON serialization to new_values as old_values. Only
affects SSL certificates (only entity with datetime in new_values).
All other entity types (frontend, backend, server, waf) are unaffected
as their new_values contain only JSON-serializable types.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-17 16:36:27 +03:00
taylanbakircioglu 1f100d01e7 fix: SSL reject rollback, expiry calculation, and UI improvements
- SSL Reject: Remove conditional has_same_update_applied check, always
  rollback since Auto-Reject handles cross-cluster consistency
- SSL Rollback: Restore expiry_date by parsing ISO string back to datetime
- SSL UI: Add In Use filter toggle, fix Expiring Soon count using actual
  date calculation, smart Private Key content validation messages
- Remove emojis from log messages

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-17 16:36:27 +03:00
taylanbakircioglu 7dedd0f573 feat: SSL sync status tracking and smart reload optimization
- Add per-cluster SSL sync status tracking with APPLYING/SYNCED/PARTIAL states
- Add timeout detection (10min) for stalled SSL deployments showing PARTIAL status
- Add SSL-specific info in Apply Management dialog (cluster count, auto-apply notice)
- Add Deployment Status tab in SSL details showing per-cluster agent sync progress
- Implement SSL auto-reject (reject propagates to all clusters) and auto-undo
- Add conditional entity rollback for SSL reject (time-window based safety check)
- Filter REJECTED status from SSL last_config_status display
- Add pending_cluster_names to SSL list API response
- Optimize agent SSL reload: only trigger HAProxy reload when changed cert is
  actually referenced in the cluster's HAProxy config (grep -qF check), preventing
  unnecessary reloads on clusters that don't use the updated certificate
- Applied to all 4 SSL deploy paths: Linux/macOS standalone and daemon embedded modes

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-17 16:36:27 +03:00
taylanbakircioglu c19f0b5275 fix: SSL certificate updates now trigger HAProxy reload after self-upgrade
Root cause: After agent self-upgrade, the embedded daemon (SKIP_TO_DAEMON
block) runs instead of run_daemon(). HAPROXY_BIN and HAPROXY_CONFIG
variables were uninitialized before the daemon loop, causing SSL-triggered
HAProxy reloads to silently fail with empty path validation.

Changes:
- Initialize HAPROXY_BIN/HAPROXY_CONFIG before embedded daemon loop
- Add md5 checksum comparison in deploy_ssl_certificates() to detect
  actual cert file changes (avoid unnecessary writes and reloads)
- Add check_ssl_updates() for independent SSL sync every ~2.5 min
  in run_daemon(), independent of config version changes
- Add SSL-aware reload in check_config_updates(): if config validation
  fails but SSL certs changed, reload HAProxy with existing config
- Add "full" fetch mode to fetch_and_deploy_ssl_certificates() to
  bypass incremental timestamp filter for standalone SSL checks

Applied to both linux_install.sh and macos_install.sh.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-17 16:36:27 +03:00
taylanbakircioglu dc978f847d fix: prevent daemon crash-loop on exit 1 with retry-backoff mechanism
- Replace immediate exit 1 with retry-with-backoff in all daemon mode paths
  (dependency checks: 5 retries, 30/60/90/120/150s; config file: 5 retries, 15/30/45/60/75s)
- Make socat missing non-fatal in daemon mode (agent continues without stats)
- Add SystemD StartLimitBurst=5/StartLimitIntervalSec=120 for new installs
- Add macOS launchd ThrottleInterval=30 for new installs
- Fix Linux daemon fallback to installer mode (would hang on interactive read)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 20:04:42 +03:00
taylanbakircioglu 93602fa65d fix: check and install jq before cluster validation in agent scripts
Move jq dependency check to run before cluster validation which requires
it. Auto-install jq via the detected package manager (apt, dnf, yum,
zypper, apk for Linux; brew for macOS). Exit with clear manual install
instructions if automatic installation fails.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 20:04:42 +03:00
taylanbakircioglu cc10015952 fix: prevent install script from killing itself during cleanup
Same pgrep self-kill bug as uninstall scripts. When user downloads
install script as install-haproxy-agent.sh, pgrep -f "haproxy-agent"
matches the installer's own bash process and kills it before
installation starts. Now filters out INSTALLER_PID and PPID.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 16:45:29 +03:00
taylanbakircioglu 2d5c863735 fix: replace static protected paths with dynamic safety in uninstall
Instead of a hardcoded PROTECTED_PATHS list (varies per environment):
- safe_rm() blocks any path not containing "haproxy-agent"
- Process killer verifies ps output contains "haproxy-agent"
- Pre/post HAProxy integrity check via md5 hash comparison of config
  and service status diff (was running -> still running?)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 16:45:29 +03:00
taylanbakircioglu 8351a6439b fix: add HAProxy safety guards to uninstall scripts
- PROTECTED_PATHS array prevents accidental removal of haproxy.cfg,
  haproxy binary, haproxy.service, haproxy logs
- safe_rm() blocks any path not containing "haproxy-agent"
- Process killer verifies command line contains "haproxy-agent" and
  skips HAProxy master PID
- Binary removal validates filename is exactly "haproxy-agent"
- Pre-flight safety check reports HAProxy status before starting
- Post-uninstall HAProxy integrity check confirms nothing was touched

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 16:45:29 +03:00
taylanbakircioglu 08c500855e fix: rewrite uninstall scripts - simple and reliable
Replaced overcomplicated 380-line scripts with clean ~125-line versions.
Steps: stop service, kill processes (excluding self), remove binary,
remove config/logs/temps, verify. No emojis, no fragile helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 16:45:29 +03:00
taylanbakircioglu b7dde62972 fix: prevent uninstall script from killing itself via pgrep
pgrep -f "haproxy-agent" was matching the uninstall script's own
process (uninstall-haproxy-agent-linux.sh contains "haproxy-agent"),
causing the script to terminate itself at step 1/7 before reaching
file cleanup. Now filters out $$ (own PID) and $PPID from kill lists.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 16:45:29 +03:00
taylanbakircioglu 5cec6cf85a fix: remove emojis from all agent scripts and fix install/uninstall bugs
- Remove all emoji characters from install scripts (linux, macos)
- Rewrite uninstall scripts: remove set -e, fix safe_remove to always
  return 0, replace ((var++)) with $((var + 1)), fix local keyword
  usage, add comprehensive cleanup including config.json
- Fix install script QUIET_MODE/DAEMON_MODE detection to correctly
  handle interactive runs when old config.json exists

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 16:45:29 +03:00
taylanbakircioglu eac00b3e39 fix: consistent section header detection in listen extraction
Additional fix for listen block extraction:
- Section boundary check now uses ([[:space:]]|$) pattern
- Previously only checked [[:space:]], missing 'defaults' at end of line
- Ensures listen extraction stops correctly at any section header

Pattern consistency verified across all 4 locations:
- Linux install mode: global, defaults, listen extraction ✓
- Linux daemon mode: global, defaults, listen extraction ✓
- macOS install mode: global, defaults, listen extraction ✓
- macOS daemon mode: global, defaults, listen extraction ✓

Edge cases tested:
- Named defaults (defaults http): works correctly
- Multiple listen blocks: all preserved
- Tab characters: handled by [[:space:]]
- User's actual config structure: produces clean merge

No impact on other agent functions (self-upgrade, metrics, etc.)
2026-01-26 15:25:16 +03:00
taylanbakircioglu 25408a618e fix: awk patterns now match keywords at end of line
CRITICAL BUG FIX:
- Previous pattern `/^defaults[[:space:]]/` required whitespace after keyword
- HAProxy allows `defaults` without a name (no trailing whitespace)
- Pattern failed to match, causing global extraction to include defaults section

New pattern uses `([[:space:]]|$)`:
- Matches keyword followed by whitespace OR end of line
- `defaults` (no name) now correctly triggers exit
- `defaults http` (named) also correctly triggers exit

Test results:
- Old pattern: extracted 8 lines (included defaults) 
- New pattern: extracted 4 lines (stopped at defaults) 
2026-01-26 15:25:16 +03:00
taylanbakircioglu 995d87df43 fix: defaults extraction captures only first defaults section
CRITICAL BUG FIX:
- Previous awk pattern allowed multiple defaults sections to be captured
- Pattern `!/^defaults/` meant "don't exit if line IS defaults"
- This caused duplicate defaults when config had listen before defaults

New pattern uses `started` flag:
- First `defaults` line: set started=1, begin capturing
- Second `defaults` line: started is set, EXIT immediately
- Any `frontend/backend/listen`: started is set, EXIT

Also includes: debug logging for validation error storage with fallback

Tested scenarios:
- Normal config (defaults → listen → frontend): ✓
- Listen before defaults: ✓
- Two defaults sections: ✓ Only first captured
- No defaults section: ✓ Empty output
- Defaults at end of file: ✓
- Empty defaults section: ✓
2026-01-26 15:25:15 +03:00
taylanbakircioglu 4a6bc1b139 fix: global section extraction includes listen blocks when listen comes before defaults
Bug: When haproxy.cfg has 'listen stats' BEFORE 'defaults' section,
the global extraction incorrectly included listen stats because it
only stopped at 'defaults', not at any section header.

Fix: Changed extraction to stop at ANY section (defaults/listen/frontend/backend)
This prevents duplicate listen blocks in merged config.

Root cause of 'proxy stats has same name as proxy stats' HAProxy validation error.
2026-01-26 15:25:15 +03:00
taylanbakircioglu e75bfdf706 feat: dynamic HAProxy binary path from cluster configuration
- /api/agents/{name}/config now returns haproxy_bin_path, haproxy_config_path, stats_socket_path from cluster
- Agent daemon uses these dynamic paths from API response for validation
- Fallback to local config file if API values not present
- Allows cluster admin to change paths without reinstalling agents

This fixes validation when HAProxy binary is in non-standard location
2026-01-26 15:25:15 +03:00
taylanbakircioglu 97e32114e0 fix: translate Turkish error messages to English
- Updated SUGGESTION_TEMPLATES in haproxy_error_parser.py
- Fixed fallback error messages in cluster.py
- Product language should be English throughout
2026-01-26 15:25:15 +03:00
taylanbakircioglu ecbaebf451 feat: report invalid config format errors to backend for UI display
When config content doesn't look like valid HAProxy config (missing
global/defaults/frontend/backend/listen keywords), agent now reports
this to backend via config-validation-failed endpoint.

This catches backend-side config generation errors (like Python
exceptions) that prevented actual HAProxy config from being generated.

Changes:
- Add invalid config format detection and reporting in daemon mode
- Use same curl pattern as existing HAProxy validation failure reporting
- Same endpoint, headers, error handling, and spam prevention
- Follows exact existing pattern for consistency
- Does not affect self-upgrade flow (runs before upgrade check)

Both linux and macos scripts updated identically.
2026-01-26 15:25:15 +03:00
taylanbakircioglu 5947caa46d fix: move uninstall scripts to backend/utils/agent_scripts for deployment
- Copy uninstall-agent-linux.sh and uninstall-agent-macos.sh to
  backend/utils/agent_scripts/ (same location as install scripts)
- Update generate-uninstall-script endpoint to use the same path
  pattern as working install script endpoint
- Add container-specific fallback paths for robustness
- Add debug logging to track which path is used

Fixes 404 error when fetching uninstall script in production
where /utils/ directory at project root is not deployed.
2026-01-26 15:25:15 +03:00
taylanbakircioglu 8076f3fcfd feat: add intelligent HAProxy validation error display in UI
- Add haproxy_error_parser.py: Parses HAProxy validation errors with
  confidence scoring, extracts entity type/name, line number, error type
- Add ValidationErrorModal.js: Rich modal with parsed error summary,
  quick fix suggestions, and manual troubleshooting guide
- Update cluster.py: Integrate error parser into agent-sync and
  config-versions endpoints with graceful fallback
- Update ApplyManagement.js: Add validation error banner with quick
  navigation buttons and error detail modal
- Update FrontendManagement.js & BackendServers.js: Handle URL params
  for deep-linking to entity edit forms with field highlighting

Enables users to see actionable validation failure details directly
in the UI without needing server access for debugging.
2026-01-26 15:25:15 +03:00
taylanbakircioglu 851377aedf feat: Add HAProxy proxy name collision prevention system
- Add preserved_listen_blocks column to agents table for storing agent's local listen block names
- Implement reserved names check (stats, monitoring, admin, etc.) for frontend/backend creation
- Add dynamic collision detection against agent's preserved listen blocks
- Apply collision checks to CREATE, UPDATE endpoints and bulk import
- Add debug mode for failed config validation (saves to /tmp/haproxy-failed-*.cfg)
- Fix JSON character stripping for ACL and use_backend rules
- Remove collision protection from agent scripts (now handled by backend)
- All collision checks wrapped in try-except for backwards compatibility
2026-01-26 15:25:15 +03:00
taylanbakircioglu 5d054f3426 feat: Add random and first balance methods support
- Add 'random' and 'first' options to backend balance method selector
- Add balance method validation in config parser with warning for unknown methods
- Update API documentation with all supported balance algorithms
2026-01-26 15:25:15 +03:00
taylanbakircioglu 81d2b3b8d5 feat: Display HAProxy version in Agent Management page
- Add haproxy_version field to heartbeat payload in Linux agent script
- Add haproxy_version field to heartbeat payload in macOS agent script
- Display HAProxy version below IP address in Registered Agents list
- Safe extraction with fallback to 'unknown' if haproxy command fails
- Version is updated on every heartbeat (30s interval)
- Green color styling for easy visibility

Backend already supports haproxy_version field in AgentHeartbeat model
and saves it to database on each heartbeat.
2025-12-23 13:28:29 +03:00
Taylan Bakırcıoğlu 589f865f59 fix(ssl): rollback support + improved ALPN validation error message
PART 1: Rollback Support for SSL Advanced Options
===================================================
Problem: SSL advanced options lost on reject/rollback operations

Root Cause:
- Snapshot creation uses SELECT * (includes all fields) 
- old_values contains SSL advanced options 
- Rollback UPDATE did NOT restore SSL fields 

Impact - Frontend:
- User changes ssl_alpn, then clicks Reject
- Rollback skipped: ssl_alpn, ssl_npn, ssl_ciphers, ssl_ciphersuites, ssl_min_ver, ssl_max_ver, ssl_strict_sni
- Result: All SSL advanced options lost (set to NULL)

Impact - Backend Server:
- User changes ssl_min_ver='TLSv1.2', then clicks Reject
- Rollback skipped: ssl_sni, ssl_min_ver, ssl_max_ver, ssl_ciphers
- Result: Security issue - TLS version constraints removed!

Fix:
- backend/utils/entity_snapshot.py line 285-286: Added 7 frontend SSL fields to rollback UPDATE
- backend/utils/entity_snapshot.py line 458: Added 4 server SSL fields to rollback UPDATE

PART 2: Improved ALPN Validation Error Message
===============================================
Problem: User enters 'http/2' in ALPN field, gets generic error

User feedback: Tried 'h2,http/1.1,http/2' → validation error not clear

Root Cause:
- ALPN standard uses 'h2' for HTTP/2 (not 'http/2')
- Validator rejected 'http/2' but didn't explain the correct format

Fix:
- backend/models/frontend.py line 255-260: Detect common mistakes (http/2, http2, http-2)
- Provide helpful error: 'For HTTP/2, use "h2" (not "http/2")'

Before:
  "Invalid ALPN protocol: http/2. Valid protocols: h2, http/1.1, ..."

After:
  "Invalid ALPN protocol: http/2. For HTTP/2, use 'h2' (not 'http/2'). Valid protocols: ..."

Testing:
1. Rollback test: Edit frontend SSL, reject, verify SSL fields restored
2. Validation test: Enter 'http/2', verify friendly error message

Files Changed:
- backend/utils/entity_snapshot.py: _rollback_update() for frontend and server
- backend/models/frontend.py: validate_alpn() with better error messages
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 132b59bcd7 feat(agent): preserve failed HAProxy configs for debugging (TESTED)
PROBLEM:
- When HAProxy validation fails, /tmp/haproxy-new-config.cfg is deleted
- Admins cannot inspect the failed config to diagnose syntax errors
- Debugging validation failures requires database queries

SOLUTION:
- Save failed configs with timestamp: /tmp/haproxy-failed-{version}-{timestamp}.cfg
- Automatic cleanup: keeps last 5 failed configs, deletes older ones
- Clear log messages with debug commands

IMPLEMENTATION:
- Minimal change in validation failed branch only
- Uses mv instead of rm for failed configs
- Successful configs still cleaned up (already copied to haproxy.cfg)
- TESTED: bash -n syntax validation passed for both scripts

BENEFITS:
- Easy inspection: cat /tmp/haproxy-failed-*.cfg
- Manual validation: haproxy -c -f /tmp/haproxy-failed-*.cfg
- Identifies config generation bugs quickly
- No disk space issues (auto-cleanup)

DEPLOYMENT:
- Zero risk: only affects validation failure path
- Use Script Management UI -> Reset to Default
- Then upgrade agents via Script Management

EXAMPLE LOG:
[INFO] DAEMON: Failed config saved to: /tmp/haproxy-failed-apply-consolidated-1763478044-20251118-150057.cfg
[INFO] DAEMON: Debug: cat /tmp/haproxy-failed-apply-consolidated-1763478044-20251118-150057.cfg
[INFO] DAEMON: Debug: haproxy -c -f /tmp/haproxy-failed-apply-consolidated-1763478044-20251118-150057.cfg
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 7492d85649 FIX: Multiple SSL certificates & advanced params parsing
CRITICAL BUG FIX: Only 1 SSL cert matched instead of 3 for public_ssl

ROOT CAUSE:
- Parser only stored first cert path (ssl_cert_path)
- Bulk import SSL matching only checked single path
- ssl_certificate_ids = [2] (should be [2,3,4] for 3 certs)
- ssl_alpn = NULL (should be 'h2,http/1.1')

SOLUTION:
1. Added ssl_cert_paths List[str] to ParsedFrontend
2. Parser now stores ALL cert paths from bind directive
3. Bulk import loops through all cert paths for matching
4. SSL advanced options (alpn, npn, ciphers, etc.) included in frontends_data

EXAMPLE BIND DIRECTIVE:
bind 0.0.0.0:8443 ssl
  crt /etc/ssl/certs/example-cert1.pem
  crt /etc/ssl/certs/demo-cluster-cert.pem
  crt /etc/ssl/certs/example-cert3.pem
  alpn h2,http/1.1

BEFORE:
- ssl_certificate_ids: [2]  (only first cert)
- ssl_alpn: NULL            (not passed to bulk import)

AFTER:
- ssl_certificate_ids: [2, 3, 4]  (all 3 certs matched)
- ssl_alpn: 'h2,http/1.1'         (parsed & stored)

IMPACT:
- Multi-SSL frontends correctly imported
- SSL advanced params preserved & editable in UI
- SNI-based routing works correctly
- HTTP/2 ALPN negotiation preserved

TESTING:
- Parser: 3 crt paths → ssl_cert_paths = [path1, path2, path3]
- Matching: 3 paths → 3 IDs (if all SYNCED)
- Database: ssl_certificate_ids JSONB = [2,3,4]

Ref: demo-cluster public_ssl frontend issue
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 5bd75c9614 ENHANCEMENT: Robust Multi-Value SSL Parameter Parsing in Bulk Import
🔧 IMPROVEMENT: Handle Quoted and Complex SSL Values

PROBLEM:
- Bulk import parser used simple line.split() for SSL parameters
- Failed to handle quoted values: ciphers "ECDHE-RSA:ECDHE-ECDSA:!MD5"
- Long cipher lists could be incorrectly parsed
- Edge cases with special characters not handled

SOLUTION - SHLEX PARSING:
 Frontend bind parsing:
   - Changed from line.split() to shlex.split()
   - Handles quoted values correctly
   - Removes quotes automatically
   - Fallback to simple split if malformed

 Backend server parsing:
   - Enhanced regex patterns for SSL params
   - Supports both quoted and unquoted values
   - Pattern: (?:"([^"]+)"|(\S+))
   - Applies to: sni, ssl-min-ver, ssl-max-ver, ciphers

EXAMPLES NOW SUPPORTED:

Frontend:
  bind :443 ssl crt cert.pem ciphers "ECDHE-RSA:ECDHE-ECDSA:!MD5:!aNULL" alpn "h2,http/1.1"
  → ciphers: ECDHE-RSA:ECDHE-ECDSA:!MD5:!aNULL (quotes removed)
  → alpn: h2,http/1.1 (quotes removed)

Backend:
  server s1 10.1.1.1:443 ssl sni "backend.example.com" ciphers "ECDHE-RSA:ECDHE-ECDSA"
  → sni: backend.example.com
  → ciphers: ECDHE-RSA:ECDHE-ECDSA

BENEFITS:
-  Production HAProxy configs with quoted values now parse correctly
-  Long cipher lists (100+ chars) handled properly
-  Special characters (!MD5, @STRENGTH) in cipher lists supported
-  Backward compatible (unquoted values still work)
-  Robust error handling (fallback to simple split)

TESTED WITH:
- User's problematic config with multiple crt + alpn
- Quoted cipher suites
- Mixed quoted/unquoted parameters
- Edge cases with special characters

This ensures bulk import handles ALL real-world HAProxy configurations correctly!
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu b212fb92bc Add SSL Advanced Options support (Backend) - Part 1
FEATURE: Complete SSL Advanced Options implementation for frontend and backend server SSL

 DATABASE:
- Added SSL parameter columns to frontends table:
  * ssl_alpn, ssl_npn, ssl_ciphers, ssl_ciphersuites
  * ssl_min_ver, ssl_max_ver, ssl_strict_sni
- Added SSL parameter columns to backend_servers table:
  * ssl_sni, ssl_min_ver, ssl_max_ver, ssl_ciphers
- Migration functions: add_ssl_advanced_options_to_frontends() and add_ssl_advanced_options_to_servers()

 MODELS:
- FrontendConfig: Added 7 new SSL fields for bind parameters
- ServerConfig: Added 4 new SSL fields for server parameters
- AgentHeartbeat: Added system_info field (fixes HTTP 422 validation error)

 BULK IMPORT PARSER:
- Parse alpn, npn, ciphers, ciphersuites, ssl-min-ver, ssl-max-ver, strict-sni from bind lines
- Parse sni, ssl-min-ver, ssl-max-ver, ciphers from server lines
- Store parsed values in frontend/server objects
- User-friendly warnings about imported SSL parameters

 CONFIG GENERATOR:
- Generate bind lines with SSL advanced options: 'bind :443 ssl crt file.pem alpn h2,http/1.1 ciphers ...'
- Generate server lines with SSL advanced options: 'server s1 addr:port ssl sni hostname ssl-min-ver TLSv1.2'
- Support both NEW MODE (multiple certs) and OLD MODE (single cert)

USER IMPACT:
- Bulk import now correctly parses SSL configs with alpn/npn/ciphers
- SSL parameters preserved during import (not lost anymore)
- Agent heartbeat fixed (no more offline agents)
- Ready for UI implementation (next commit)

EXAMPLE USAGE:
Frontend: bind 0.0.0.0:8443 ssl crt cert1.pem crt cert2.pem alpn h2,http/1.1
Server: server s1 10.1.1.1:443 ssl verify required sni backend.example.com ssl-min-ver TLSv1.2

NEXT: Frontend UI components for editing these SSL options
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 5c1d2e11f9 Fix agent offline issue and bulk import SSL parsing
CRITICAL FIXES:
1. Agent Heartbeat Validation Error (HTTP 422)
   - Added missing 'system_info' field to AgentHeartbeat model
   - Agents were sending system_info but backend model didn't accept it
   - No agent script update needed - agents already send this field

2. Bulk Import SSL Parser Enhancement
   - Fixed parsing of multiple SSL certificates with alpn/npn parameters
   - Example: 'bind :443 ssl crt cert1.pem crt cert2.pem crt cert3.pem alpn h2,http/1.1'
   - Old parser stopped at first whitespace after crt path
   - New parser extracts all crt paths even with alpn/npn/ciphers after them
   - Added user-friendly warning for SSL parameters (alpn, npn, ciphers) that won't be imported

TECHNICAL DETAILS:
- backend/models/agent.py: Added system_info: Optional[Dict[str, Any]]
- backend/utils/haproxy_config_parser.py: Enhanced SSL bind parsing logic
  * Parse bind line by splitting and iterating through parts
  * Extract all crt paths before hitting SSL parameters
  * Detect and warn about alpn, npn, ciphers, ciphersuites parameters
  * Inform user these advanced options should be configured manually

USER IMPACT:
- Agents will come online after backend deployment (no reinstall needed)
- Bulk import will correctly parse configs with multiple SSL certs + alpn
- Clear warnings shown in UI about SSL parameters not imported
2025-11-18 21:58:05 +03:00
taylanbakircioglu c979ea867d fix: Remove set -e from agent scripts for production stability
PRODUCTION FIX: Prevent agent crashes from command failures

PROBLEM: set -e causes immediate exit on any command failure

The 'set -e' directive at the beginning of agent scripts caused agents to exit
immediately when ANY command returned a non-zero exit code. This was causing
production instability:

- Agent exits unexpectedly on minor errors
- systemd restarts agent continuously
- Creates restart loops
- Prevents agent from reaching daemon mode
- Configuration updates lost
- Metrics collection interrupted

EXAMPLES OF TRIGGERS:
- DNS lookup failures
- Temporary network issues
- HAProxy stats socket unavailable
- File system temporarily busy
- Any non-critical command failure

SOLUTION: Remove 'set -e' and rely on explicit error handling

Instead of crashing on errors, agents now:
- Log errors with context
- Continue running in daemon mode
- Handle errors gracefully
- Maintain service availability
- Only exit on critical failures (explicitly coded)

DEPLOYMENT STRATEGY:
1. Manual temporary fix: Comment out 'set -e' on agent servers
2. UI-driven upgrade: Deploy new script version (1.0.12)
3. Result: Stable agents with proper error handling

PRODUCTION IMPACT:
- 15/15 production agents upgraded successfully
- No agent crashes or restart loops
- All configuration updates working
- Metrics collection stable
- Zero downtime deployment
2025-11-17 20:22:00 +03:00
taylanbakircioglu e1fecde331 fix: Remove misleading upgrade completion heartbeat causing agent restart loop
CRITICAL PRODUCTION BUG: Agent stuck in restart loop after upgrade

SYMPTOMS:
- Agents continuously restarting every ~30 seconds
- Log shows: "Sending upgrade completion heartbeat..."
- Log shows: "Agent upgrade completed successfully"
- systemd restarts agent immediately after
- Agents never reach daemon loop
- Configuration updates not received
- Entity updates not applied

ROOT CAUSE:
- Agent script v1.0.10 had misleading "upgrade completion heartbeat"
- This heartbeat was sent EVERY time daemon started
- After sending, script would exit (expecting systemd restart)
- systemd would restart agent → infinite loop
- Agent never reached check_agent_upgrade() or check_config_updates()

MISLEADING CODE (REMOVED):

SOLUTION:
- Removed "upgrade completion heartbeat" from daemon startup
- Agent sends normal heartbeat in daemon loop (every 30s)
- No special "upgrade completion" needed
- Agent stays in daemon mode continuously
- systemd only restarts on actual failures

IMPACT:
- Agents no longer restart in loop
- Configuration updates work normally
- Entity updates applied successfully
- Upgrade process works correctly
- Production stability restored
2025-11-17 20:21:40 +03:00
taylanbakircioglu e87e279580 fix: Production-safe heartbeat using temp files for unlimited payload size
PRODUCTION ENHANCEMENT: Handle extremely large stats CSV payloads

IMPROVEMENT OVER PREVIOUS FIX:
- Previous: Temp file for response only
- Now: Temp file for BOTH payload and response
- Reason: Very large payloads (>1MB) still hit argument limits

PRODUCTION SCENARIO:
- Large HAProxy instances with 100+ backends
- Stats CSV can exceed 1MB in production
- curl --data argument hits system limits
- Need temp file for payload itself

SOLUTION:
- Write heartbeat_payload to temp file
- Use curl --data-binary @temp_payload
- Write response to separate temp file
- Read HTTP code and response body
- Cleanup both temp files

BENEFITS:
- Unlimited payload size support
- No argument list limits
- Production-tested and safe
- Backward compatible

FILES CHANGED:
- backend/utils/agent_scripts/linux_install.sh
- backend/utils/agent_scripts/macos_install.sh
- Updated both embedded daemon (Line ~1099) and installer (Line ~2367)
2025-11-17 20:21:12 +03:00
taylanbakircioglu 30a4424f61 fix: Use temp file for heartbeat to avoid argument list too long error
PRODUCTION BUG: Argument list too long when sending large stats CSV

ERROR MESSAGE:
"Heartbeat failed (HTTP /usr/local/bin/haproxy-agent: line 417: /usr/bin/curl: Argument list too long)"

ROOT CAUSE:
- curl output capture exceeded system argument list limit
- Large stats CSV (>200KB, production can be >1MB)
- Shell variable assignment hit system limits

SOLUTION:
- Redirect curl output to temp file (/tmp/heartbeat_response_$$.txt)
- Read HTTP code and response body from temp file
- Cleanup temp file immediately after use

BENEFITS:
- No size limit on HTTP responses
- Production-safe for large HAProxy instances
- Better error handling with detailed logging

FILES CHANGED:
- backend/utils/agent_scripts/linux_install.sh
- backend/utils/agent_scripts/macos_install.sh
- Updated both embedded daemon and installer functions
2025-11-17 20:20:54 +03:00
taylanbakircioglu 4f2405e57a fix: Update embedded daemon heartbeat with HTTP error logging
CRITICAL FIX: Embedded daemon section needed same HTTP error logging

PROBLEM:
- Agent install script embeds daemon via heredoc (Line ~755-1999)
- Previous commit only updated installer functions, not embedded daemon
- Agents still showed old heartbeat error format

SOLUTION:
- Updated send_heartbeat() in embedded daemon section
- Added HTTP status code checking
- Added backend error response logging
- Added warning comment about embedded daemon updates

IMPORTANT:
- When updating agent functionality, BOTH sections must be updated:
  1. Embedded daemon (Line 755-1999)
  2. Installer functions (Line 2000+)

PRODUCTION IMPACT:
- Agents now log detailed HTTP errors in embedded daemon mode
- Better troubleshooting for heartbeat failures
- Consistent error reporting across all agent modes
2025-11-17 20:20:34 +03:00
taylanbakircioglu e0fb7180ae fix: Agent heartbeat cluster-pool auto-healing + global token support
MAIN BUG FIX:
- Agent offline issue resolved (cluster created before pool scenario)
- 2-method cluster lookup: pool_id -> cluster_id fallback
- Auto-healing: pool_id NULL automatically corrected on first heartbeat

SECURITY & VALIDATION:
- Removed pool-based security check (token is globally usable)
- Pool-cluster validation for new agents (frontend + backend)
- Relaxed validation for agent upgrades (fallback pool_id tolerated)

AGENT IMPROVEMENTS:
- HTTP error logging in agent scripts (curl status code check)
- Detailed backend error response logging
- Better troubleshooting capabilities

PRODUCTION SAFE:
- Backward compatible (no breaking changes)
- Existing agents unaffected (Method 1 priority)
- Agent upgrades work (relaxed validation)
- Global token model preserved (cross-pool usage OK)
2025-11-17 20:20:09 +03:00