diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 9aaf808..a6eca41 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -255,6 +255,25 @@ jobs: fi fi + # Fails only when 1,000 series do not finish within one poller interval + # (REQ-PERF-001). The timings are printed, not compared: runners vary. + # It runs after the log check, since its budget case logs a warning on + # purpose; its own exit status and the web server log are checked here. + - name: Measure collection and the health page + working-directory: cacti + env: + CLOUD_TEST_DATABASE: disposable + run: | + php -S 127.0.0.1:8081 -t "$GITHUB_WORKSPACE" > "$RUNNER_TEMP/php-perf.log" 2>&1 & + for _ in 1 2 3 4 5 6 7 8 9 10; do + curl -fsS -o /dev/null http://127.0.0.1:8081/cacti/index.php && break + sleep 1 + done + php plugins/cloud/tests/bin/perf.php http://127.0.0.1:8081/cacti/ + if grep -E "Fatal error|Warning:|Uncaught" "$RUNNER_TEMP/php-perf.log"; then + exit 1 + fi + # A 1.2.31 site may still run PHP 8.1. Enabling the plugin there must be # refused with a message and leave Cacti working, both on a fresh install # and after an upgrade-in-place left the plugin's hooks registered. diff --git a/README.md b/README.md index 2bb45b6..4f99ec2 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ These steps install the milestone 2 code for evaluation. They require Cacti 1.2. ## Design +- [docs/performance.md](docs/performance.md) has the collector and health page measurements, with the hardware and settings used. - [docs/PLAN.md](docs/PLAN.md) is the full plan: architecture, the provider and Cacti facts it depends on (with sources), the driver contract, cost arithmetic, security boundaries, testing, and risks. - [docs/decisions/](docs/decisions/) holds architecture decision records for choices already made. - [docs/REQUIREMENTS.md](docs/REQUIREMENTS.md) maps every requirement ID to its issue. diff --git a/docs/PLAN.md b/docs/PLAN.md index cac64c0..05d7087 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -345,7 +345,7 @@ Arithmetic at 1,000 series collected every 300 seconds (8,640 collections a mont | Google Cloud | One or more per metric type and project | About $3.82 (8.64 million series, first million free, $0.50 per million) | | Azure | One per 50 resources, region, and type (if a batch bills as one call) | Within the free million calls per subscription: 20 calls per collection, 172,800 a month. If each resource bills separately, about $76 ([cost model](research/cost-model.md)) | -Engineering targets, to be measured, not yet demonstrated: +Engineering targets, measured against a fixture server in [performance.md](performance.md): - A collector run for 1,000 series finishes within one poller interval, including provider latency. - No page request calls a provider, except Verify on the account page. diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 0000000..70b35c1 --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,62 @@ +# Performance + +Measurements for [#47](https://github.com/somethingwithproof/plugin_cloud/issues/47), taken 2026-11-15 with [`tests/bin/perf.php`](../tests/bin/perf.php). CI runs the same script on every Cacti and PHP job. It fails the job only when 1,000 series don't finish within one poller interval, and prints its timings without comparing them, because runner hardware varies. + +**Result.** With a local fixture server and no added latency, a collector run reads 1,000 series in about 3 seconds. That is about 3 ms of plugin and TLS work per request. The health page renders 10,000 cached series in 0.08 seconds. With 100 ms of simulated provider latency per request, the same run takes 106 seconds. Provider latency, not the plugin, decides whether 1,000 series fit in one poller interval. + +## What runs + +The script uses the real collector, the DigitalOcean driver, the guarded transport (operation allowlist) and the socket transport, with TLS verified against a test CA. Only the host is rewritten, after the operation check, so requests reach [`tests/bin/perf-server.php`](../tests/bin/perf-server.php) instead of `api.digitalocean.com`. That server replays the recorded fixtures with their timestamps moved to the current time, and sends the rate-limit headers the driver reads. + +| Case | Setup | Measures | +|---|---|---| +| Collect | 4 accounts, 50 Droplets each, 5 series per Droplet (CPU and four bandwidth): 1,000 series | One collector run on poller 1 (REQ-PERF-001) | +| Budget | 1 account, 200 Droplets, 5 series each: 1,000 series | The same run, where the request budget stops the account | +| Page | 10 accounts, 200 Droplets each, 5 cached series per Droplet: 10,000 series | `cloud_health.php` over HTTP as a logged-in administrator, the median of five loads after a warm-up (REQ-PERF-002) | + +The collect case uses four accounts because one DigitalOcean token allows 250 requests a minute. At 100 percent request share, that is the most one account reads in a run (`RequestBudget::perRun`). The budget case shows the limit: the account reads 250 series, marks the other 750 unread with reason `budget`, and the health page reports it. + +## Hardware and settings (REQ-PERF-003) + +| | | +|---|---| +| Host | Apple M3 Max, 14 cores, 36 GiB | +| Runtime | OrbStack Linux VM, aarch64, 14 CPUs, 15.7 GiB, Docker image `cloud-ci:8.2` | +| PHP | 8.2.35, CLI for the collector, built-in web server for the page | +| Database | MariaDB 11.8.9, same VM | +| Cacti | 1.2.31 and the 1.2.x branch (1.2.32) | +| Poller interval | 300 seconds | +| Accounts | Collection interval 300 seconds, request share 100 percent, discovery not due during the run | +| Collector time budget | Poller interval less 10 seconds (290); the plugin's default setting is 240 | + +## Results + +Three runs on each Cacti version, no added latency: + +| Case | Cacti 1.2.31 | Cacti 1.2.x | +|---|---|---| +| Collect, 1,000 series in 4 accounts | 2.83, 3.00, 3.17 s; 1,000 read with 1,000 requests | 3.42, 2.59, 2.61 s; 1,000 read with 1,000 requests | +| Budget, 1,000 series in 1 account | 1.20, 1.32, 1.10 s; 250 read, 750 left with reason `budget` | 1.24, 1.72, 1.10 s; 250 read, 750 left with reason `budget` | +| Health page, 10,000 series | 0.08 s median, 0.08 s slowest, all three runs | 0.08 s median, 0.09 s slowest at most | + +With `perf.php 100`, which adds 100 ms before each fixture response, the collect case took 106.26 seconds on Cacti 1.2.31 and read all 1,000 series. The budget case took 27.02 seconds. + +The page result was checked by its content, not only its speed. Each of the 10 accounts showed 1,000 current series, and an estimate of 12,000 requests an hour (1,000 series every 300 seconds). + +## Reading the results + +- **Run time scales with provider latency.** The collector reads one series per request, one request at a time. A run takes about requests × (latency + 3 ms). With the default 240-second time budget, 1,000 series fit while the average round trip stays under about 237 ms. Above that, the collector stops starting new accounts at the budget, and the unread accounts are collected in the next run. The first [live check](research/provider-facts.md#live-checks) (#16) measured a median round trip of 384 ms (301 to 799 ms) from a home connection. At that latency, 1,000 series take about 390 seconds, so the default budget reads about 620 a run and the rest carry over. A poller in a data center near DigitalOcean should see less, so measure from your own poller before planning for more than about 600 series on one poller. +- **DigitalOcean's limit is per token, not per plugin.** At the default 50 percent share, one account reads 125 series a run. Larger estates need more accounts, each with its own token, and the health page estimate shows how close each account is to its share. +- **The page stays cheap at 10,000 series.** It reads cached rows only and never calls a provider, so its cost grows with the plugin's tables, not with provider latency. +- **Not measured here:** RRD updates by Cacti's poller, boost, Spine, remote data collectors, and a database on a separate host. Each adds cost outside the plugin. + +## Running it + +On a disposable database, with the plugin installed and enabled and Cacti served at a URL: + +```sh +CLOUD_TEST_DATABASE=disposable php plugins/cloud/tests/bin/perf.php http://127.0.0.1:8080/cacti/ +CLOUD_TEST_DATABASE=disposable php plugins/cloud/tests/bin/perf.php http://127.0.0.1:8080/cacti/ 100 +``` + +The second argument adds that many milliseconds of latency to each fixture response. The script deletes every plugin account, resource, series, and observation, and resets the admin password, so never run it against a database you keep. diff --git a/tests/bin/perf-server.php b/tests/bin/perf-server.php new file mode 100644 index 0000000..25b2ec4 --- /dev/null +++ b/tests/bin/perf-server.php @@ -0,0 +1,110 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * The DigitalOcean fixture server for the performance runs (#47). Serves + * every monitoring path over TLS from the recorded fixtures, with their + * timestamps moved to now so each datapoint is current, plus the rate + * limit headers the driver reads. One connection at a time, like the + * collector. Must parse on PHP 8.0. + * + * php perf-server.php [latency ms] + * + * The latency is added before each response, to stand in for the provider. + */ + +$port = (int) ($argv[1] ?? 0); +$cert = (string) ($argv[2] ?? ''); +$seconds = (int) ($argv[3] ?? 600); +$latency = (int) ($argv[4] ?? 0); +$fixture = dirname(__DIR__) . '/fixtures/digitalocean/'; + +$templates = array( + 'bandwidth' => json_decode((string) file_get_contents($fixture . 'droplet_bandwidth.json'), true), + 'default' => json_decode((string) file_get_contents($fixture . 'droplet_cpu.json'), true), +); + +$server = stream_socket_server( + 'ssl://127.0.0.1:' . $port, + $errno, + $errstr, + STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, + stream_context_create(array('ssl' => array('local_cert' => $cert))) +); + +if ($server === false) { + fwrite(STDERR, "listen failed: $errstr\n"); + exit(1); +} + +/** + * The fixture for $path with each series' points ending a minute ago. + */ +function perf_body($templates, $path) { + $body = $templates[basename($path) === 'bandwidth' ? 'bandwidth' : 'default']; + $now = time() - 60; + + foreach ($body['data']['result'] as $i => $series) { + $count = count($series['values']); + + foreach ($series['values'] as $j => $point) { + $body['data']['result'][$i]['values'][$j][0] = $now - ($count - 1 - $j) * 60; + } + } + + return json_encode($body); +} + +$deadline = time() + $seconds; + +while (time() < $deadline) { + $conn = @stream_socket_accept($server, 1); + + if ($conn === false) { + continue; + } + + stream_set_timeout($conn, 5); + $head = ''; + + while (strpos($head, "\r\n\r\n") === false && strlen($head) < 65536) { + $line = fgets($conn, 8192); + + if ($line === false) { + break; + } + + $head .= $line; + } + + usleep($latency * 1000); + + $target = explode(' ', explode("\r\n", $head, 2)[0]) + array('', '', ''); + $path = (string) parse_url($target[1], PHP_URL_PATH); + $body = strpos($path, '/v2/monitoring/metrics/') === 0 ? perf_body($templates, $path) : '{"id":"not_found"}'; + $status = strpos($path, '/v2/monitoring/metrics/') === 0 ? '200 OK' : '404 Not Found'; + + @fwrite( + $conn, + "HTTP/1.1 $status\r\nContent-Type: application/json\r\nContent-Length: " . strlen($body) . "\r\n" . + "ratelimit-limit: 5000\r\nratelimit-remaining: 4999\r\nratelimit-reset: " . (time() + 3600) . "\r\n" . + "Connection: close\r\n\r\n" . $body + ); + fclose($conn); +} diff --git a/tests/bin/perf.php b/tests/bin/perf.php new file mode 100644 index 0000000..10d4a62 --- /dev/null +++ b/tests/bin/perf.php @@ -0,0 +1,386 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Performance runs (#47), on a disposable database and a running Cacti: + * + * collect 1,000 series in four accounts of 250, the most one token + * reads in a run, timed against the fixture server over TLS + * budget 1,000 series in one account, where the request budget stops + * the run at 250 and leaves the rest unread + * page the health page over HTTP at 10,000 cached series + * + * The real driver, guarded transport, and socket transport run; only the + * host is rewritten to the fixture server after the operation check. + * Prints the results as JSON with the hardware and settings, and exits 1 + * when the 1,000-series run does not finish within one poller interval. + * Must parse on PHP 8.0. + * + * CLOUD_TEST_DATABASE=disposable php plugins/cloud/tests/bin/perf.php http://127.0.0.1:8080/cacti/ [latency ms] + * + * A latency, in milliseconds, delays each fixture response to stand in for + * the provider's round trip. + */ + +use Somethingwithproof\Cloud\Collector; +use Somethingwithproof\Cloud\CredentialStore; +use Somethingwithproof\Cloud\DigitalOceanDriver; +use Somethingwithproof\Cloud\Drivers; +use Somethingwithproof\Cloud\HealthRepository; +use Somethingwithproof\Cloud\HttpRequest; +use Somethingwithproof\Cloud\HttpResponse; +use Somethingwithproof\Cloud\HttpTransport; +use Somethingwithproof\Cloud\LeaseRepository; +use Somethingwithproof\Cloud\ObservationRepository; +use Somethingwithproof\Cloud\OutboundPolicy; +use Somethingwithproof\Cloud\Provider; +use Somethingwithproof\Cloud\ProviderDriver; +use Somethingwithproof\Cloud\Redactor; +use Somethingwithproof\Cloud\ResourceRepository; +use Somethingwithproof\Cloud\SecretRepository; +use Somethingwithproof\Cloud\SeriesRepository; +use Somethingwithproof\Cloud\SocketTransport; +use Somethingwithproof\Cloud\SystemClock; + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); + +if (getenv('CLOUD_TEST_DATABASE') !== 'disposable' || !isset($argv[1])) { + fwrite(STDERR, "Set CLOUD_TEST_DATABASE=disposable and pass the Cacti base URL\n"); + exit(2); +} + +include_once($config['base_path'] . '/plugins/cloud/setup.php'); + +if (!cloud_boot()) { + fwrite(STDERR, "The plugin did not boot; install and enable it first\n"); + exit(2); +} + +const PERF_METRICS = array('do_cpu_pct', 'do_bw_pub_in', 'do_bw_pub_out', 'do_bw_prv_in', 'do_bw_prv_out'); +const PERF_LOCAL = 9000000; + +$root = rtrim($argv[1], '/') . '/'; +$tmp = sys_get_temp_dir() . '/cloud-perf-' . getmypid(); +$password = 'Perf-' . bin2hex(random_bytes(8)); +$poller = (int) read_config_option('poller_interval'); +$poller = $poller > 0 ? $poller : 300; +$latency = max(0, (int) ($argv[2] ?? 0)); + +mkdir($tmp, 0700); +passthru(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg(__DIR__ . '/../transport-spike/make-certs.php') . ' ' + . escapeshellarg($tmp) . ' >/dev/null'); +file_put_contents($tmp . '/token', 'dop_v1_' . str_repeat('p', 64)); +chmod($tmp . '/token', 0600); + +$probe = stream_socket_server('tcp://127.0.0.1:0'); +$name = (string) stream_socket_get_name($probe, false); +fclose($probe); +$port = (int) substr($name, strrpos($name, ':') + 1); + +$server = proc_open( + array(PHP_BINARY, __DIR__ . '/perf-server.php', (string) $port, $tmp . '/good.pem', '1800', (string) $latency), + array( + 0 => array('file', '/dev/null', 'r'), + 1 => array('file', '/dev/null', 'w'), + 2 => array('file', '/dev/null', 'w'), + ), + $pipes +); + +// Cacti's error handler logs a refused probe even under @, so wait quietly. +set_error_handler(static function () { + return true; +}); + +for ($i = 0; $i < 100 && stream_socket_client('tcp://127.0.0.1:' . $port, $errno, $errstr, 0.1) === false; $i++) { + usleep(50000); +} + +restore_error_handler(); + +/** + * Sends each request to the fixture server instead of the provider, after + * the guarded transport has checked it against the driver's operations. + */ +final class PerfTransport implements HttpTransport { + private SocketTransport $inner; + private string $origin; + + public function __construct(int $port, string $caFile) { + $policy = new OutboundPolicy(array('127.0.0.1'), array($port)); + $this->inner = new SocketTransport($policy, 5.0, 30.0, 5242880, $caFile); + $this->origin = 'https://127.0.0.1:' . $port . '/'; + } + + public function send(HttpRequest $request): HttpResponse { + $prefix = 'https://' . DigitalOceanDriver::HOST . '/'; + $url = strpos($request->url, $prefix) === 0 + ? $this->origin . substr($request->url, strlen($prefix)) + : $request->url; + + return $this->inner->send(new HttpRequest($request->method, $url, $request->headers, $request->body)); + } +} + +function perf_reset() { + foreach (array('plugin_cloud_observation', 'plugin_cloud_series', 'plugin_cloud_health', 'plugin_cloud_lease', + 'plugin_cloud_resource', 'plugin_cloud_account') as $table) { + db_execute('DELETE FROM ' . $table); + } + + db_execute_prepared('DELETE FROM data_template_data WHERE local_data_id >= ?', array(PERF_LOCAL)); +} + +/** + * Insert rows in chunks of 500. + * + * @param list> $rows + */ +function perf_insert($sql, $rows) { + foreach (array_chunk($rows, 500) as $chunk) { + $marks = '(' . implode(', ', array_fill(0, count($chunk[0]), '?')) . ')'; + db_execute_prepared($sql . implode(', ', array_fill(0, count($chunk), $marks)), array_merge(...$chunk)); + } +} + +/** + * $accounts accounts of $droplets Droplets with five series each (CPU and + * the four bandwidth series), discovered just now so no run rediscovers them. + */ +function perf_world($accounts, $droplets, $observed) { + global $tmp; + + perf_reset(); + $now = time(); + $local = PERF_LOCAL; + + for ($a = 1; $a <= $accounts; $a++) { + db_execute_prepared( + "INSERT INTO plugin_cloud_account (provider, name, poller_id, credential_source, credential_file, + collect_interval, discover_interval, request_share, admin_state) + VALUES ('digitalocean', ?, 1, 'file', ?, 300, 86400, 100, 'enabled')", + array('Perf ' . $a, $tmp . '/token') + ); + $account = (int) db_fetch_insert_id(); + db_execute_prepared( + "INSERT INTO plugin_cloud_health (account_id, discovered_at, discovery) VALUES (?, ?, 'ok')", + array($account, $now) + ); + + $resources = array(); + + for ($d = 1; $d <= $droplets; $d++) { + $id = (string) ($a * 100000 + $d); + $resources[] = array($account, 'droplet', $id, 'perf-' . $a . '-' . $d, 'active', $now, $now); + } + + perf_insert( + 'INSERT INTO plugin_cloud_resource (account_id, type, provider_id, name, lifecycle, first_seen, last_seen) VALUES ', + $resources + ); + + $sources = array(); + $series = array(); + $points = array(); + + $rows = db_fetch_assoc_prepared('SELECT id FROM plugin_cloud_resource WHERE account_id = ?', array($account)); + + foreach ($rows as $row) { + foreach (PERF_METRICS as $metric) { + $sources[] = array($local, 0, 'perf', 'on'); + $series[] = array($local, $account, (int) $row['id'], $metric, $now); + $points[] = array((int) $row['id'], $metric, 1.5, $now - 60, $now - 30, 'ok'); + $local++; + } + } + + perf_insert('INSERT INTO data_template_data (local_data_id, data_template_id, name, active) VALUES ', $sources); + perf_insert( + 'INSERT INTO plugin_cloud_series (local_data_id, account_id, resource_id, metric, created_at) VALUES ', + $series + ); + + if ($observed) { + perf_insert( + 'INSERT INTO plugin_cloud_observation (resource_id, metric, value, observed_at, fetched_at, status) VALUES ', + $points + ); + } + } +} + +/** + * One collector run on poller 1, timed, with what the accounts recorded. + */ +function perf_collect() { + global $port, $tmp, $poller; + + $clock = new SystemClock(); + $drivers = new Drivers(static function (OutboundPolicy $policy) use ($port, $tmp): HttpTransport { + return new PerfTransport($port, $tmp . '/ca.pem'); + }); + $drivers->register(Provider::DigitalOcean, static function (HttpTransport $http): ProviderDriver { + return new DigitalOceanDriver($http, new SystemClock()); + }); + $collector = new Collector( + new \Somethingwithproof\Cloud\AccountRepository(false, $clock), + $drivers, + new CredentialStore(new SecretRepository(false, $clock), '/nonexistent', $tmp), + new LeaseRepository(false, $clock), + new ResourceRepository(false, $clock), + new SeriesRepository(false), + new ObservationRepository(false), + new HealthRepository(false), + new Redactor(), + $clock, + 'perf' + ); + + $started = microtime(true); + $collector->run(1, max(10, $poller - 10)); + $seconds = microtime(true) - $started; + $health = db_fetch_row( + 'SELECT SUM(series_total) AS total, SUM(series_read) AS read_count, SUM(requests) AS requests, + GROUP_CONCAT(DISTINCT collection) AS collection FROM plugin_cloud_health' + ); + + return array( + 'seconds' => round($seconds, 2), + 'series' => (int) $health['total'], + 'series_read' => (int) $health['read_count'], + 'requests' => (int) $health['requests'], + 'collection' => (string) $health['collection'], + 'observations' => (int) db_fetch_cell("SELECT COUNT(*) FROM plugin_cloud_observation WHERE status = 'ok'"), + ); +} + +function perf_http($url, $jar, $post = null) { + $ch = curl_init($url); + curl_setopt_array($ch, array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_COOKIEJAR => $jar, + CURLOPT_COOKIEFILE => $jar, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_TIMEOUT => 120, + )); + + if ($post !== null) { + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post)); + } + + $started = microtime(true); + $body = (string) curl_exec($ch); + + return array((int) curl_getinfo($ch, CURLINFO_HTTP_CODE), $body, microtime(true) - $started); +} + +/** + * The health page as a logged-in administrator: the median of five loads + * after one warm-up, and whether every load rendered the estimate. + */ +function perf_page() { + global $root, $password, $tmp; + + db_execute_prepared( + "UPDATE user_auth SET password = ?, must_change_password = '', password_change = '', enabled = 'on', + locked = '', failed_attempts = 0 WHERE id = 1", + array(password_hash($password, PASSWORD_DEFAULT)) + ); + + $jar = $tmp . '/cookies'; + list(, $login) = perf_http($root . 'index.php', $jar); + preg_match('/csrfMagicToken\s*=\s*"([^"]+)"/', $login, $m); + perf_http($root . 'index.php', $jar, array( + '__csrf_magic' => isset($m[1]) ? $m[1] : '', + 'action' => 'login', + 'login_username' => 'admin', + 'login_password' => $password, + )); + + $times = array(); + $rendered = true; + + for ($i = 0; $i < 6; $i++) { + list($code, $body, $seconds) = perf_http($root . 'plugins/cloud/cloud_health.php', $jar); + $rendered = $rendered && $code === 200 && strpos($body, 'Cloud Request Estimate') !== false + && strpos($body, 'Perf 10') !== false; + + if ($i > 0) { + $times[] = $seconds; + } + } + + sort($times); + + return array('seconds' => round($times[2], 2), 'slowest' => round(end($times), 2), 'rendered' => $rendered); +} + +// lscpu names ARM and x86 processors alike; a VM may hide the model. +$cpu = array(); + +foreach (explode("\n", (string) shell_exec('lscpu 2>/dev/null')) as $line) { + if (preg_match('/^(Vendor ID|Model name):\s*(.+)$/', $line, $field) === 1 && trim($field[2]) !== '-') { + $cpu[] = trim($field[2]); + } +} + +$memory = preg_match('/^MemTotal:\s+(\d+)/m', (string) @file_get_contents('/proc/meminfo'), $mem) === 1 + ? round((int) $mem[1] / 1048576, 1) . ' GiB' + : ''; + +perf_world(4, 50, false); +$collect = perf_collect(); +perf_world(1, 200, false); +$budget = perf_collect(); +perf_world(10, 200, true); +$page = perf_page(); +perf_reset(); + +proc_terminate($server); + +foreach (array('token', 'cookies', 'ca.pem', 'good.pem', 'wrongname.pem', 'selfsigned.pem', 'openssl.cnf') as $file) { + @unlink($tmp . '/' . $file); +} + +@rmdir($tmp); + +$within = $collect['series_read'] === 1000 && $collect['seconds'] < $poller; + +print json_encode(array( + 'environment' => array( + 'cpu' => implode(' ', $cpu), + 'cores' => trim((string) shell_exec('nproc')), + 'memory' => $memory, + 'machine' => php_uname('s') . ' ' . php_uname('r') . ' ' . php_uname('m'), + 'php' => PHP_VERSION, + 'database' => (string) db_fetch_cell('SELECT VERSION()'), + 'cacti' => CACTI_VERSION, + 'poller_interval' => $poller, + 'latency_ms' => $latency, + ), + 'collect_1000_in_4_accounts' => $collect, + 'budget_1000_in_1_account' => $budget, + 'health_page_10000_series' => $page, + 'within_poller_interval' => $within, +), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL; + +exit($within ? 0 : 1);