diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bcb448bf..2abf4523e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,6 +114,9 @@ Update from Maintenance > Update as usual - this release has fifteen database ch - Email-to-ticket: an email with no sender address was answered at itflow-guest@example.com, which was also made the ticket's CC - each email to it failed in the mail queue. It's from nobody now: a ticket with no client when unknown senders are let in, saying it has no sender address, with nobody answered or copied in, and on a ticket an internal note that reopens nothing - it matched a contact with no email address before. - Email-to-ticket: an address that's a contact at more than one client - someone who works for two, a shared mailbox - raised its tickets at whichever client the database gave first. It's the client whose domain it's at now, else the one they last raised a ticket at, and a note on the ticket names the others, to change its client if it's theirs. - Mail queue: every email in a run went out with the first one's sender as its envelope sender - where bounces go - so an invoice sent after a ticket email bounced to the ticket mailbox, and a mail server that checks who may send as whom could turn it away. Each goes as itself now. +- UniFi through Site Manager with many sites (forum #3236): linked sites never got their devices - every sync spent its time asking each of hundreds of sites for its device count before reaching the linked ones, and said "0 devices brought in. Stopped for time" every time. Device counts now come from Site Manager's own list of sites in one or two requests, a console is only asked for its sites when it has one ITFlow doesn't know yet, listing new sites gets at most half a sync's time, and at least one linked site's devices come in each sync. +- Linking a network platform's site or an RMM's client, Sync Now, Test and saving a provider no longer freeze your other ITFlow pages while the RMM or UniFi answers, and linking brings in just that one's devices instead of listing every site first. +- UniFi asking ITFlow to slow down (HTTP 429) - Site Manager allows 100 requests a minute for each console - is waited out when it's a few seconds and said plainly otherwise, where it was reported as consoles needing newer firmware. ### Developer Updates @@ -175,6 +178,7 @@ Update from Maintenance > Update as usual - this release has fifteen database ch - Mail review stage 7d: database 4.3.4 adds settings.config_guest_link_days (GUEST_LINK_DAYS_CHOICES, 90) and email_templates. functions/guest_link.php: guestLinkDoneAt() - ticket_closed_at; a Paid invoice's last unarchived payment (else its Paid history, else invoice_updated_at); an Accepted, Declined or Invoiced quote's history for it, or the end of quote_expire for one unanswered - later of that and the last history line with 'emailed' in it; guestLinkExpired() adds the days. ticketByGuestKey() returns null for an expired link, setting its new &$expired, so the guest ticket page, its attachments, its posts and its calendar file all refuse it; guest_view_invoice.php, guest_view_quote.php, the guest PDF exports (410) and the quote upload check it too, and guestLinkExpiredHtml() is the page; agent/invoice.php and agent/quote.php mark Copy Client Link Expired. functions/email_template.php: EMAIL_TEMPLATES (the 13 Tickets - to clients preview keys, with ITFlow's wording in placeholders), emailTemplateApply() replaces title, intro (paragraphs) and after where saved, filling [Placeholders] from emailTemplateValues() (ticketPlaceholderValues() and the email's own; empty when there is nothing), and puts the subject in template_subject for emailTemplateSubject(), which prefixes [REF] when it isn't in it. Applied in ticketEmailContent() (not the stranger's subject, nor Resolve - no response's intro), ticketMailSend(), ticketMailCcsAdded(), ticketMailColleaguesNew(), ticketMailTaskApproval() (the client's only) and ticketMailClosedReply(). admin/modals/email_template/email_template_edit.php and admin/post/email_template.php (save_email_template, reset_email_template - a part sent back as the default is NULL); mail_preview.php answers template and edited. - Mail review stage 8: database 4.3.5 adds email_ignored_senders and email_queue.email_message_id (indexed, filled in from email_headers), email_about, email_bounced_at and email_bounce. functions/mail_ignore.php: mailIgnoreClean() takes an address or a domain (@ or *@ in front allowed), mailIgnoreFind() matches the From address - an address rule before a domain one, a domain matching its subdomains - and cron/ticket_email_parser.php sets the email aside (seen, moved, mailIgnoreHit()) after the bounce check, unless it is a MailUnprocessedMessage asked to make a ticket or reply; ticketMailTry() has the step. Admin > Ignored Senders (admin/email_ignored_senders.php, modals/email_ignored_sender/, admin/post/email_ignored_sender.php). The parser leaves email from someone who isn't a contact at a domain no client has (unknown senders off), or whose sender checks failed, in the inbox flagged as before 7b - mailUnprocessedLeave() keeps only an email that was taken and failed, or an agent's ask; ticketMailTry() says Left in the inbox. emailQueue() gives every email a Message-ID (emailMessageId()) where the conversation gave none and takes about (invoice:N, quote:N - billingEmailQueue()'s about, passed by every invoice and quote send); addToMailQueue() keeps both. addBounce() calls mailQueueBounced(): the sent row by email_message_id, else the last week's sent to a failed address with the bounce's subject, marked with {address: why}, and a billing email's history written. mailQueueStateOf() has bounced (status 3 with email_bounced_at), mailQueueTabs() a Bounced tab, ticketReplyEmailStates() marks each bounced recipient and the key bounced, and ticketReplyEmailHtml() says so. A report naming an address that isn't on the email, or nobody: on an email to one person it is theirs ("address: why"); on one to several the named address is kept in email_bounce as it is, nobody on it is marked, and the reply has elsewhere => [address or '' => why]. A billing email's history is written the first time and for each address more. With config_ticket_email_parse_unknown_senders off the parser moves only what is ITFlow's: addBounce() takes $take_all and returns whether it was (a ticket by Message-ID or subject, emailMessageIdOurs() - itflow..@ or itflow.q.@, or in email_queue - mailQueueBounceRow(), the find split from mailQueueBounced(), or a contact's address), the own-address step moves only an email with ITFlow's Message-ID, a ticket's number in its subject or a ticket's email that it answers, and an auto-reply answering no ticket is set aside only from a contact, a client's domain or in answer to an ITFlow Message-ID (In-Reply-To, References); the rest is flagged and left, as a stranger's email is. .gitignore leaves out uploads/mail_unprocessed and uploads/kb, as the other upload folders. - Text messaging receive only: database 4.3.6 adds sms_providers.sms_provider_send (1, or 0 for Receive only). smsSends() reads it; smsReady() is false when a provider doesn't send, so smsQueue() and everything that texts stops there, and smsNotSendingWhy() says why. smsReceiveOnly() and smsTicketTextedInNumber() drive the notes on Text Messaging, Text Messages, Settings > Notifications and Tickets and the ticket reply box; smsProviderCheck() needs the SID and secret only when sending; setting a provider to Receive only cancels the texts waiting to go (smsCancelWaiting()). Inbound (api/sms/skyetel.php, smsInbound()) is unchanged. +- RMM sync (forum #3236): rmmSync() skips the client listing when $only is given, gives it half of $max_seconds through rmmDeadline() (rmmPastDeadline() for a kind to leave out what can wait), always syncs at least one linked client, records each synced client's device count, keeps the stored count when a kind returns devices null, and marks clients gone only from a whole list (a kind returns 'partial' with what it left). rmmUnifiSites() for unifi_cloud takes counts from Site Manager's GET /v1/sites (rmmUnifiSiteManagerSites(), by hostId and meta.name = internalReference), asks a console's connector for sites only when it has sites not in rmm_clients (rmmUnifiKnownSites()), and stops asking at the deadline; unifi_os counts per site only up to UNIFI_COUNT_SITES_MAX (50). rmmHttp() waits out a 429 with Retry-After up to RMM_RETRY_WAIT (10 s) and retries once (rmmHttpOnce() is one request), with a 'rate' hint. rmmWithoutSession() closes the PHP session around the slow calls in admin/post/rmm.php and agent/post/asset.php and reopens it for the message. ## [26.12.2] diff --git a/admin/post/rmm.php b/admin/post/rmm.php index 77609b327..f1373ec92 100644 --- a/admin/post/rmm.php +++ b/admin/post/rmm.php @@ -73,12 +73,18 @@ if (isset($_POST['check_rmm_provider']) || isset($_POST['add_rmm_provider']) || flashAlert('' . escapeHtml($name) . ' saved - it is off, so nothing is brought in'); redirect($back); } - $test = rmmTest($provider); + // Asking it can take a while - the agent's other pages don't wait on it (rmmWithoutSession()) + $test = rmmWithoutSession(function () use ($provider) { + $test = rmmTest($provider); + if ($test['ok']) { + rmmSync($provider, 0, 60); + } + return $test; + }); if (!$test['ok']) { flashAlert('' . escapeHtml($name) . ' saved, but it didn\'t answer: ' . escapeHtml($test['text']), 'warning'); redirect($back); } - rmmSync($provider, 0, 60); flashAlert('' . escapeHtml($name) . ' saved. ' . escapeHtml($test['text']) . ($before ? '' : ' Now link its ' . $words['clients'] . ' to your clients.')); redirect($back); @@ -94,7 +100,9 @@ if (isset($_GET['test_rmm_provider'])) { flashAlert('That provider or platform no longer exists.', 'error'); redirect('rmm_providers.php'); } - $test = rmmTest($provider); + $test = rmmWithoutSession(function () use ($provider) { + return rmmTest($provider); + }); flashAlert('' . escapeHtml(rmmProviderName($provider)) . ' - ' . escapeHtml($test['text']), $test['ok'] ? 'success' : 'error'); redirect(); @@ -111,7 +119,9 @@ if (isset($_GET['sync_rmm'])) { redirect(); } set_time_limit(180); - $sync = rmmSync($provider, 0, 150); + $sync = rmmWithoutSession(function () use ($provider) { + return rmmSync($provider, 0, 150); + }); flashAlert('' . escapeHtml(rmmProviderName($provider)) . ' ' . ($sync['ok'] ? 'synced - ' : 'didn\'t sync - ') . escapeHtml($sync['note']), $sync['ok'] ? 'success' : 'error'); redirect(); @@ -214,7 +224,10 @@ if (isset($_POST['link_rmm_client'])) { $linked = $rmm_link_client($rmm_client, $client_id); set_time_limit(180); - $sync = rmmSync(rmmProviderRow($rmm_client['rmm_client_provider_id']), intval($rmm_client['rmm_client_id']), 150); + // Its devices now - just its own; the agent's other pages don't wait on it + $sync = rmmWithoutSession(function () use ($rmm_client) { + return rmmSync(rmmProviderRow($rmm_client['rmm_client_provider_id']), intval($rmm_client['rmm_client_id']), 150); + }); $left = $linked['left'] ? '. The ' . ($linked['left'] === 1 ? 'asset' : $linked['left'] . ' assets') . ' brought in for ' . escapeHtml($linked['before_name']) . ' ' . ($linked['left'] === 1 ? 'stays there - archive it if it was' : 'stay there - archive them if they were') . ' never theirs.' : ''; flashAlert('' . escapeHtml($rmm_client['rmm_client_name']) . ' linked to ' . escapeHtml($linked['client_name']) . ' - ' . escapeHtml($sync['note']) . $left, $sync['ok'] ? 'success' : 'warning'); redirect($back); @@ -247,7 +260,9 @@ if (isset($_GET['link_rmm_suggested'])) { $rmm_link_client(rmmClientRow($rmm_client_id), $client_id); } set_time_limit(180); - $sync = rmmSync($provider, count($suggestions) === 1 ? intval(array_key_first($suggestions)) : 0, 150); + $sync = rmmWithoutSession(function () use ($provider, $suggestions) { + return rmmSync($provider, count($suggestions) === 1 ? intval(array_key_first($suggestions)) : 0, 150); + }); flashAlert(count($suggestions) . ' ' . $words['client'] . (count($suggestions) === 1 ? '' : 's') . ' linked - ' . escapeHtml($sync['note']), $sync['ok'] ? 'success' : 'warning'); redirect($back); @@ -292,7 +307,9 @@ if (isset($_GET['rmm_bring_back'])) { $brought_networks = mysqli_affected_rows($mysqli); } set_time_limit(180); - $sync = rmmSync(rmmProviderRow($rmm_client['rmm_client_provider_id']), $rmm_client_id, 150); + $sync = rmmWithoutSession(function () use ($rmm_client, $rmm_client_id) { + return rmmSync(rmmProviderRow($rmm_client['rmm_client_provider_id']), $rmm_client_id, 150); + }); $words = rmmFamilyWords(rmmFamily($rmm_client)); $brought_words = implode(' and ', array_filter([$brought || !$brought_networks ? "$brought deleted device" . ($brought === 1 ? '' : 's') : '', $brought_networks ? "$brought_networks deleted network" . ($brought_networks === 1 ? '' : 's') : ''])); logAudit($words['audit'], "Edit", "$session_name brought back $brought_words of " . escapeSql(rmmProviderName($rmm_client) . " {$words['client']} {$rmm_client['rmm_client_name']}"), intval($rmm_client['rmm_client_client_id']), intval($rmm_client['rmm_client_provider_id'])); diff --git a/agent/post/asset.php b/agent/post/asset.php index cd8c0e00c..ca1660c17 100644 --- a/agent/post/asset.php +++ b/agent/post/asset.php @@ -318,7 +318,9 @@ if (isset($_POST['rmm_link_asset'])) { // What the asset picked is missing comes in now set_time_limit(180); $provider = rmmProviderRow($device['rmm_device_provider_id']); - $sync = $provider ? rmmSync($provider, intval($device['rmm_device_rmm_client_id']), 60) : ['ok' => false, 'note' => '']; + $sync = $provider ? rmmWithoutSession(function () use ($provider, $device) { + return rmmSync($provider, intval($device['rmm_device_rmm_client_id']), 60); + }) : ['ok' => false, 'note' => '']; $message = '' . escapeHtml($device['rmm_device_hostname']) . ' in ' . escapeHtml(rmmProviderName($device)) . ' linked to ' . escapeHtml((string) getFieldById('assets', $asset_id, 'asset_name')) . ''; if (!$sync['ok'] && $sync['note'] !== '') { diff --git a/functions/rmm.php b/functions/rmm.php index a12582f00..092dd815e 100644 --- a/functions/rmm.php +++ b/functions/rmm.php @@ -54,7 +54,10 @@ * (404) and not_json (an answer that isn't the API's) * links - a device's pages in the RMM that rmmDeviceUrls() gives, key => label: * open, and control (Take Control) and background where it has them - * clients - fn(provider): ['ok', 'clients' => [[id, name, sites, devices]], 'error'] + * clients - fn(provider): ['ok', 'clients' => [[id, name, sites, devices]], 'error'] - devices + * null when it didn't count them (the count kept is left), and 'partial' => what + * it left out, when it stopped at rmmDeadline() before listing every one (none of + * the ones not listed is marked gone) * devices - fn(provider, client's id there): ['ok', 'devices' => [device], 'error'], * each device as rmmDeviceSave() takes it * dashboard - fn(provider): its web address, '' when it has none @@ -76,6 +79,49 @@ const RMM_GONE_HOLD_HOURS = 24; /** Alerts cleared this long ago are deleted at night - nothing reads one once it has cleared. */ const RMM_ALERTS_KEEP_DAYS = 180; +/** An API that answers 429 with a wait of up to this many seconds is waited for, and asked once more. */ +const RMM_RETRY_WAIT = 10; + +/** + * When a sync's listing of a provider's clients should be done by (microtime) - past it, a kind leaves + * out what can wait: device counts, and the consoles it hasn't asked yet. $at sets it; INF while no + * sync is timing one. A sync gives the listing half its time, so the linked clients' devices get the rest. + */ +function rmmDeadline(?float $at = null): float +{ + static $deadline = INF; + if ($at !== null) { + $deadline = $at; + } + return $deadline; +} + +/** Whether the listing's time is up (rmmDeadline()). */ +function rmmPastDeadline(): bool +{ + return microtime(true) > rmmDeadline(); +} + +/** + * A slow call to an RMM made from a page - linking a client, Sync now - with the session let go + * meanwhile, so the agent's other pages don't wait on it. It is taken back after, for the message. + * What $call returns. + */ +function rmmWithoutSession(callable $call) +{ + $held = session_status() === PHP_SESSION_ACTIVE; + if ($held) { + session_write_close(); + } + try { + return $call(); + } finally { + if ($held && !headers_sent()) { + session_start(); + } + } +} + /** The RMMs ITFlow can bring devices in from - kind => what it is. */ function rmmProviderKinds(?string $family = null): array { @@ -282,6 +328,24 @@ function rmmDeviceUrls(array $row): array * when it didn't work, with the kind's hints. The kind's file says where and how to sign in. */ function rmmHttp(array $provider, string $method, string $url, array $headers = [], ?array $body = null, int $timeout = 30, array $opts = []): array +{ + // Asked too often - an API that says how long to wait, up to RMM_RETRY_WAIT seconds, is asked once more after it + $answer = rmmHttpOnce($provider, $method, $url, $headers, $body, $timeout, $opts); + if ($answer['code'] === 429) { + $wait = (string) ($answer['headers']['retry-after'] ?? ''); + if (!is_numeric($wait) && is_array($answer['json']) && preg_match('/retry after ([0-9.]+)\s*s/i', (string) ($answer['json']['message'] ?? ''), $m)) { + $wait = $m[1]; + } + if (is_numeric($wait) && floatval($wait) >= 0 && floatval($wait) <= RMM_RETRY_WAIT) { + usleep(intval(ceil(floatval($wait) * 1000000)) + 100000); + $answer = rmmHttpOnce($provider, $method, $url, $headers, $body, $timeout, $opts); + } + } + return $answer; +} + +/** One request, as rmmHttp() describes - without waiting out an API that says it is asked too often. */ +function rmmHttpOnce(array $provider, string $method, string $url, array $headers = [], ?array $body = null, int $timeout = 30, array $opts = []): array { $name = rmmProviderName($provider); $hints = rmmKind($provider)['hints'] ?? []; @@ -348,6 +412,9 @@ function rmmHttp(array $provider, string $method, string $url, array $headers = if ($code === 404) { return ['ok' => false, 'code' => $code, 'json' => $json, 'error' => "Nothing at $path on $host (HTTP 404)" . $hint('not_found'), 'headers' => $answer_headers]; } + if ($code === 429) { + return ['ok' => false, 'code' => $code, 'json' => $json, 'error' => "$name was asked too often (HTTP 429) - it allows only so many requests a minute, so the rest are asked next sync" . $hint('rate'), 'headers' => $answer_headers]; + } if ($code < 200 || $code > 299) { $detail = is_array($json) ? rmmText($json['detail'] ?? $json['error'] ?? $json['message'] ?? '', 300) : ''; return ['ok' => false, 'code' => $code, 'json' => $json, 'error' => "$name answered HTTP $code" . ($detail !== '' ? " - $detail" : ''), 'headers' => $answer_headers]; @@ -391,7 +458,13 @@ function rmmRemoteDevices(array $provider, string $client_remote_id): array /** Try a provider - ['ok', 'text']: how many clients and devices it sees, or what went wrong. */ function rmmTest(array $provider): array { - $answer = rmmRemoteClients($provider); + // Not every one of a great many - the sync lists the rest + rmmDeadline(microtime(true) + 25); + try { + $answer = rmmRemoteClients($provider); + } finally { + rmmDeadline(INF); + } if (!$answer['ok']) { return ['ok' => false, 'text' => $answer['error']]; } @@ -400,6 +473,7 @@ function rmmTest(array $provider): array $words = rmmFamilyWords(rmmFamily($provider)); // A kind can say more - which API it reached $more = isset($answer['about']) && $answer['about'] !== '' ? ' ' . $answer['about'] : ''; + $more .= trim((string) ($answer['partial'] ?? '')) !== '' ? ' ' . trim((string) $answer['partial']) . '.' : ''; return ['ok' => true, 'text' => 'Connected - ' . rmmProviderName($provider) . ' has ' . number_format($clients) . ' ' . $words['client'] . ($clients === 1 ? '' : 's') . ' and ' . number_format($devices) . ' device' . ($devices === 1 ? '' : 's') . ' ' . (rmmFamily($provider) === 'network' ? 'it can see' : 'this key can see') . '.' . $more]; } @@ -966,8 +1040,11 @@ function rmmLinkedClients(int $provider_id, int $only = 0): array /** * Sync one provider - its clients, then the devices of each linked one. One at a time (a * second sync of it started while one runs says so and stops). $only is an rmm_clients id, - * for bringing in one client's devices straight after it is linked. Stops after $max_seconds - * and picks up where it left off next time - the clients brought in longest ago go first. + * for bringing in one client's devices straight after it is linked - without listing its + * clients again. Stops after $max_seconds and picks up where it left off next time - the + * clients brought in longest ago go first, and at least one each sync, however long the + * listing took. The listing has half the time (rmmDeadline()); a kind with many clients + * lists the rest next time. * * Returns ['ok', 'note', 'counts'] - note is what to show a person. */ @@ -1001,6 +1078,7 @@ function rmmSync(array $provider, int $only = 0, int $max_seconds = 120): array $held = []; // the clients whose devices went at once, kept as they were: "client: n of m" $complete = []; // rmm_clients id => its name, for each client the RMM no longer has - all its devices are gone $stopped = false; + $partial = ''; // what the listing left for next time $in_list = function (array $ids) { return $ids ? "'" . implode("', '", array_map('escapeSql', $ids)) . "'" : "''"; @@ -1053,22 +1131,34 @@ function rmmSync(array $provider, int $only = 0, int $max_seconds = 120): array }; try { - $answer = rmmRemoteClients($provider); - if (!$answer['ok']) { - throw new RuntimeException($answer['error']); + // Its clients - not for one just linked, whose devices are all that is wanted. Half the time at most + $answer = ['ok' => true, 'clients' => []]; + if (!$only) { + rmmDeadline($clock + max(10, $max_seconds / 2)); + try { + $answer = rmmRemoteClients($provider); + } finally { + rmmDeadline(INF); + } + if (!$answer['ok']) { + throw new RuntimeException($answer['error']); + } + $partial = trim((string) ($answer['partial'] ?? '')); } - // Its clients - new ones added, names and counts kept up, the ones it no longer has marked + // New ones added, names and counts kept up - a count it didn't take this time stays as it was - and the ones it no longer has marked foreach ($answer['clients'] as $client) { $remote = escapeSql($client['id']); $client_name = escapeSql($client['name']); + $counted = ($client['devices'] ?? null) !== null; mysqli_query($mysqli, "INSERT INTO rmm_clients SET rmm_client_provider_id = $provider_id, rmm_client_remote_id = '$remote', rmm_client_name = '$client_name', - rmm_client_sites = " . intval($client['sites']) . ", rmm_client_devices = " . intval($client['devices']) . ", rmm_client_seen_at = NOW() + rmm_client_sites = " . intval($client['sites']) . ", rmm_client_devices = " . intval($client['devices'] ?? 0) . ", rmm_client_seen_at = NOW() ON DUPLICATE KEY UPDATE rmm_client_name = VALUES(rmm_client_name), rmm_client_sites = VALUES(rmm_client_sites), - rmm_client_devices = VALUES(rmm_client_devices), rmm_client_seen_at = NOW(), rmm_client_removed_at = NULL"); + " . ($counted ? 'rmm_client_devices = VALUES(rmm_client_devices), ' : '') . "rmm_client_seen_at = NOW(), rmm_client_removed_at = NULL"); } $counts['clients'] = count($answer['clients']); - if (!$only) { + // Only a whole list says which it no longer has + if (!$only && $partial === '') { $listed = $in_list(array_column($answer['clients'], 'id')); // And the ones marked before whose devices were kept, until they are marked too $gone = mysqli_query($mysqli, "SELECT rmm_client_id, rmm_client_name, rmm_client_removed_at FROM rmm_clients WHERE rmm_client_provider_id = $provider_id @@ -1090,14 +1180,17 @@ function rmmSync(array $provider, int $only = 0, int $max_seconds = 120): array rmmForgetClientDevices(intval($unlinked_row[0]), $name, 'its client there was unlinked'); } + $synced = 0; foreach (rmmLinkedClients($provider_id, $only) as $rmm_client) { - if (microtime(true) - $clock > $max_seconds) { + // At least one each sync, the one brought in longest ago - however long the listing took + if ($synced && microtime(true) - $clock > $max_seconds) { $stopped = true; break; } if ($rmm_client['client_archived_at'] !== null) { continue; } + $synced++; $devices = rmmRemoteDevices($provider, (string) $rmm_client['rmm_client_remote_id']); if (!$devices['ok']) { $errors[] = $rmm_client['rmm_client_name'] . ': ' . $devices['error']; @@ -1112,6 +1205,8 @@ function rmmSync(array $provider, int $only = 0, int $max_seconds = 120): array } } $kept = $remove_unlisted(intval($rmm_client['rmm_client_id']), $listed); + // Its count is what it has - a kind that lists many clients may not count each + mysqli_query($mysqli, "UPDATE rmm_clients SET rmm_client_devices = " . count($listed) . " WHERE rmm_client_id = " . intval($rmm_client['rmm_client_id'])); foreach ($devices['devices'] as $device) { if (!is_array($device)) { continue; @@ -1164,6 +1259,9 @@ function rmmSync(array $provider, int $only = 0, int $max_seconds = 120): array if ($stopped) { $note .= '. Stopped for time - the rest come in next sync'; } + if ($partial !== '') { + $note .= ". $partial"; + } if ($held) { $note .= ". Not marked gone yet - $short stopped listing most of a client's devices at once, which is more often $short or its API key's access than the devices (" . implode('; ', $held) . '). If they are still missing after ' . RMM_GONE_HOLD_HOURS . ' hours, they are marked gone'; diff --git a/functions/rmm_unifi.php b/functions/rmm_unifi.php index 9e49243db..d04ebadfc 100644 --- a/functions/rmm_unifi.php +++ b/functions/rmm_unifi.php @@ -29,6 +29,13 @@ // Where the Site Manager API is defined('UNIFI_SITE_MANAGER_URL') || define('UNIFI_SITE_MANAGER_URL', 'https://api.ui.com'); +/** + * A console asked directly (unifi_os) has its sites' device counts asked of it, a request each, only + * when it has at most this many - a console with hundreds of sites would spend its requests a minute + * on counts. Its linked sites are counted as their devices come in. + */ +const UNIFI_COUNT_SITES_MAX = 50; + /** The UniFi kinds - one for each way in. */ function rmmUnifiKinds(): array { @@ -138,6 +145,7 @@ function rmmUnifiKind(string $key): array 'auth' => 'check the key, made at unifi.ui.com under API - and, for a console someone else owns, that it is an organization key.', 'not_found' => 'that console may need firmware 5.0.3 or later, or have no Network application.', 'not_json' => '', + 'rate' => 'Site Manager lets each console be asked 100 times a minute.', ], ]); } @@ -425,23 +433,50 @@ function rmmUnifiSites(array $provider): array if (!is_array($site) || !preg_match('/^[A-Za-z0-9-]{1,100}$/', (string) ($site['id'] ?? ''))) { continue; } - $count = rmmUnifiNetwork($provider, 'sites/' . $site['id'] . '/devices', ['limit' => 1]); + // Its device count is a request of its own - asked for a console with few sites, while the sync's listing has time; else the count kept stays + $count = count($answer['data']) > UNIFI_COUNT_SITES_MAX || rmmPastDeadline() ? ['ok' => false] : rmmUnifiNetwork($provider, 'sites/' . $site['id'] . '/devices', ['limit' => 1]); $label = rmmText($site['name'] ?? '', 200); - $sites[] = ['id' => (string) $site['id'], 'name' => $label !== '' ? $label : (string) ($site['internalReference'] ?? $site['id']), 'sites' => 1, 'devices' => $count['ok'] ? $count['total'] : 0]; + $sites[] = ['id' => (string) $site['id'], 'name' => $label !== '' ? $label : (string) ($site['internalReference'] ?? $site['id']), 'sites' => 1, 'devices' => $count['ok'] ? $count['total'] : null]; } $sites = rmmUnifiLoneDefault($provider, $sites); $api = rmmUnifiNetworkApi($provider); return ['ok' => true, 'clients' => $sites, 'error' => '', 'about' => 'Its Network API' . ($api['version'] !== '' ? ' is version ' . $api['version'] : ' answered') . '.']; } - // Through Site Manager - each console's sites, named with the console when it has more than one + /* + * Through Site Manager - each console's sites, named with the console when it has more than one. Site + * Manager's own list of sites (rmmUnifiSiteManagerSites()) has every site's device count, in a request or + * two, so no site is asked for its count. A console is asked for its sites through its connector - which + * allows 100 requests a minute a console - only when that list says it has sites ITFlow doesn't know: a + * console with just its Default site, which ITFlow has already, isn't asked at all. Past the sync's + * listing time (rmmDeadline()), the consoles not asked yet are asked next sync, and their sites stay. + */ $consoles = rmmUnifiConsoles($provider); if (!$consoles['ok']) { return ['ok' => false, 'clients' => [], 'error' => $consoles['error']]; } + $listing = rmmUnifiSiteManagerSites($provider); + $known = rmmUnifiKnownSites($provider); $map = []; $unreached = []; + $left = 0; foreach ($consoles['consoles'] as $console => $console_name) { + $key = substr(md5((string) $console), 0, 16); + $listed = $listing['ok'] ? ($listing['sites'][$console] ?? []) : null; + $have = $known[$key] ?? []; + + // Just its Default site, which ITFlow has - nothing to ask the console + if ($listed !== null && count($listed) === 1 && isset($listed['default']) && count($have) === 1) { + $id = (string) array_key_first($have); + $map[$id] = [(string) $console, (string) substr($id, 17)]; + $label = rmmText($listed['default']['desc'], 100); + $sites[] = ['id' => $id, 'name' => $label === '' || strtolower($label) === 'default' ? $console_name : $label, 'sites' => 1, 'devices' => $listed['default']['devices']]; + continue; + } + if (rmmPastDeadline()) { + $left++; + continue; + } $answer = rmmUnifiNetwork($provider, 'sites', [], $console); if (!$answer['ok']) { $unreached[] = $console_name; @@ -452,17 +487,21 @@ function rmmUnifiSites(array $provider): array if (!is_array($site) || !preg_match('/^[A-Za-z0-9-]{1,60}$/', (string) ($site['id'] ?? ''))) { continue; } - $id = substr(md5($console), 0, 16) . '.' . $site['id']; + $id = "$key." . $site['id']; $map[$id] = [$console, (string) $site['id']]; - $count = rmmUnifiNetwork($provider, 'sites/' . $site['id'] . '/devices', ['limit' => 1], $console); // A console's one Default site is the console; the rest go by their names, with the console's when it has more $label = rmmText($site['name'] ?? '', 100); $plain = $label === '' || strtolower($label) === 'default'; + $reference = (string) ($site['internalReference'] ?? ''); $sites[] = ['id' => $id, 'name' => $plain ? $console_name . ($many ? ' (Default)' : '') : ($many ? "$label ($console_name)" : $label), - 'sites' => 1, 'devices' => $count['ok'] ? $count['total'] : 0]; + 'sites' => 1, 'devices' => $listed[$reference]['devices'] ?? null]; } } rmmUnifiCloudSites($map); + $partial = $left ? "Listed the sites of " . number_format(count($consoles['consoles']) - $left) . ' of ' . number_format(count($consoles['consoles'])) . ' consoles - the other ' . number_format($left) . ' next sync' : ''; + if ($left && !$sites && !$unreached) { + return ['ok' => true, 'clients' => [], 'error' => '', 'partial' => $partial, 'about' => '']; + } if ($unreached && !$sites) { return ['ok' => false, 'clients' => [], 'error' => 'Site Manager answered, but none of its consoles did through its connector (' . implode(', ', array_slice($unreached, 0, 5)) . ') - consoles need firmware 5.0.3 or later and the Network application']; } @@ -473,7 +512,55 @@ function rmmUnifiSites(array $provider): array if ($consoles['skipped']) { $about .= '; ' . $consoles['skipped'] . ' self-hosted controller' . ($consoles['skipped'] === 1 ? '' : 's') . ' left out - add ' . ($consoles['skipped'] === 1 ? 'it' : 'them') . ' as a UniFi controller (sign-in)'; } - return ['ok' => true, 'clients' => $sites, 'error' => '', 'about' => "It reaches $about."]; + return ['ok' => true, 'clients' => $sites, 'error' => '', 'about' => "It reaches $about.", 'partial' => $partial]; +} + +/** + * Every site Site Manager lists, with its device count - ['ok', 'sites' => [console id => [short name => + * ['desc', 'devices']]], 'error']. A site's short name there is its internalReference in the Network API - + * "default" for a console's first. Not ok when Site Manager doesn't list them: each console is asked. + */ +function rmmUnifiSiteManagerSites(array $provider): array +{ + $key = rmmSecret($provider, 'api_key'); + $sites = []; + $next = ''; + for ($page = 0; $page < 50; $page++) { + $query = ['pageSize' => 500] + ($next !== '' ? ['nextToken' => $next] : []); + $answer = rmmHttp($provider, 'GET', rtrim(UNIFI_SITE_MANAGER_URL, '/') . '/v1/sites?' . http_build_query($query, '', '&'), ['X-API-KEY: ' . $key]); + if (!$answer['ok'] || !rmmIsList($answer['json']['data'] ?? null)) { + return ['ok' => false, 'sites' => [], 'error' => $answer['ok'] ? 'Site Manager answered, but not with a list of sites' : $answer['error']]; + } + foreach ($answer['json']['data'] as $site) { + $host = is_array($site) ? (string) ($site['hostId'] ?? '') : ''; + $name = is_array($site['meta'] ?? null) ? (string) ($site['meta']['name'] ?? '') : ''; + if ($host === '' || $name === '') { + continue; + } + $total = $site['statistics']['counts']['totalDevice'] ?? null; + $sites[$host][$name] = ['desc' => (string) ($site['meta']['desc'] ?? ''), 'devices' => is_numeric($total) ? intval($total) : null]; + } + $next = (string) ($answer['json']['nextToken'] ?? ''); + if ($next === '') { + break; + } + } + return ['ok' => true, 'sites' => $sites, 'error' => '']; +} + +/** The sites ITFlow has of a Site Manager platform, still listed - [the console's part of their ids => [id => name]]. */ +function rmmUnifiKnownSites(array $provider): array +{ + global $mysqli; + $known = []; + $sql = mysqli_query($mysqli, "SELECT rmm_client_remote_id, rmm_client_name FROM rmm_clients + WHERE rmm_client_provider_id = " . intval($provider['rmm_provider_id'] ?? 0) . " AND rmm_client_removed_at IS NULL"); + while ($sql && ($row = mysqli_fetch_row($sql))) { + if (preg_match('/^([a-f0-9]{16})\.[A-Za-z0-9-]{1,60}$/', (string) $row[0], $m)) { + $known[$m[1]][(string) $row[0]] = (string) $row[1]; + } + } + return $known; } /** One site's devices - ['ok', 'devices', 'error'], each as rmmDeviceSave() takes it. */