diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a8c8db43..0fcceb36e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,13 +6,14 @@ This file documents all notable changes made to ITFlow. ### Upgrading -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database change (4.1.8) in the same pass. It adds a table for the problems of instances you manage and two settings for which of them open tickets, and changes nothing that is there. Nothing else is required. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's two database changes (4.1.8 and 4.1.9) in the same pass. They add a table for the problems of instances you manage and two settings for which of them open tickets, and a table for each instance's history, and change nothing that is there. Nothing else is required. -If you manage other ITFlow installs, the manager and its instances can be updated in either order. An instance sends its check-ins encoded only once both are on this version, so a web application firewall in front of the manager may need its exclusion for check-ins until then. An instance shows its agents and error categories once it is updated. +If you manage other ITFlow installs, the manager and its instances can be updated in either order. An instance sends its check-ins encoded only once both are on this version, so a web application firewall in front of the manager may need its exclusion for check-ins until then. An instance shows its agents and error categories once it is updated. Each instance's history starts with its first check-in after the manager is updated - there is none from before. ### New Features & Updates - Managed Instances: problems on the instances you manage can open tickets. **Problem Tickets** on Admin > Managed Instances picks which - **Problems**, at High: an instance that has stopped checking in, cron not running, a failed update, a database update not applied, or a security update waiting on one that doesn't update itself; or **Problems and warnings**, which adds backups failing or none for three days and errors being logged, at Medium - and the category they get. A problem opens a ticket once it has lasted ten minutes, so a blip doesn't, on the instance's client or on your own client record when it has none. The ticket says what's wrong, with the instance's address, version and last check-in, what to look at, and a link to its page. The same problem again goes on its ticket while that's open, reopening it if it was resolved, and when it clears the ticket is resolved unless someone has written on it. A suspended instance, or a new one waiting for its cron job, opens none. Each problem under Health on an instance's page links to its ticket. Off until you turn it on. +- Managed Instances: an instance's page has a History card - its agents against its seat limit, its clients, storage, uptime, errors and backups, a day at a time, over 30 days, 90 days or a year. Uptime counts the gaps of more than ten minutes between its check-ins, and lists each with when it started and how long it lasted. Errors list the categories they came under, and backups show as a strip of the days one was made, failed or wasn't. Over a year, errors, uptime and backups go by the week. It's kept for good, from the day you update. - Managed Instances: an instance's page has an Agents card - who holds its seats, with each agent's name, email, role, whether they sign in with MFA and when they last signed in, then the invites waiting and the day each runs out. API accounts are marked. The support user takes no seat and isn't listed. Managed By, on the instance, lists this among what it tells its manager. - Managed Instances: errors logged on an instance now say which categories they were logged under, in its health line and under Errors today, where the count and each category sign you in to it as support on its App Logs, showing just those errors. Only how many there are under each category is sent - never what an error says, which can hold a client's email address or a ticket's subject. @@ -29,6 +30,10 @@ If you manage other ITFlow installs, the manager and its instances can be update - `managedInstanceHealth()` issues are `[tone, text, key]` - the key stays the same while the text changes: `offline`, `waiting`, `cron`, `db_update`, `update_failed`, `update`, `security_update`, `backup`, `errors` and `seats`. - `managerIssueTickets()`, run by `cron/managed_instances.php`, records a key when it is first seen, opens a ticket once the row is `MANAGED_ISSUE_GRACE_MINUTES` (10) old and `managedIssueOpensTicket()` passes it at the level, deletes a row that clears before then, and clears the rest through `managedIssueCleared()`, which resolves the ticket unless `rmmTicketWorked()`. `managedIssueTicket()` puts a key that comes back on its last ticket that isn't closed, reopening it if resolved. A key still there but no longer watched at the level isn't taken as cleared, and the rows of an instance removed or disconnected are cleared without touching their tickets. It does nothing with the level off or ticketing off. `managerTicketsReady()`, `managerTicketLevels()` and `managerTicketSettings()` read the settings. - Tickets it opens have `ticket_source = 'Managed'`, with an icon in `ticketSourceIcon()`, wording on the ticket page and `managed` in `ticketMailNewTicketAddress()`. `managedInstanceIssueTickets($instance_id)` gives an instance's open ones by key for the Health card. The window is `admin/modals/managed_instance/managed_instance_tickets.php`, posting `edit_managed_instance_tickets`. +- Database 4.1.9: `managed_instance_stats` - one row per instance per day, by the manager's date (unique on `managed_stat_instance_id`, `managed_stat_date`): `_agents`, `_invites`, `_seat_limit`, `_clients`, `_uploads_mb`, `_db_mb`, `_errors` (the report's `errors_24h`, which at the day's last check-in is that day's) and `_error_categories` (JSON), `_backup` (`ok`, `failed` or `''`), `_version`, `_checkins`, and `_outages` (JSON, each `from` and `to`). Re-runnable. +- `managedStatsRecord($row, $report)`, from `managerCheckin()` with the row as it was before the check-in, upserts today's row - `_checkins` + 1, and a day's `ok` backup never going back to `failed` or `''` - puts a backup made before midnight but first reported after it on its own day, and appends a gap of more than `MANAGED_OFFLINE_MINUTES` since the last check-in to today's `_outages` (the last 50). `managedStatsReady()` guards it before the update. +- `managedInstanceHistory($row, $days)` reads a period, from the first day there is: each day's figures, its `uptime` and minutes `down` from the gaps overlapping it - one going on now included, while the instance is connected - the gaps newest first, uptime over the period, backups made and failed, errors and their categories most first, and the storage unit (MB, or GB from 2 GB). `admin/managed_instance.php` draws it with `reportChart()` and `js/reports.js`, `?history=30`, `90` or `365`, grouping the bar charts and the backup strip by week over 120 days. The strip is `.itflow-history-strip` in `css/itflow_custom.css`. +- Deleting a managed instance now deletes its `managed_instance_issues` and `managed_instance_stats` rows too. ## [26.12.1] diff --git a/admin/database_updates/4.1.9.php b/admin/database_updates/4.1.9.php new file mode 100644 index 000000000..a3eb6b4f9 --- /dev/null +++ b/admin/database_updates/4.1.9.php @@ -0,0 +1,37 @@ + Managed Instances > one instance. At the top, how it is - waiting to connect, * checking in or gone quiet - with what can be done to it: sign in as support, update it, * check for updates, make it read-only or suspend it. Under that, what needs a look from its - * last report, the connection code while it's waiting for one, and what it has been asked and - * how that went; alongside, what this manager sets for it and what it reported about itself. + * last report, the connection code while it's waiting for one, who holds its seats, its history + * a day at a time over 30 days, 90 days or a year (managedInstanceHistory()), and what it has + * been asked and how that went; alongside, what this manager sets for it and what it reported + * about itself. * * A connection code shows once, on the page its making redirects to - only its hash is kept * (managedInstanceNewCode()). The handlers are admin/post/managed_instances.php. @@ -380,6 +382,184 @@ if ($error_count > 0) { + '30 days', 90 => '90 days', 365 => '1 year']; + $history_days = intval($_GET['history'] ?? 30); + $history_days = isset($history_periods[$history_days]) ? $history_days : 30; + $history = managedInstanceHistory($row, $history_days); + $history_list = $history['days']; + $history_now = []; + foreach (array_reverse($history_list) as $history_day) { + if ($history_day['agents'] !== null) { + $history_now = $history_day; + break; + } + } + $history_column = function ($key) use ($history_list) { + return array_column($history_list, $key); + }; + $history_labels = $history_column('label'); + // Over a year the bars and the backup strip go by the week, so each stays readable + $history_weekly = count($history_list) > 120; + $history_bars = $history_list; + if ($history_weekly) { + $history_bars = []; + foreach (array_chunk($history_list, 7) as $week) { + $sum = function ($key) use ($week) { + $values = array_filter(array_column($week, $key), function ($v) { return $v !== null; }); + return $values ? array_sum($values) : null; + }; + $backups = array_filter(array_column($week, 'backup'), function ($v) { return $v !== null; }); + $history_bars[] = [ + 'label' => $week[0]['label'], + 'title' => $week[0]['label'] . ' - ' . end($week)['label'], + 'errors' => $sum('errors'), + 'down' => $sum('down'), + 'backup' => !$backups ? null : (in_array('failed', $backups, true) ? 'failed' : (in_array('', $backups, true) ? '' : 'ok')), + 'made' => count(array_keys($backups, 'ok', true)), + 'heard' => count($backups), + ]; + } + } + $bar_labels = array_column($history_bars, 'label'); + $bar_period = $history_weekly ? ' that week' : ''; + $history_block = function ($title, $figure, $body) { + return '
' . escapeHtml($title) . '
' + . '
' . $figure . '
' . $body . '
'; + }; + $history_span = function ($seconds) { + $minutes = max(1, (int) round($seconds / 60)); + if ($minutes < 90) { + return $minutes . ' minute' . ($minutes === 1 ? '' : 's'); + } + $hours = round($minutes / 60, 1); + return $hours < 48 ? rtrim(rtrim(number_format($hours, 1), '0'), '.') . ' hours' : round($hours / 24) . ' days'; + }; + ?> + + +
+
+

