UniFi and RMM sync (forum #3236): Site Manager device counts come from its list of sites instead of a request per site, a console is asked for its sites only when it has new ones, listing gets half a sync's time and finishes over later syncs, at least one linked site syncs each run, linking brings in only that site's devices, linking, Sync Now, Test and saving release the session so other pages don't wait, a 429 with a short wait is retried once and a longer one is reported plainly, and a console asked directly with more than 50 sites isn't asked for each site's count; 26.12.3 changelog

This commit is contained in:
johnnyq
2026-12-01 13:57:25 -05:00
parent abcd1a6fcf
commit 0b770dcdf0
5 changed files with 235 additions and 27 deletions

View File

@@ -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';