Skip to content

feat: server monitoring metrics - #77

Merged
loadinglucian merged 4 commits into
mainfrom
feat/server-monitoring-metrics
Nov 10, 2025
Merged

feat: server monitoring metrics#77
loadinglucian merged 4 commits into
mainfrom
feat/server-monitoring-metrics

Conversation

@loadinglucian

@loadinglucian loadinglucian commented Nov 10, 2025

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Server info dashboard now shows Caddy and PHP-FPM metrics (version, uptime, requests, memory, pools/processes, queues, slow/max indicators)
    • Demo site provisioning now creates a dedicated site config and demo site files
    • Bun runtime installation added
  • Improvements

    • Robust package-manager handling with retry/lock wait
    • Repository and PHP/Caddy setup enhanced; PHP-FPM handling improved
    • Deployer user, SSH key, directories and permission management added; clearer setup guidance

- Create modular Caddy configuration with conf.d/sites/ directory
- Add localhost-only monitoring endpoints (PHP-FPM status)
- Enable PHP-FPM status page in pool configuration
- Update demo-site to use new modular config structure
- Improve code organization with better section headers
- Query Caddy admin API for version, uptime, requests, memory
- Query PHP-FPM status endpoint for pool stats and performance metrics
- Extract metrics using curl and text parsing (no jq dependency)
- Output metrics in YAML format for server info command
- Display Caddy metrics: version, uptime, requests, memory
- Display PHP-FPM metrics: pool, processes, queue, performance indicators
- Add formatUptime helper for human-readable uptime display
- Highlight warnings for queue backlog and performance issues
@coderabbitai

coderabbitai Bot commented Nov 10, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds server monitoring display for Caddy and PHP‑FPM in the PHP trait, introduces Caddy/PHP‑FPM metrics collection and YAML exposure, restructures demo-site provisioning with a dedicated Caddy site config, and significantly expands the server-install playbook with repository, package, Caddy/Bun, and deploy-user/key setup.

Changes

Cohort / File(s) Summary
Server Monitoring Display
app/Traits/ServersTrait.php
Adds UI blocks in displayServerInfo() to render Caddy and PHP‑FPM metrics (version, uptime, requests, memory, pool, processes, queues, slow/max indicators). Adds private function formatUptime(int $seconds): string. All extractions guarded by existence/type checks; only non-empty values displayed.
Demo Site Provisioning
playbooks/demo-site.sh
Reworks provisioning: requires preconfigured deployer user and Caddy structure, validates deployer/home, creates demo site files/dirs, sets ownership/permissions, and replaces configure_caddy() with configure_demo_site() writing /etc/caddy/conf.d/sites/demo.caddy (logging + PHP‑FPM integration). Updates main flow and output key to demo_site_configured.
Server Metrics Collection
playbooks/server-info.sh
Adds get_caddy_metrics() and get_php_fpm_metrics() returning tab-separated metrics; updates main flow to call these, parse results, and extend DEPLOYER_OUTPUT_FILE with caddy and php_fpm sections (availability, version/pool, uptime_seconds, requests, memory, process counts, queues, slow requests). Adjusts detect_family() usage to internal positional distro handling.
Server Installation & Infrastructure
playbooks/server-install.sh
Large expansion: adds dpkg/apt locking helpers (wait_for_dpkg_lock, apt_get_with_retry), setup_repositories() for Caddy/PHP, install_bun(), setup_caddy_structure(), deployer/user/group management (ensure_deployer_user, configure_deployer_groups, setup_deploy_user), deploy key and directories (setup_deploy_key, setup_deploy_directories), validate_php_version(), and reorganizes install_all_packages() and main flow to integrate these tasks and record them in YAML.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant SI as server-info.sh
    participant C as Caddy
    participant P as PHP-FPM
    participant Y as DEPLOYER_OUTPUT_FILE (YAML)

    SI->>C: get_caddy_metrics() (metrics endpoint / status)
    C-->>SI: tab-separated metrics (version, uptime, requests, memory, sites, domains)
    SI->>P: get_php_fpm_metrics() (status socket/http)
    P-->>SI: tab-separated metrics (pool, uptime, accepted, queues, processes, slow)
    SI->>Y: parse & write `caddy` and `php_fpm` fields
    note over SI,Y: New YAML sections expose collected metrics