History

+ +
+
+ $period_label) { ?> + > + +
+
+ +
+ +
Its history needs this install's database update - apply it from Maintenance > Update.
+ +
Its history starts with its next check-in - a line a day of its agents, clients, storage, uptime, errors and backups, kept for good.
+ strtotime('-' . ($history_days - 1) . ' days'); ?> +
+ +
Its history starts on .
+ +
+ 'Agents', 'data' => $history_column('agents'), 'tone' => 'accent', 'fill' => true]]; + if (array_sum(array_map('intval', $history_column('invites'))) > 0) { + $series[] = ['label' => 'With invites waiting', 'tone' => 'muted', 'data' => array_map(function ($d) { + return $d['agents'] === null ? null : $d['agents'] + $d['invites']; + }, $history_list)]; + } + if (max(array_map('intval', $history_column('limit')) ?: [0]) > 0) { + $series[] = ['label' => 'Seat limit', 'data' => array_map(function ($d) { + return $d['limit'] ? $d['limit'] : null; + }, $history_list), 'tone' => 'faint', 'dashed' => true]; + } + $figure = $history_now ? intval($history_now['agents']) . ' agent' . (intval($history_now['agents']) === 1 ? '' : 's') + . ($history_now['invites'] ? ', ' . intval($history_now['invites']) . ' invited' : '') + . ($history_now['limit'] ? ' - ' . intval($history_now['limit']) . ' seats' : '') : ''; + echo $history_block('Agents', $figure, reportChart(['type' => 'line', 'labels' => $history_labels, 'series' => $series, 'format' => 'count'], 'sm', 'Agents by day')); + + // Clients + $clients = array_values(array_filter($history_column('clients'), function ($v) { return $v !== null; })); + $change = $clients ? end($clients) - $clients[0] : 0; + $figure = $clients ? end($clients) . ' client' . (end($clients) === 1 ? '' : 's') . ($change ? ' - ' . ($change > 0 ? '+' : '') . $change . ' in this period' : '') : ''; + echo $history_block('Clients', $figure, reportChart(['type' => 'line', 'labels' => $history_labels, 'legend' => false, + 'series' => [['label' => 'Clients', 'data' => $history_column('clients'), 'tone' => 'accent', 'fill' => true]], 'format' => 'count'], 'sm', 'Clients by day')); + + // Storage - uploads and the database, in MB, or GB once it's 2 GB + $unit = $history['unit']; + $size = function ($mb) use ($unit) { + return $mb === null ? null : round($unit === 'GB' ? $mb / 1024 : $mb, 1); + }; + $figure = $history_now ? $size($history_now['uploads'] + $history_now['db']) . " $unit - " . $size($history_now['uploads']) . " $unit uploads, " . $size($history_now['db']) . " $unit database" : ''; + echo $history_block('Storage', $figure, reportChart(['type' => 'line', 'labels' => $history_labels, 'format' => 'number', 'series' => [ + ['label' => "Uploads ($unit)", 'data' => array_map($size, $history_column('uploads')), 'tone' => 'accent', 'fill' => true], + ['label' => "Database ($unit)", 'data' => array_map($size, $history_column('db')), 'tone' => 'muted'], + ]], 'sm', 'Storage by day')); + + // Uptime - the minutes each day it wasn't checking in, so the days it went quiet stand out + $gaps_html = ''; + if ($history['gaps']) { + $gaps_html .= '
    '; + foreach (array_slice($history['gaps'], 0, 5) as $gap) { + $same_day = date('Y-m-d', $gap['from']) === date('Y-m-d', $gap['to']); + $gaps_html .= '
  • ' + . ($gap['ongoing'] ? 'Since ' . date('M j, g:i A', $gap['from']) . ' - not checking in now' + : date('M j, g:i A', $gap['from']) . ' - ' . date($same_day ? 'g:i A' : 'M j, g:i A', $gap['to'])) + . ' ' . $history_span($gap['to'] - $gap['from']) . '
  • '; + } + if (count($history['gaps']) > 5) { + $gaps_html .= '
  • and ' . (count($history['gaps']) - 5) . ' more
  • '; + } + $gaps_html .= '
