diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0fcceb36e..c1788ca6a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,14 +6,15 @@ 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 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.
+Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's three database changes (4.1.8 to 4.2.0) 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 with columns for its usage, 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. Each instance's history starts with its first check-in after the manager is updated - there is none from before.
+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 - and its usage once the instance is updated too.
### 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: how much each instance is used. Its History card has a Usage part - tickets opened and resolved and those that came in by email, replies and notes by its agents, how many agents signed in each day and over the last 30 days, client portal sign-ins, invoices made and payments recorded, email sent and failed, and API calls with the keys that made the most of them - each day as the instance counts it, by its own date. The list has a Last 30 days column - tickets opened, how many of its agents signed in and when one last did, and API calls - and sorting by it puts the ones hardly used first. Only counts are sent, never what any of them say, and Managed By on the instance says so.
- 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.
@@ -34,6 +35,9 @@ If you manage other ITFlow installs, the manager and its instances can be update
- `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.
+- Usage: `managedUsage()` counts the instance's today and yesterday, by its own date, with a `GROUP BY` of the day each - `tickets_opened` and `tickets_email` (`ticket_created_at`, `ticket_source = 'Email'`), `tickets_resolved`, `replies` (`ticket_reply_by > 0` and not `Client`), `invoices` (`invoice_created_at`), `payments` (`payment_created_at`), `agent_signins` (distinct `Login` `Success` log users, not the support user), `portal_signins` (`Client Login` `Success`), `emails_sent` and `emails_failed` (`email_queue` status 3 by `email_sent_at`, 2 by `email_failed_at`), and `api_calls` with `api_keys` - the ten keys' names with most calls, from `api_key_usage` - and `agents_30d`. A count that can't be made is left out. `managedReport()` sends it as `usage` (`days`, `agents_30d`, `measured_at`), counted at most every ten minutes and kept in `config_managed.usage` meanwhile.
+- Database 4.2.0: `managed_instance_stats` gets a column for each of `MANAGED_USAGE_FIGURES`, `_api_keys` (JSON) and `_agents_30d`, all NULL for a day nothing was reported. Re-runnable. `managedStatsRecord()` writes each of the instance's days onto the row of the same date, when it is there and within three days, and `_agents_30d` onto today's; `managedUsageReady()` guards it. `managedInstanceHistory()` adds each day's figures, `usage` (their totals, or null), `api_keys` and `agents_30d`, and the weekly view adds the figures up - `agent_signins` taking the week's highest day.
+- `admin/managed_instances.php` reads each instance's last 30 days in one query, and sorts by tickets opened in them as `usage_tickets` - a sort key keeps to letters and underscores, as `filter_header.php` strips anything else. The Health column wraps, so the table fits.
## [26.12.1]
diff --git a/admin/database_updates/4.2.0.php b/admin/database_updates/4.2.0.php
new file mode 100644
index 000000000..772feffb3
--- /dev/null
+++ b/admin/database_updates/4.2.0.php
@@ -0,0 +1,40 @@
+ "int(11) DEFAULT NULL AFTER `managed_stat_outages`",
+ 'managed_stat_tickets_email' => "int(11) DEFAULT NULL AFTER `managed_stat_tickets_opened`",
+ 'managed_stat_tickets_resolved' => "int(11) DEFAULT NULL AFTER `managed_stat_tickets_email`",
+ 'managed_stat_replies' => "int(11) DEFAULT NULL AFTER `managed_stat_tickets_resolved`",
+ 'managed_stat_invoices' => "int(11) DEFAULT NULL AFTER `managed_stat_replies`",
+ 'managed_stat_payments' => "int(11) DEFAULT NULL AFTER `managed_stat_invoices`",
+ 'managed_stat_agent_signins' => "int(11) DEFAULT NULL AFTER `managed_stat_payments`",
+ 'managed_stat_portal_signins' => "int(11) DEFAULT NULL AFTER `managed_stat_agent_signins`",
+ 'managed_stat_emails_sent' => "int(11) DEFAULT NULL AFTER `managed_stat_portal_signins`",
+ 'managed_stat_emails_failed' => "int(11) DEFAULT NULL AFTER `managed_stat_emails_sent`",
+ 'managed_stat_api_calls' => "int(11) DEFAULT NULL AFTER `managed_stat_emails_failed`",
+ 'managed_stat_api_keys' => "text DEFAULT NULL AFTER `managed_stat_api_calls`",
+ 'managed_stat_agents_30d' => "int(11) DEFAULT NULL AFTER `managed_stat_api_keys`",
+ ];
+ foreach ($itflow_usage_columns as $itflow_usage_column => $itflow_usage_definition) {
+ $itflow_column_exists = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS
+ WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'managed_instance_stats' AND COLUMN_NAME = '$itflow_usage_column' LIMIT 1");
+ if (!$itflow_column_exists || mysqli_num_rows($itflow_column_exists) === 0) {
+ mysqli_query($mysqli, "ALTER TABLE `managed_instance_stats` ADD `$itflow_usage_column` $itflow_usage_definition");
+ }
+ }
diff --git a/admin/managed_by.php b/admin/managed_by.php
index 7c68530a7..f52e73d53 100644
--- a/admin/managed_by.php
+++ b/admin/managed_by.php
@@ -112,7 +112,7 @@ $lock = 'What a manager can do
- - See how it's doing - versions, updates, cron, backups, errors, and who holds its seats. No client data leaves here.
+ - See how it's doing - versions, updates, cron, backups, errors, who holds its seats and how much it's used. No client data leaves here.
- Update it, by hand or automatically - and then updates come only from there.
- Set how many agents it can have, and its white-label key.
- Sign in as support, for two hours at a time - each time in the audit log, and you're notified.
@@ -197,6 +197,7 @@ $lock = 'No tickets, documents, credentials, invoices or contacts.
diff --git a/admin/managed_instance.php b/admin/managed_instance.php
index 5f5523632..e2bfe4a64 100644
--- a/admin/managed_instance.php
+++ b/admin/managed_instance.php
@@ -411,7 +411,7 @@ if ($error_count > 0) {
return $values ? array_sum($values) : null;
};
$backups = array_filter(array_column($week, 'backup'), function ($v) { return $v !== null; });
- $history_bars[] = [
+ $bucket = [
'label' => $week[0]['label'],
'title' => $week[0]['label'] . ' - ' . end($week)['label'],
'errors' => $sum('errors'),
@@ -420,6 +420,12 @@ if ($error_count > 0) {
'made' => count(array_keys($backups, 'ok', true)),
'heard' => count($backups),
];
+ // Usage adds up over the week - but agents signed in is the most on any one day of it
+ foreach (MANAGED_USAGE_FIGURES as $figure) {
+ $values = array_filter(array_column($week, $figure), function ($v) { return $v !== null; });
+ $bucket[$figure] = !$values ? null : ($figure === 'agent_signins' ? max($values) : array_sum($values));
+ }
+ $history_bars[] = $bucket;
}
}
$bar_labels = array_column($history_bars, 'label');
@@ -556,6 +562,70 @@ if ($error_count > 0) {
echo $history_block('Backups', $figure, $strip);
?>
+
+
+ Its usage shows once it runs a version that counts it.
+
+
+ 'bar', 'labels' => $bar_labels, 'format' => 'count', 'series' => [
+ ['label' => "Opened$bar_period", 'data' => $bars('tickets_opened'), 'tone' => 'accent'],
+ ['label' => "Resolved$bar_period", 'data' => $bars('tickets_resolved'), 'tone' => 'muted'],
+ ]], 'sm', 'Tickets opened and resolved'));
+
+ // Agents' replies
+ echo $history_block('Replies', $total('replies') . ' replies and notes by agents', reportChart(['type' => 'bar', 'labels' => $bar_labels, 'format' => 'count', 'legend' => false,
+ 'series' => [['label' => "Replies and notes$bar_period", 'data' => $bars('replies'), 'tone' => 'accent']]], 'sm', 'Replies by agents'));
+
+ // Who signs in - agents each day, against the agents it has
+ $figure = ($history['agents_30d'] !== null ? $history['agents_30d'] . ($history_now ? ' of ' . intval($history_now['agents']) : '') . ' agents signed in over the last 30 days' : 'Agents who signed in')
+ . ' - ' . $total('portal_signins') . ' client portal sign-ins';
+ echo $history_block('Signing in', $figure, reportChart(['type' => 'bar', 'labels' => $bar_labels, 'format' => 'count', 'legend' => false,
+ 'series' => [['label' => $history_weekly ? 'Most agents signed in on a day that week' : 'Agents signed in', 'data' => $bars('agent_signins'), 'tone' => 'accent']]], 'sm', 'Agents signed in'));
+
+ // Invoices made and payments recorded
+ echo $history_block('Billing', $total('invoices') . ' invoices made, ' . $total('payments') . ' payments recorded', reportChart(['type' => 'bar', 'labels' => $bar_labels, 'format' => 'count', 'series' => [
+ ['label' => "Invoices$bar_period", 'data' => $bars('invoices'), 'tone' => 'accent'],
+ ['label' => "Payments$bar_period", 'data' => $bars('payments'), 'tone' => 'muted'],
+ ]], 'sm', 'Invoices and payments'));
+
+ // Email sent, and what failed
+ echo $history_block('Email', $total('emails_sent') . ' sent - ' . $total('emails_failed') . ' failed', reportChart(['type' => 'bar', 'labels' => $bar_labels, 'format' => 'count', 'series' => [
+ ['label' => "Sent$bar_period", 'data' => $bars('emails_sent'), 'tone' => 'accent'],
+ ['label' => "Failed$bar_period", 'data' => $bars('emails_failed'), 'tone' => 'danger'],
+ ]], 'sm', 'Email sent and failed'));
+
+ // API calls, and the keys making them
+ $keys_html = '';
+ if ($history['api_keys']) {
+ $named = [];
+ foreach (array_slice($history['api_keys'], 0, 5, true) as $name => $calls) {
+ $named[] = escapeHtml($name) . '
' . number_format($calls) . '';
+ }
+ $more = count($history['api_keys']) - count($named);
+ $keys_html = '
' . implode(' · ', $named) . ($more > 0 ? " and $more more" : '') . '
';
+ }
+ echo $history_block('API calls', $total('api_calls') . ' calls', reportChart(['type' => 'bar', 'labels' => $bar_labels, 'format' => 'count', 'legend' => false,
+ 'series' => [['label' => "Calls$bar_period", 'data' => $bars('api_calls'), 'tone' => 'accent']]], 'sm', 'API calls') . $keys_html);
+ ?>
+
+
diff --git a/admin/managed_instances.php b/admin/managed_instances.php
index f4659ccb8..2618e63b9 100644
--- a/admin/managed_instances.php
+++ b/admin/managed_instances.php
@@ -40,6 +40,12 @@ $sortable_columns = [
'managed_instance_last_checkin_at' => "managed_instance_last_checkin_at IS NULL, managed_instance_last_checkin_at $order, managed_instance_name ASC",
'client_name' => "client_name IS NULL, client_name $order, managed_instance_name ASC",
];
+// Its use over the last 30 days - tickets opened, from its history (managedStatsRecord())
+$usage_ready = managedUsageReady();
+if ($usage_ready) {
+ $sortable_columns['usage_tickets'] = "(SELECT COALESCE(SUM(managed_stat_tickets_opened), 0) FROM managed_instance_stats
+ WHERE managed_stat_instance_id = managed_instance_id AND managed_stat_date > CURDATE() - INTERVAL 30 DAY) $order, managed_instance_name ASC";
+}
if (!isset($sortable_columns[$sort])) {
$sort = 'managed_instance_name';
}
@@ -101,12 +107,23 @@ $csrf = $_SESSION['csrf_token'];
- CURDATE() - INTERVAL 30 DAY GROUP BY managed_stat_instance_id");
+ while ($usage_row = mysqli_fetch_row($result)) {
+ $usage_30d[intval($usage_row[0])] = ['tickets' => intval($usage_row[1]), 'api_calls' => intval($usage_row[2]), 'counted' => intval($usage_row[3]) > 0];
+ }
+ }
+ while ($row = mysqli_fetch_assoc($sql)) {
$instance_id = intval($row['managed_instance_id']);
$name = escapeHtml($row['managed_instance_name']);
$health = managedInstanceHealth($row);
@@ -155,7 +172,7 @@ $csrf = $_SESSION['csrf_token'];
-
-
+ |
-
@@ -175,6 +192,26 @@ $csrf = $_SESSION['csrf_token'];
-
|
+
+
+
+ -
+
+ = number_format($usage['tickets']) ?> ticket= $usage['tickets'] === 1 ? '' : 's' ?>
+
+ = $agents_30d ?>= !empty($agents['active']) ? ' of ' . intval($agents['active']) : '' ?> agent= $agents_30d === 1 && empty($agents['active']) ? '' : 's' ?> signed in
+
+ Last sign-in = escapeHtml(timeAgo(date('Y-m-d H:i:s', $signed_in))) ?>
+ = number_format($usage['api_calls']) ?> API calls
+
+ |
+
= $last_html ?> |
diff --git a/db.sql b/db.sql
index 79a51048e..429965b18 100644
--- a/db.sql
+++ b/db.sql
@@ -2353,6 +2353,19 @@ CREATE TABLE `managed_instance_stats` (
`managed_stat_version` varchar(20) NOT NULL DEFAULT '',
`managed_stat_checkins` int(11) NOT NULL DEFAULT 0,
`managed_stat_outages` text DEFAULT NULL,
+ `managed_stat_tickets_opened` int(11) DEFAULT NULL,
+ `managed_stat_tickets_email` int(11) DEFAULT NULL,
+ `managed_stat_tickets_resolved` int(11) DEFAULT NULL,
+ `managed_stat_replies` int(11) DEFAULT NULL,
+ `managed_stat_invoices` int(11) DEFAULT NULL,
+ `managed_stat_payments` int(11) DEFAULT NULL,
+ `managed_stat_agent_signins` int(11) DEFAULT NULL,
+ `managed_stat_portal_signins` int(11) DEFAULT NULL,
+ `managed_stat_emails_sent` int(11) DEFAULT NULL,
+ `managed_stat_emails_failed` int(11) DEFAULT NULL,
+ `managed_stat_api_calls` int(11) DEFAULT NULL,
+ `managed_stat_api_keys` text DEFAULT NULL,
+ `managed_stat_agents_30d` int(11) 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;
diff --git a/functions/managed.php b/functions/managed.php
index a63941638..5a3c384c5 100644
--- a/functions/managed.php
+++ b/functions/managed.php
@@ -39,6 +39,10 @@ const MANAGED_OFFLINE_MINUTES = 10;
// How long a problem lasts before it opens a ticket - so a blip doesn't (managerIssueTickets())
const MANAGED_ISSUE_GRACE_MINUTES = 10;
+// The usage figures an instance counts each day (managedUsage()), each a managed_instance_stats column
+const MANAGED_USAGE_FIGURES = ['tickets_opened', 'tickets_email', 'tickets_resolved', 'replies', 'invoices', 'payments',
+ 'agent_signins', 'portal_signins', 'emails_sent', 'emails_failed', 'api_calls'];
+
/* A support sign-in link works this long; the session it opens, this long */
const MANAGED_SUPPORT_LINK_SECONDS = 120;
const MANAGED_SUPPORT_SESSION_HOURS = 2;
@@ -169,6 +173,7 @@ function managedHttpJson(string $url, array $body, array $headers = []): array
* report_encoding how the manager reads a report - 'base64url', or '' for plain JSON
* acks answers to commands, sent with the next check-in
* metrics disk and database size, measured every half hour
+ * usage how much it was used today and yesterday, counted every ten minutes (managedUsage())
* white_label_applied the key the manager put in, if it did
* nonces support links already used, until they expire
*/
@@ -442,10 +447,88 @@ function managedDirMb(string $dir): float
return round($bytes / 1048576, 1);
}
+/*
+ * How much this ITFlow was used today and yesterday, by its own date - counts only, never what
+ * any of it says: tickets opened (and those by email) and resolved, agents' replies, invoices
+ * made, payments recorded, agents who signed in (not the support user) and client portal
+ * sign-ins, emails sent and failed, and API calls - in all, and under each key's name. With
+ * them, how many agents signed in over the last 30 days. ['days' => [date => counts],
+ * 'agents_30d' => n] - each part that can't be counted (a table not there yet) left out.
+ */
+function managedUsage(): array
+{
+ global $mysqli;
+
+ $since = date('Y-m-d', strtotime('-1 day'));
+ $days = [date('Y-m-d') => [], $since => []];
+ $support = managedSupportUserId();
+ $not_support = $support ? " AND log_user_id <> $support" : '';
+ // Each count, by day - a query giving the day and its figures, each figure under its key
+ $count = function (string $sql, array $keys) use ($mysqli, &$days) {
+ try {
+ $result = mysqli_query($mysqli, $sql);
+ while ($result && ($row = mysqli_fetch_row($result))) {
+ if (isset($days[$row[0]])) {
+ foreach ($keys as $i => $key) {
+ $days[$row[0]][$key] = intval($row[$i + 1]);
+ }
+ }
+ }
+ // A day with none is 0, not missing
+ foreach ($days as $day => $figures) {
+ foreach ($keys as $key) {
+ $days[$day][$key] = $days[$day][$key] ?? 0;
+ }
+ }
+ } catch (Throwable $e) {
+ // Not counted - left out
+ }
+ };
+ $count("SELECT DATE(ticket_created_at) d, COUNT(*), SUM(ticket_source = 'Email') FROM tickets WHERE ticket_created_at >= '$since' GROUP BY d", ['tickets_opened', 'tickets_email']);
+ $count("SELECT DATE(ticket_resolved_at) d, COUNT(*) FROM tickets WHERE ticket_resolved_at >= '$since' GROUP BY d", ['tickets_resolved']);
+ $count("SELECT DATE(ticket_reply_created_at) d, COUNT(*) FROM ticket_replies WHERE ticket_reply_by > 0 AND ticket_reply_type <> 'Client' AND ticket_reply_created_at >= '$since' GROUP BY d", ['replies']);
+ $count("SELECT DATE(invoice_created_at) d, COUNT(*) FROM invoices WHERE invoice_created_at >= '$since' GROUP BY d", ['invoices']);
+ $count("SELECT DATE(payment_created_at) d, COUNT(*) FROM payments WHERE payment_created_at >= '$since' GROUP BY d", ['payments']);
+ $count("SELECT DATE(log_created_at) d, COUNT(DISTINCT log_user_id) FROM logs WHERE log_type = 'Login' AND log_action = 'Success' AND log_created_at >= '$since'$not_support GROUP BY d", ['agent_signins']);
+ $count("SELECT DATE(log_created_at) d, COUNT(*) FROM logs WHERE log_type = 'Client Login' AND log_action = 'Success' AND log_created_at >= '$since' GROUP BY d", ['portal_signins']);
+ $count("SELECT DATE(email_sent_at) d, COUNT(*) FROM email_queue WHERE email_status = 3 AND email_sent_at >= '$since' GROUP BY d", ['emails_sent']);
+ $count("SELECT DATE(email_failed_at) d, COUNT(*) FROM email_queue WHERE email_status = 2 AND email_failed_at >= '$since' GROUP BY d", ['emails_failed']);
+
+ // API calls, in all and under each key's name - the ten most used
+ try {
+ $result = mysqli_query($mysqli, "SELECT api_key_usage_date, COALESCE(api_key_name, 'A deleted key'), SUM(api_key_usage_calls) AS calls FROM api_key_usage
+ LEFT JOIN api_keys ON api_key_id = api_key_usage_key_id WHERE api_key_usage_date >= '$since' GROUP BY api_key_usage_date, api_key_usage_key_id ORDER BY calls DESC");
+ foreach ($days as $day => $figures) {
+ $days[$day]['api_calls'] = 0;
+ $days[$day]['api_keys'] = [];
+ }
+ while ($result && ($row = mysqli_fetch_row($result))) {
+ if (isset($days[$row[0]])) {
+ $days[$row[0]]['api_calls'] += intval($row[2]);
+ if (count($days[$row[0]]['api_keys']) < 10) {
+ $name = mb_substr((string) $row[1], 0, 100);
+ $days[$row[0]]['api_keys'][$name] = ($days[$row[0]]['api_keys'][$name] ?? 0) + intval($row[2]);
+ }
+ }
+ }
+ foreach ($days as $day => $figures) {
+ $days[$day]['api_keys'] = (object) $days[$day]['api_keys'];
+ }
+ } catch (Throwable $e) {
+ // No API usage table yet - left out
+ }
+
+ $agents_30d = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(DISTINCT log_user_id) FROM logs
+ WHERE log_type = 'Login' AND log_action = 'Success' AND log_created_at > NOW() - INTERVAL 30 DAY$not_support"))[0] ?? 0);
+
+ return ['days' => $days, 'agents_30d' => $agents_30d];
+}
+
/*
* How this ITFlow is doing, for its manager - versions, updates, cron, backups, errors,
- * agents against the seat limit and who they are, and disk and database size (measured every half hour,
- * as walking the uploads folder isn't free). Times carry their offset (managedIsoTime()).
+ * agents against the seat limit and who they are, disk and database size (measured every
+ * half hour, as walking the uploads folder isn't free), and how much it is used (counted every
+ * ten minutes - managedUsage()). Times carry their offset (managedIsoTime()).
*/
function managedReport(): array
{
@@ -532,6 +615,14 @@ function managedReport(): array
managedConfigSave($config);
}
+ // How much it's used - today and yesterday, by its own date - every ten minutes
+ $usage = (array) ($config['usage'] ?? []);
+ if (empty($usage['measured_at']) || strtotime($usage['measured_at']) < strtotime('-10 minutes')) {
+ $usage = managedUsage() + ['measured_at' => date('Y-m-d H:i:s')];
+ $config['usage'] = $usage;
+ managedConfigSave($config);
+ }
+
return [
'url' => (string) ($config['self_url'] ?? ''),
'company' => $company,
@@ -580,6 +671,8 @@ function managedReport(): array
],
'clients' => $clients,
'disk' => ['measured_at' => managedIsoTime($metrics['measured_at'] ?? null)] + $metrics,
+ // An object even when empty - {} rather than []
+ 'usage' => ['days' => (object) ($usage['days'] ?? []), 'agents_30d' => intval($usage['agents_30d'] ?? 0), 'measured_at' => managedIsoTime($usage['measured_at'] ?? null)],
'mode' => managedMode(),
];
}
@@ -1517,6 +1610,46 @@ function managedStatsRecord(array $row, array $report): void
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'");
}
+
+ // How much it was used - each day it counted (its today and yesterday, by its own date) on
+ // that day's row, when there is one; an instance too old to count sends none
+ if (!managedUsageReady() || !is_array($report['usage'] ?? null)) {
+ return;
+ }
+ $usage = $report['usage'];
+ foreach ((array) ($usage['days'] ?? []) as $date => $figures) {
+ if (!is_array($figures) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) $date) || $date > $today || $date < date('Y-m-d', strtotime('-3 days'))) {
+ continue;
+ }
+ $set = [];
+ foreach (MANAGED_USAGE_FIGURES as $figure) {
+ $set[] = "managed_stat_$figure = " . (array_key_exists($figure, $figures) ? max(0, intval($figures[$figure])) : 'NULL');
+ }
+ $keys = [];
+ foreach ((array) ($figures['api_keys'] ?? []) as $name => $calls) {
+ $keys[mb_substr((string) $name, 0, 100)] = max(0, intval($calls));
+ }
+ $set[] = "managed_stat_api_keys = " . (array_key_exists('api_keys', $figures) ? "'" . mysqli_real_escape_string($mysqli, (string) json_encode((object) array_slice($keys, 0, 10, true))) . "'" : 'NULL');
+ mysqli_query($mysqli, "UPDATE managed_instance_stats SET " . implode(', ', $set) . "
+ WHERE managed_stat_instance_id = $instance_id AND managed_stat_date = '" . escapeSql($date) . "'");
+ }
+ mysqli_query($mysqli, "UPDATE managed_instance_stats SET managed_stat_agents_30d = " . max(0, intval($usage['agents_30d'] ?? 0)) . "
+ WHERE managed_stat_instance_id = $instance_id AND managed_stat_date = '$today'");
+}
+
+/** Whether the history has its usage columns - they arrive with the 4.2.0 database update. */
+function managedUsageReady(): bool
+{
+ global $mysqli;
+ static $ready = null;
+ if ($ready === null) {
+ try {
+ $ready = (bool) mysqli_query($mysqli, "SELECT managed_stat_agents_30d FROM managed_instance_stats LIMIT 1");
+ } catch (Throwable $e) {
+ $ready = false;
+ }
+ }
+ return $ready;
}
/**
@@ -1526,7 +1659,9 @@ function managedStatsRecord(array $row, array $report): void
* 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).
+ * storage unit (MB, or GB from 2 GB). Usage, when it reports it: each day's figures
+ * (MANAGED_USAGE_FIGURES - null for a day it didn't), their totals over the period (usage - null
+ * when there were none), the API keys' calls over it, most first, and agents_30d, the latest.
*/
function managedInstanceHistory(array $row, int $days): array
{
@@ -1534,7 +1669,7 @@ function managedInstanceHistory(array $row, int $days): array
$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'];
+ 'errors' => 0, 'categories' => [], 'unit' => 'MB', 'usage' => null, 'api_keys' => [], 'agents_30d' => null];
if (!managedStatsReady()) {
return $history;
}
@@ -1547,8 +1682,10 @@ function managedInstanceHistory(array $row, int $days): array
$from = max($since, date('Y-m-d', strtotime('-' . ($days - 1) . ' days')));
$rows = [];
+ $usage_ready = managedUsageReady();
+ $usage_columns = $usage_ready ? ', managed_stat_' . implode(', managed_stat_', MANAGED_USAGE_FIGURES) . ', managed_stat_api_keys, managed_stat_agents_30d' : '';
$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
+ managed_stat_uploads_mb, managed_stat_db_mb, managed_stat_errors, managed_stat_error_categories, managed_stat_backup, managed_stat_outages$usage_columns
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;
@@ -1602,6 +1739,9 @@ function managedInstanceHistory(array $row, int $days): array
'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,
];
+ foreach (MANAGED_USAGE_FIGURES as $figure) {
+ $entry[$figure] = null;
+ }
if ($stat) {
$entry = array_merge($entry, [
'agents' => intval($stat['managed_stat_agents']),
@@ -1618,6 +1758,19 @@ function managedInstanceHistory(array $row, int $days): array
foreach (json_decode((string) $stat['managed_stat_error_categories'], true) ?: [] as $category => $logged) {
$history['categories'][$category] = ($history['categories'][$category] ?? 0) + intval($logged);
}
+ // How much it was used, when it said - totals over the period, and the API keys' calls
+ foreach (MANAGED_USAGE_FIGURES as $figure) {
+ if (isset($stat["managed_stat_$figure"])) {
+ $entry[$figure] = intval($stat["managed_stat_$figure"]);
+ $history['usage'][$figure] = ($history['usage'][$figure] ?? 0) + $entry[$figure];
+ }
+ }
+ foreach (json_decode((string) ($stat['managed_stat_api_keys'] ?? ''), true) ?: [] as $name => $calls) {
+ $history['api_keys'][$name] = ($history['api_keys'][$name] ?? 0) + intval($calls);
+ }
+ if (isset($stat['managed_stat_agents_30d'])) {
+ $history['agents_30d'] = intval($stat['managed_stat_agents_30d']);
+ }
$history['backups']['days']++;
if ($entry['backup'] === 'ok') {
$history['backups']['ok']++;
@@ -1629,6 +1782,7 @@ function managedInstanceHistory(array $row, int $days): array
$day->modify('+1 day');
}
arsort($history['categories']);
+ arsort($history['api_keys']);
$history['uptime'] = $minutes_total ? round(100 * (1 - $down_total / $minutes_total), 2) : null;
$history['unit'] = $mb >= 2048 ? 'GB' : 'MB';
return $history;
|