Loading
sequenceDiagram
    autonumber
    participant INSTALL as server-install.sh
    participant PKG as apt/dpkg
    participant REPO as repo servers
    participant CADDY as Caddy setup
    participant USER as deployer user & keys

    INSTALL->>PKG: wait_for_dpkg_lock() / apt_get_with_retry()
    INSTALL->>REPO: setup_repositories() (Caddy, PHP)
    INSTALL->>PKG: install_all_packages() (PHP 8.4, PHP-FPM, Caddy deps)
    INSTALL->>CADDY: setup_caddy_structure() (dirs, Caddyfile, status)
    INSTALL->>USER: ensure_deployer_user(), setup_deploy_user(), setup_deploy_key()
    INSTALL->>PKG: enable/start services (php-fpm, caddy)
    note right of INSTALL: Tasks recorded in output YAML
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Key attention areas:

  • playbooks/server-install.sh: many new functions touching package management, repo setup, user/group/perm changes, SSH key generation.
  • playbooks/server-info.sh: metrics collection/parsing and YAML mapping; verify endpoints and parsing resilience.
  • playbooks/demo-site.sh: Caddy site config generation, path/permission assumptions.
  • app/Traits/ServersTrait.php: new display logic and uptime formatting—ensure type safety and HTML formatting escapes.

Possibly related PRs

  • bigpixelrocket/deployer-php#75 — Modifies app/Traits/ServersTrait.php; overlaps with display and server-info helper changes here.
  • bigpixelrocket/deployer-php#68 — Also updates ServersTrait display/processing logic; directly related to the trait UI additions.

Poem

🐰 I nibble logs and trace the threads,
I hop where Caddy counts its heads,
Demo doors I tuck and bake,
PHP‑FPM hums by the lake,
Deployments bloom where rabbit tracks are laid.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: server monitoring metrics' accurately captures the main objective of the changeset, which centers on adding server monitoring capabilities including Caddy and PHP-FPM metrics collection, display formatting, and associated infrastructure setup.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/server-monitoring-metrics

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 84cbd04 and acd94df.

📒 Files selected for processing (1)
  • playbooks/server-info.sh (9 hunks)
🔇 Additional comments (2)
playbooks/server-info.sh (2)

1-114: Clear refactoring of detection functions.

The restructuring into logical sections (Detection Functions, Helper Functions, Service Metrics) improves maintainability. Distribution and permission detection logic is sound, and detect_family(distro) now correctly parameterizes the distro input.


280-419: PHP-FPM metrics collection and main execution flow are well-structured.

The tab-separated value approach (lines 356, 368) correctly avoids shell word-splitting issues. Availability detection via empty-string checks is sound, and the YAML output structure with fallback defaults is clean. PHP-FPM JSON parsing using grep/sed (lines 295–323) is fragile but acceptable as a first pass (avoids jq dependency). Fields are safely quoted in the YAML output with fallback defaults.

Verify that the YAML output parses correctly and that the consuming code (app/Traits/ServersTrait.php) handles empty caddy_domains gracefully.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
playbooks/demo-site.sh (1)

132-194: Hardcoded PHP version creates maintenance burden.

Line 136 hardcodes the PHP-FPM socket path as /run/php/php8.4-fpm.sock, tying the demo site to PHP 8.4 specifically. This same hardcoded version appears in playbooks/server-install.sh at line 372.

If the PHP version changes (e.g., to 8.5), multiple files need updates.

Consider extracting the PHP version to a shared configuration or detecting it dynamically:

-	local php_fpm_socket='/run/php/php8.4-fpm.sock'
+	# Detect installed PHP-FPM version
+	local php_version=$(php -r "echo PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;" 2>/dev/null || echo "8.4")
+	local php_fpm_socket="/run/php/php${php_version}-fpm.sock"
playbooks/server-install.sh (1)

256-310: Hardcoded PHP 8.4 version throughout installation.

Lines 258-293 install PHP 8.4 packages with hardcoded version numbers. This same hardcoded version also appears at:

  • Line 372 in localhost.caddy socket path
  • Line 438 in PHP-FPM restart logic
  • And in playbooks/demo-site.sh line 136

When upgrading to PHP 8.5 or later, all these locations require updates.

Consider parameterizing the PHP version or detecting it dynamically to reduce maintenance burden across multiple files.

app/Traits/ServersTrait.php (1)

291-314: Consider inlining single-use method.

The formatUptime() method is called only once (line 180), which conflicts with the coding guideline: "Eliminate single-use methods: inline if a method is called only once."