'; + } + $quiet = count($history['gaps']); + $figure = $history['uptime'] !== null ? rtrim(rtrim(number_format($history['uptime'], 2), '0'), '.') . '% - ' + . ($quiet ? 'went quiet ' . ($quiet === 1 ? 'once' : "$quiet times") : 'never went quiet') : ''; + echo $history_block('Uptime', $figure, $quiet ? reportChart(['type' => 'bar', 'labels' => $bar_labels, 'format' => 'count', 'legend' => false, + 'series' => [['label' => "Minutes not checking in$bar_period", 'data' => array_column($history_bars, 'down'), 'tone' => 'danger']]], 'sm', 'Minutes not checking in') . $gaps_html + : '
Checking in throughout - no gap of more than ' . MANAGED_OFFLINE_MINUTES . ' minutes.
'); + + // Errors - each day's, and the categories they came under over the period + $categories_html = ''; + if ($history['categories']) { + $named = []; + foreach (array_slice($history['categories'], 0, 5, true) as $category => $logged) { + $named[] = escapeHtml($category !== '' ? $category : 'No category') . ' ' . intval($logged) . ''; + } + $more = count($history['categories']) - count($named); + $categories_html = '
' . implode(' · ', $named) . ($more > 0 ? " and $more more" : '') . '
'; + } + $figure = $history['errors'] . ' error' . ($history['errors'] === 1 ? '' : 's') . ' in this period'; + echo $history_block('Errors', $figure, reportChart(['type' => 'bar', 'labels' => $bar_labels, 'format' => 'count', 'legend' => false, + 'series' => [['label' => "Errors$bar_period", 'data' => array_column($history_bars, 'errors'), 'tone' => 'accent']]], 'sm', 'Errors') . $categories_html); + + // Backups - a strip of the days (or weeks): made, failed, none, or nothing heard + $backups = $history['backups']; + $strip = '
' + . 'Backed up' + . 'Failed' + . 'None
'; + $figure = 'Backed up on ' . $backups['ok'] . ' of ' . $backups['days'] . ' day' . ($backups['days'] === 1 ? '' : 's') . ($backups['failed'] ? ' - ' . $backups['failed'] . ' failed' : ''); + echo $history_block('Backups', $figure, $strip); + ?> +
+
+ +
+
@@ -494,3 +674,7 @@ if ($error_count > 0) { + + span { + flex: 1 1 0; + min-width: 1px; + border-radius: 2px; +} +.itflow-history-strip.is-dense > span { + min-width: 0; + border-radius: 0; +} +.itflow-history-strip > .is-empty { + background: transparent; + box-shadow: inset 0 0 0 1px var(--bs-border-color); +} +.itflow-history-key { + display: inline-block; + width: 10px; + height: 10px; + border-radius: 2px; + margin-right: .35rem; + vertical-align: -1px; +} + /* Tables: sortable headings, and a totals row that reads as one */ .itflow-report-table > tfoot > tr > td { border-top: 2px solid var(--bs-border-color); diff --git a/db.sql b/db.sql index 5fc4b6415..79a51048e 100644 --- a/db.sql +++ b/db.sql @@ -2330,6 +2330,34 @@ CREATE TABLE `managed_instance_issues` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `managed_instance_stats` +-- + +DROP TABLE IF EXISTS `managed_instance_stats`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `managed_instance_stats` ( + `managed_stat_id` int(11) NOT NULL AUTO_INCREMENT, + `managed_stat_instance_id` int(11) NOT NULL, + `managed_stat_date` date NOT NULL, + `managed_stat_agents` int(11) NOT NULL DEFAULT 0, + `managed_stat_invites` int(11) NOT NULL DEFAULT 0, + `managed_stat_seat_limit` int(11) NOT NULL DEFAULT 0, + `managed_stat_clients` int(11) NOT NULL DEFAULT 0, + `managed_stat_uploads_mb` decimal(12,1) NOT NULL DEFAULT 0.0, + `managed_stat_db_mb` decimal(12,1) NOT NULL DEFAULT 0.0, + `managed_stat_errors` int(11) NOT NULL DEFAULT 0, + `managed_stat_error_categories` text DEFAULT NULL, + `managed_stat_backup` varchar(10) NOT NULL DEFAULT '', + `managed_stat_version` varchar(20) NOT NULL DEFAULT '', + `managed_stat_checkins` int(11) NOT NULL DEFAULT 0, + `managed_stat_outages` text DEFAULT NULL, + PRIMARY KEY (`managed_stat_id`), + UNIQUE KEY `managed_stat_day` (`managed_stat_instance_id`,`managed_stat_date`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `managed_instances` -- diff --git a/functions/managed.php b/functions/managed.php index c6d3642c4..a63941638 100644 --- a/functions/managed.php +++ b/functions/managed.php @@ -1439,6 +1439,201 @@ function managedInstanceIssueTickets(int $instance_id): array return $tickets; } +/* + * ---------- History ---------- + * One managed_instance_stats row per instance per day, by this ITFlow's own date, kept up at + * each check-in from its report (managedStatsRecord()): agents, invites and the seat limit, + * clients, storage, the errors of the last 24 hours under their categories - at the day's last + * check-in, that day's own - whether a backup was made, and the version. With them, how many + * times it checked in, and each gap between check-ins of more than MANAGED_OFFLINE_MINUTES, + * on the day it ended - its uptime is worked out from those. Kept for good: a row a day is + * small. managedInstanceHistory() reads a period of it for the instance's page. + */ + +/** Whether the history table is there - it arrives with the 4.1.9 database update. */ +function managedStatsReady(): bool +{ + global $mysqli; + static $ready = null; + if ($ready === null) { + try { + $ready = (bool) mysqli_query($mysqli, "SELECT 1 FROM managed_instance_stats LIMIT 1"); + } catch (Throwable $e) { + $ready = false; + } + } + return $ready; +} + +/** Today's history row for an instance, from the report it just sent - $row as it was before this check-in. */ +function managedStatsRecord(array $row, array $report): void +{ + global $mysqli; + + if (!managedStatsReady()) { + return; + } + $instance_id = intval($row['managed_instance_id']); + $today = date('Y-m-d'); + $agents = (array) ($report['agents'] ?? []); + $disk = (array) ($report['disk'] ?? []); + $backup = (array) ($report['backup'] ?? []); + $app = (array) ($report['app'] ?? []); + + $categories = []; + foreach ((array) ($report['errors_by_category'] ?? []) as $category => $logged) { + $categories[mb_substr((string) $category, 0, 100)] = intval($logged); + } + $day_of = function ($iso) { + $time = $iso ? strtotime((string) $iso) : false; + return $time ? date('Y-m-d', $time) : ''; + }; + // A backup made today - or one that failed today, unless one was made too + $made = $day_of($backup['last_ok_at'] ?? null); + $backed = $made === $today ? 'ok' : (($backup['last_status'] ?? '') === 'Failed' && $day_of($backup['last_at'] ?? null) === $today ? 'failed' : ''); + + $set = "managed_stat_agents = " . intval($agents['active'] ?? 0) . ", managed_stat_invites = " . intval($agents['invites'] ?? 0) . ", + managed_stat_seat_limit = " . intval($agents['limit'] ?? 0) . ", managed_stat_clients = " . intval($report['clients'] ?? 0) . ", + managed_stat_uploads_mb = " . round(floatval($disk['uploads_mb'] ?? 0), 1) . ", managed_stat_db_mb = " . round(floatval($disk['db_mb'] ?? 0), 1) . ", + managed_stat_errors = " . intval($report['errors_24h'] ?? 0) . ", managed_stat_error_categories = '" . mysqli_real_escape_string($mysqli, (string) json_encode((object) $categories)) . "', + managed_stat_version = '" . mysqli_real_escape_string($mysqli, mb_substr((string) ($app['version'] ?? ''), 0, 20)) . "'"; + mysqli_query($mysqli, "INSERT INTO managed_instance_stats SET managed_stat_instance_id = $instance_id, managed_stat_date = '$today', $set, + managed_stat_backup = '$backed', managed_stat_checkins = 1 + ON DUPLICATE KEY UPDATE $set, managed_stat_checkins = managed_stat_checkins + 1, + managed_stat_backup = IF('$backed' = 'ok' OR managed_stat_backup = '', '$backed', managed_stat_backup)"); + + // A backup made just before midnight, first reported after it, goes on its own day + if ($made !== '' && $made !== $today && $made >= date('Y-m-d', strtotime('-2 days'))) { + mysqli_query($mysqli, "UPDATE managed_instance_stats SET managed_stat_backup = 'ok' + WHERE managed_stat_instance_id = $instance_id AND managed_stat_date = '$made' AND managed_stat_backup <> 'ok'"); + } + + // Back after a gap - kept on today's row, from its last check-in to now + $last = $row['managed_instance_last_checkin_at'] ?? null; + if ($last && strtotime($last) < time() - MANAGED_OFFLINE_MINUTES * 60) { + $outages = json_decode((string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT managed_stat_outages FROM managed_instance_stats + WHERE managed_stat_instance_id = $instance_id AND managed_stat_date = '$today'"))[0] ?? ''), true) ?: []; + $outages[] = ['from' => date('Y-m-d H:i:s', strtotime($last)), 'to' => date('Y-m-d H:i:s')]; + mysqli_query($mysqli, "UPDATE managed_instance_stats SET managed_stat_outages = '" . mysqli_real_escape_string($mysqli, (string) json_encode(array_slice($outages, -50))) . "' + WHERE managed_stat_instance_id = $instance_id AND managed_stat_date = '$today'"); + } +} + +/** + * An instance's history for its page - the last $days days, from the first it has. Each day + * has its label and agents, invites, seat limit, clients, uploads and database size, errors, + * backup, uptime (a percentage) and minutes down - from the gaps that overlap it - null + * where there's nothing for that day. With them: since (its first day, or null with no history yet), the + * gaps in the period, newest first (from, to, ongoing), uptime over the period, the backups + * made and failed, the errors and their categories over the period, most first, and the + * storage unit (MB, or GB from 2 GB). + */ +function managedInstanceHistory(array $row, int $days): array +{ + global $mysqli; + + $instance_id = intval($row['managed_instance_id']); + $history = ['since' => null, 'days' => [], 'gaps' => [], 'uptime' => null, 'backups' => ['ok' => 0, 'failed' => 0, 'days' => 0], + 'errors' => 0, 'categories' => [], 'unit' => 'MB']; + if (!managedStatsReady()) { + return $history; + } + $since = mysqli_fetch_row(mysqli_query($mysqli, "SELECT MIN(managed_stat_date) FROM managed_instance_stats WHERE managed_stat_instance_id = $instance_id"))[0] ?? null; + if (!$since) { + return $history; + } + $history['since'] = $since; + $today = date('Y-m-d'); + $from = max($since, date('Y-m-d', strtotime('-' . ($days - 1) . ' days'))); + + $rows = []; + $result = mysqli_query($mysqli, "SELECT managed_stat_date, managed_stat_agents, managed_stat_invites, managed_stat_seat_limit, managed_stat_clients, + managed_stat_uploads_mb, managed_stat_db_mb, managed_stat_errors, managed_stat_error_categories, managed_stat_backup, managed_stat_outages + FROM managed_instance_stats WHERE managed_stat_instance_id = $instance_id AND managed_stat_date >= '$from' ORDER BY managed_stat_date"); + while ($stat = mysqli_fetch_assoc($result)) { + $rows[$stat['managed_stat_date']] = $stat; + } + + // The gaps - each kept on the day it ended, so a gap that began before the period is here + // too - and the one going on now, if it has stopped checking in + $now = time(); + $period_start = strtotime($from); + $gaps = []; + foreach ($rows as $stat) { + foreach (json_decode((string) $stat['managed_stat_outages'], true) ?: [] as $gap) { + $gaps[] = ['from' => strtotime((string) ($gap['from'] ?? '')), 'to' => strtotime((string) ($gap['to'] ?? '')), 'ongoing' => false]; + } + } + $last = $row['managed_instance_last_checkin_at'] ?? null; + $watched = !empty($row['managed_instance_secret_hash']) && empty($row['managed_instance_archived_at']); + if ($watched && $last && strtotime($last) < $now - MANAGED_OFFLINE_MINUTES * 60) { + $gaps[] = ['from' => strtotime($last), 'to' => $now, 'ongoing' => true]; + } + $gaps = array_values(array_filter($gaps, function ($gap) use ($period_start) { + return $gap['from'] && $gap['to'] > $gap['from'] && $gap['to'] > $period_start; + })); + usort($gaps, function ($a, $b) { + return $b['from'] <=> $a['from']; + }); + $history['gaps'] = $gaps; + + $mb = 0.0; + $down_total = 0; + $minutes_total = 0; + $day = new DateTime($from); + while ($day->format('Y-m-d') <= $today) { + $date = $day->format('Y-m-d'); + $start = $day->getTimestamp(); + $end = min((clone $day)->modify('+1 day')->getTimestamp(), $now); + $down = 0; + foreach ($gaps as $gap) { + $down += max(0, min($end, $gap['to']) - max($start, max($gap['from'], $period_start))); + } + $stat = $rows[$date] ?? null; + $length = max(1, $end - $start); + if ($stat || $down > 0) { + $down_total += min($down, $length); + $minutes_total += $length; + } + $entry = [ + 'label' => $day->format('M j'), + 'date' => $date, + 'uptime' => $stat || $down > 0 ? round(max(0, 100 * (1 - $down / $length)), 1) : null, + 'down' => $stat || $down > 0 ? (int) round(min($down, $length) / 60) : null, + 'agents' => null, 'invites' => null, 'limit' => null, 'clients' => null, 'uploads' => null, 'db' => null, 'errors' => null, 'backup' => null, + ]; + if ($stat) { + $entry = array_merge($entry, [ + 'agents' => intval($stat['managed_stat_agents']), + 'invites' => intval($stat['managed_stat_invites']), + 'limit' => intval($stat['managed_stat_seat_limit']), + 'clients' => intval($stat['managed_stat_clients']), + 'uploads' => floatval($stat['managed_stat_uploads_mb']), + 'db' => floatval($stat['managed_stat_db_mb']), + 'errors' => intval($stat['managed_stat_errors']), + 'backup' => (string) $stat['managed_stat_backup'], + ]); + $mb = max($mb, $entry['uploads'] + $entry['db']); + $history['errors'] += $entry['errors']; + foreach (json_decode((string) $stat['managed_stat_error_categories'], true) ?: [] as $category => $logged) { + $history['categories'][$category] = ($history['categories'][$category] ?? 0) + intval($logged); + } + $history['backups']['days']++; + if ($entry['backup'] === 'ok') { + $history['backups']['ok']++; + } elseif ($entry['backup'] === 'failed') { + $history['backups']['failed']++; + } + } + $history['days'][] = $entry; + $day->modify('+1 day'); + } + arsort($history['categories']); + $history['uptime'] = $minutes_total ? round(100 * (1 - $down_total / $minutes_total), 2) : null; + $history['unit'] = $mb >= 2048 ? 'GB' : 'MB'; + return $history; +} + /* * A new connection code for an instance - the old one stops working. The code carries this * ITFlow's address and a token that works once, for a week; the manager keeps only its hash. @@ -1750,6 +1945,9 @@ function managerCheckin(string $authorization, array $body, string $ip): array } mysqli_query($mysqli, "UPDATE managed_instances SET " . implode(', ', $set) . " WHERE managed_instance_id = $instance_id"); + // Today's line of its history - with the gap it is back from, if any + managedStatsRecord($row, $body); + // The commands it answered foreach ($acks as $ack) { $command_id = intval($ack['id'] ?? 0);