As per coding guidelines, consider inlining the uptime formatting logic directly at line 180:

             if (isset($info['caddy']['uptime_seconds'])) {
                 /** @var int|string|float $rawUptime */
                 $rawUptime = $info['caddy']['uptime_seconds'];
                 /** @var int $uptimeSeconds */
                 $uptimeSeconds = (int) $rawUptime;
-                $caddyItems[] = 'Uptime: '.$this->formatUptime($uptimeSeconds);
+                $uptime = match (true) {
+                    $uptimeSeconds < 60 => "{$uptimeSeconds}s",
+                    $uptimeSeconds < 3600 => floor($uptimeSeconds / 60) . 'm',
+                    $uptimeSeconds < 86400 => floor($uptimeSeconds / 3600) . 'h ' . floor(($uptimeSeconds % 3600) / 60) . 'm',
+                    default => floor($uptimeSeconds / 86400) . 'd ' . floor(($uptimeSeconds % 86400) / 3600) . 'h',
+                };
+                $caddyItems[] = 'Uptime: ' . $uptime;
             }

And remove the formatUptime() method at lines 288-314.

Based on coding guidelines.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 94eb2f9 and 84cbd04.

📒 Files selected for processing (4)
  • app/Traits/ServersTrait.php (1 hunks)
  • playbooks/demo-site.sh (9 hunks)
  • playbooks/server-info.sh (9 hunks)
  • playbooks/server-install.sh (15 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.php

📄 CodeRabbit inference engine (.cursor/rules/00-main.mdc)

**/*.php: Eliminate single-use methods: inline if a method is called only once
Cache computed values: initialize expensive calculations in the constructor
Avoid method call overhead: prefer direct property access when appropriate

Files:

  • app/Traits/ServersTrait.php
🧬 Code graph analysis (3)
playbooks/demo-site.sh (1)
playbooks/server-install.sh (1)
  • run_cmd (49-55)
app/Traits/ServersTrait.php (1)
app/Services/IOService.php (2)
  • displayDeets (543-566)
  • writeln (463-469)
playbooks/server-install.sh (1)
playbooks/demo-site.sh (1)
  • run_cmd (37-43)
🔇 Additional comments (8)
playbooks/server-info.sh (2)

281-328: LGTM: Simple and robust JSON parsing.

The PHP-FPM metrics collection uses straightforward grep/sed patterns for JSON field extraction. The approach is appropriate given the simple field structure, and all fields have sensible fallback defaults.


350-369: LGTM: Clean metrics integration.

The main execution properly integrates the new metrics functions with availability flags and fallback handling, ensuring consistent YAML output structure regardless of whether services are available.

playbooks/demo-site.sh (1)

56-66: LGTM: Robust prerequisite validation.

The enhanced validation properly checks for both the deployer user and home directory existence, with clear error messages directing users to run server:install first.

playbooks/server-install.sh (4)

64-135: LGTM: Robust package manager lock handling.

The lock detection and retry logic properly handles concurrent package manager operations with exponential backoff. The implementation checks multiple lock files and differentiates between lock-related errors (retryable) and other failures (fatal).


292-296: LGTM: Status page enablement supports monitoring.

Enabling the PHP-FPM status page at /fpm-status is necessary for the metrics collection implemented in playbooks/server-info.sh. The configuration correctly enables this endpoint for localhost-only access.


337-384: LGTM: Comprehensive Caddy configuration structure.

The setup creates a clean configuration hierarchy with:

  • Global settings for metrics and logging
  • Localhost-only monitoring endpoints
  • Dedicated sites directory for per-site configs

This structure properly supports the monitoring features and isolates internal endpoints from external access.


492-545: LGTM: Deploy key generation without passphrase.

Generating an SSH deploy key without a passphrase (line 517 with -N "") is appropriate for automated deployments. The key permissions are properly secured (600 for private, 644 for public).

app/Traits/ServersTrait.php (1)

165-285: LGTM: Defensive metrics display with proper guards.

The Caddy and PHP-FPM display blocks properly guard all data access with existence checks and type casts. The colored formatting for warnings (yellow) on queue depth, max children reached, and slow requests provides good visual feedback.

Comment thread playbooks/server-info.sh
Replace configuration-dependent handler="vars" filter with sum across
all handlers for caddy_http_requests_total metric. This makes the
playbook robust across different Caddy configurations without assuming
specific handler names exist.
@loadinglucian
loadinglucian merged commit 11a9edb into main Nov 10, 2025
5 checks passed
@loadinglucian
loadinglucian deleted the feat/server-monitoring-metrics branch November 10, 2025 11:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant