]> ###2026.11.22 - "returning …" badge only while a return to the preferred node really runs: it no longer sticks to services that run stable, that have already arrived or that have no preferred node anymore - Return to the preferred node: if the service does not start there, the return is cancelled after 5 minutes and Swarm runs it elsewhere again; the next attempt follows after 30 minutes, then 1 h, 2 h … (before: a new attempt – and a restart – every 10 minutes) - Switching "automatic return" off ends pending returns at once and removes their temporary node binding; Stack Up forgets returns of that stack; returns of deleted services are forgotten - New settings tab "Log": what Swarm View does in the background – watchdog decisions (failover, return, crash loops, nodes offline/online, notifications), your actions on the Docker page with their output, changed settings and errors. Filter by level, source and text, live view, details per entry, download, clear. Recording level: errors / warnings / info (default) / debug (every watchdog run and why a service does or does not return) ###2026.11.21d - Folder View: when the Swarm data arrived while Folder View was still building its folders, a folder could stay empty – Swarm View now waits until Folder View is done before it reloads the list ###2026.11.21c - Folder View 3: the host column no longer shrinks to a sliver after switching Basic → Advanced view - Folder View 2: Swarm containers running on Unraid are now sorted into folders as well - Orphan images: an image was hidden by mistake when the agent container was the last container in the list (and reappeared in the basic view); "<none>:<none>" counts as an image without name; without Swarm data nothing is hidden - Swarm section scrolls horizontally on narrow screens instead of being cut off - Host column keeps a minimum width ###2026.11.21b - Support link to the Unraid forum thread - GitHub account renamed to Hugo2625: new plugin URL https://raw.githubusercontent.com/Hugo2625/unraid-swarm-view/main/swarm-view.plg ###2026.11.21a - English interface; German stays available. The language follows Unraid's display language or can be chosen in the settings (General → Display → Language) - Notifications, messages and the settings page are translated as well - Settings: popup after "Apply" only for noteworthy changes (agent started/stopped, watchdog switched on, swarm values changed) ###2026.11.21 - First public release - Swarm Stacks section on the Docker page: create, edit and deploy stacks (Stack Up / Update Stack / Stack Down), per-service actions (update, rollback, restart, logs, move) - Host column and rows for containers running on other nodes, with CPU/RAM, network, uptime and context menu; Folder View support (folder totals across nodes, regex on display names) - Node placement per service at runtime: automatic, preferred (with failover and automatic return) or fixed - Notifications (node offline, crash loops, pending tasks, node changes, image updates), update hints with rollback, cleanup of stopped task containers and old images - Settings with tabs: general, nodes (with warnings), watchdog, maintenance, status rm -rf &plugdir; ">
Stack Status Image
]]>
''; $sv_swarm_ok = $sv_sw['active'] && $sv_sw['manager']; $sv_yn = fn($k) => $sv_opt($sv_cfg[$k], 'yes', sv_t('Yes')) . $sv_opt($sv_cfg[$k], 'no', sv_t('No')); $sv_on = fn($k) => $sv_opt($sv_cfg[$k], 'no', sv_t('Off')) . $sv_opt($sv_cfg[$k], 'yes', sv_t('On')); $sv_lvl = fn($k) => ''; $sv_num = fn($k, $min, $max) => ''; $sv_date = fn($ts, $short = false) => date(sv_lang() === 'de' ? ($short ? 'd.m. H:i' : 'd.m.Y H:i') : ($short ? 'M j, H:i' : 'Y-m-d H:i'), (int)$ts); $sv_upd = sv_state_read('updates'); $sv_upd_when = !empty($sv_upd['checked']) ? $sv_date($sv_upd['checked']) : sv_t('never'); $sv_upd_count = count(array_filter($sv_upd['services'] ?? [], fn($x) => !empty($x['update']))); $sv_upd_html = htmlspecialchars($sv_upd_when) . ($sv_upd_count ? ' – ' . htmlspecialchars(sv_tn($sv_upd_count, '{0} update available', '{0} updates available')) . '' : ''); // ---------- data for the tabs Nodes, Watchdog, Status ---------- $sv_ago = function ($ts) use ($sv_date) { if (!$ts) return sv_t('never'); $d = max(0, time() - (int)$ts); if ($d < 60) return sv_t('{0} s ago', $d); if ($d < 3600) return sv_t('{0} min ago', intdiv($d, 60)); if ($d < 86400) return sv_t('{0} h ago', intdiv($d, 3600)); return $sv_date($ts); }; $sv_ninfo = []; // hostname → details from node inspect $sv_prefer = []; // services with a preferred node: name → node if ($sv_swarm_ok && $sv_nodes) { [$rc, $out] = sv_run(array_merge([$GLOBALS['DOCKER'], 'node', 'inspect'], array_map(fn($n) => $n['ID'], $sv_nodes))); foreach ($rc === 0 ? (json_decode($out, true) ?: []) : [] as $ni) { $sv_ninfo[$ni['Description']['Hostname'] ?? ''] = [ 'addr' => $ni['Status']['Addr'] ?? '', 'arch' => $ni['Description']['Platform']['Architecture'] ?? '', 'os' => $ni['Description']['Platform']['OS'] ?? '', 'engine' => $ni['Description']['Engine']['EngineVersion'] ?? '', 'cpus' => round(($ni['Description']['Resources']['NanoCPUs'] ?? 0) / 1e9), 'memGB' => round(($ni['Description']['Resources']['MemoryBytes'] ?? 0) / 1073741824, 1), 'labels' => $ni['Spec']['Labels'] ?? [], ]; } [$rc, $out] = sv_run([$GLOBALS['DOCKER'], 'service', 'ls', '--filter', 'label=swarm-view.prefer', '--format', '{{.Name}}']); $pnames = $rc === 0 ? array_filter(explode("\n", trim($out))) : []; if ($pnames) { [$rc, $out] = sv_run(array_merge([$GLOBALS['DOCKER'], 'service', 'inspect', '--format', '{{.Spec.Name}}={{index .Spec.Labels "swarm-view.prefer"}}'], $pnames)); foreach (explode("\n", $rc === 0 ? trim($out) : '') as $l) if (strpos($l, '=') !== false) { [$k, $v] = explode('=', $l, 2); $sv_prefer[$k] = $v; } } } $sv_agent = ($sv_cfg['STATS'] === 'yes' && $sv_swarm_ok) ? sv_agent_read((int)$sv_cfg['STATS_INTERVAL']) : []; $sv_mon = sv_state_read('monitor'); $sv_self_engine = ''; foreach ($sv_nodes as $n) if (!empty($n['Self'])) $sv_self_engine = $sv_ninfo[$n['Hostname'] ?? '']['engine'] ?? ''; /** Warnings for a node: [level, HTML text] */ $sv_warn = function (array $n) use ($sv_ninfo, $sv_agent, $sv_cfg, $sv_self_engine, $sv_ago) { $h = $n['Hostname'] ?? ''; $i = $sv_ninfo[$h] ?? []; $w = []; if (strtolower($n['Status'] ?? '') !== 'ready') $w[] = ['bad', sv_e('Node is unreachable – Swarm moves its containers to other nodes.')]; if (strtolower($n['Availability'] ?? 'active') !== 'active') $w[] = ['warn', strtolower($n['Availability']) === 'drain' ? sv_e('Node is in maintenance – Swarm starts no new containers there.') : sv_e('Node is paused – Swarm starts no new containers there.')]; if ($sv_self_engine && ($i['engine'] ?? '') && $i['engine'] !== $sv_self_engine) $w[] = ['warn', sv_e('Different Docker version than the manager ({0} instead of {1}). Mixed versions usually work but are a common source of errors.', $i['engine'], $sv_self_engine)]; if ($sv_cfg['STATS'] === 'yes') { $a = $sv_agent[$h] ?? null; if (!$a) $w[] = ['warn', sv_e('The CPU/RAM agent has not reported yet.')]; else { if (!empty($a['stale'])) $w[] = ['warn', sv_e('The CPU/RAM agent reports no current values (last: {0}).', $sv_ago($a['ts'] ?? 0))]; $noMem = !empty($a['rss']); foreach ($a['stats'] ?? [] as $c) if (preg_match('#^0B\s*/\s*0B$#', trim($c['MemUsage'] ?? ''))) $noMem = true; if ($noMem) $w[] = ['warn', str_replace(['%1', '%2'], ['cgroup_enable=memory cgroup_memory=1', '/boot/firmware/cmdline.txt'], sv_e('Docker measures no container memory here (memory cgroup off), so the containers\' RAM values are estimated. Fix on Raspberry Pi OS: append {0} to the line in {1}, then reboot.', '%1', '%2'))]; if (($a['ts'] ?? 0) > time() + 5) $w[] = ['warn', sv_e('The clock of this node is ahead ({0} s). Times and Swarm certificates can suffer – check NTP.', (int)$a['ts'] - time())]; } } return $w; }; $sv_nw = array_sum(array_map(fn($n) => count($sv_warn($n)), $sv_nodes)); ?>

Stacks
/<name>/
Nodes

' . sv_e('(this server)') . '' : ''?>

IP

Docker
CPU / RAM
Agent
' . sv_e('off') . '' : ($a ? htmlspecialchars($sv_ago($a['ts'] ?? 0)) : '' . sv_e('no data') . '')?>
Labels
"$k=$v", array_keys($i['labels']), $i['labels']))) : '–'?>

style="margin-left:10px">
"$k → $v", array_keys($sv_prefer), $sv_prefer)))?>"> preg_replace('/^[^_]+_/', '', $k) . " → $v", array_keys($sv_prefer), $sv_prefer)))?>
    deploy:
      labels:
        swarm-view.prefer: raspberrypi
>
180); ?>
– · –
$a):?>:
"$k → {$v['node']}", array_keys($sv_mon['rebalance']), $sv_mon['rebalance'])))?>
()
$hst['t'], 'cls' => ['normal' => 'sv-ok', 'warning' => 'sv-warn', 'alert' => 'sv-bad'][$hst['level']] ?? '', 'icon' => 'fa-bell', 'text' => $hst['subject'] . ' – ' . $hst['desc']]; foreach ($sv_mon['events'] ?? [] as $ev) $sv_feed[] = ['t' => $ev['t'], 'cls' => 'sv-dim', 'icon' => 'fa-cog', 'text' => $ev['text']]; usort($sv_feed, fn($x, $y) => $y['t'] <=> $x['t']); $sv_feed = array_slice($sv_feed, 0, 10); ?>

Log

]]>
a { font-size: 0 !important; } #docker_list .appname[data-sv-alias]::before { content: attr(data-sv-alias); font-size: var(--sv-fs, 13px); } /* ---------- Einstellungen: Tabs, Nodes, Status ---------- */ #sv-settings .sv-tabbar { display: flex; flex-wrap: wrap; gap: 4px; border-bottom: 1px solid rgba(128,128,128,.4); margin: 4px 0 14px; } #sv-settings .sv-tabbtn { padding: 8px 16px; border: 1px solid transparent; border-bottom: none; border-radius: 4px 4px 0 0; text-decoration: none; color: inherit; opacity: .7; margin-bottom: -1px; } #sv-settings .sv-tabbtn:hover { opacity: 1; } #sv-settings .sv-tabbtn.active { opacity: 1; font-weight: bold; border-color: rgba(128,128,128,.4); border-bottom: 2px solid #ff8c2f; } #sv-settings .sv-tabbtn .fa { margin-right: 4px; } #sv-settings .sv-tabbadge { display: inline-block; min-width: 16px; padding: 0 5px; margin-left: 4px; border-radius: 8px; background: #ff9800; color: #000; font-size: .8em; text-align: center; font-weight: bold; } #sv-settings dd { white-space: nowrap; } #sv-settings dd select + .sv-dim, #sv-settings dd select + .sv-warn { white-space: normal; } #sv-settings input.narrow { width: 70px; } #sv-settings .sv-set-buttons { margin: 18px 0 6px; padding-top: 12px; border-top: 1px solid rgba(128,128,128,.3); } #sv-settings .sv-set-buttons input { margin: 0 8px 0 0; } #sv-settings .sv-node-card { border: 1px solid rgba(128,128,128,.35); border-radius: 6px; padding: 10px 14px; margin: 0 0 12px; } #sv-settings .sv-node-head { font-size: 1.1em; } #sv-settings .sv-node-head .fa { margin-right: 6px; opacity: .8; } #sv-settings .sv-node-head select.sv-avail { float: right; margin: -3px 0 0; font-size: .9em; } #sv-settings table.sv-node-facts { width: auto; margin: 8px 0 2px; border-collapse: collapse; } #sv-settings table.sv-node-facts td { padding: 2px 22px 2px 0; vertical-align: top; white-space: nowrap; } #sv-settings .sv-node-warn { margin-top: 6px; padding: 5px 10px; border-radius: 4px; font-size: .95em; } #sv-settings .sv-node-warn-warn { background: rgba(255,152,0,.12); border-left: 3px solid #ff9800; } #sv-settings .sv-node-warn-bad { background: rgba(244,67,54,.12); border-left: 3px solid #f44336; } #sv-settings .sv-node-warn .fa { margin-right: 6px; } #sv-settings table.sv-feed { width: auto; border-collapse: collapse; } #sv-settings table.sv-feed td { padding: 3px 12px 3px 0; vertical-align: top; } /* hide orphan images (Unraid sets display inline when the view changes – hence !important) */ #docker_list tr.sv-orphan-hidden { display: none !important; } #docker_list tr.sv-internal-row { display: none !important; } /* agent/cleanup helper containers */ #docker_list .appname a.sv-local-name { color: inherit; cursor: inherit; text-decoration: none; } #sv-root .sv-tablewrap { overflow-x: auto; } /* narrow screens: scroll the table instead of cutting it off */ #docker_list tr.sv-orphan-sum td { padding: 6px 10px; } #docker_list tr.sv-orphan-sum a { color: inherit; text-decoration: none; } #docker_list tr.sv-orphan-sum a:hover { text-decoration: underline; } /* settings → Log */ #sv-settings .sv-log-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 12px 0 10px; } #sv-settings .sv-log-tools select, #sv-settings .sv-log-tools input { margin: 0; } #sv-settings .sv-log-tools select { width: auto; min-width: 150px; padding-right: 24px; } #sv-settings .sv-log-tools input.sv-log-q { width: 220px; } #sv-settings .sv-log-autolabel { white-space: nowrap; cursor: pointer; } #sv-settings .sv-log-wrap { max-height: 62vh; overflow: auto; border: 1px solid rgba(128,128,128,.3); border-radius: 4px; } #sv-settings table.sv-logtable { width: 100%; margin: 0; border-collapse: collapse; font-size: .92em; } #sv-settings table.sv-logtable td { height: auto; padding: 5px 8px; line-height: 1.45; white-space: normal; border-bottom: 1px solid rgba(128,128,128,.14); vertical-align: top; text-align: left; } #sv-settings table.sv-logtable td.sv-log-t, #sv-settings table.sv-logtable td.sv-log-s { white-space: nowrap; opacity: .7; font-variant-numeric: tabular-nums; } #sv-settings .sv-log-lvl { display: inline-block; min-width: 58px; padding: 0 6px; border: 1px solid currentColor; border-radius: 3px; font-size: .8em; line-height: 1.55; text-align: center; } #sv-settings .sv-log-debug .sv-log-lvl { color: #9e9e9e; } #sv-settings .sv-log-info .sv-log-lvl { color: #42a5f5; } #sv-settings .sv-log-warn .sv-log-lvl { color: #ff9800; } #sv-settings .sv-log-error .sv-log-lvl { color: #f44336; } #sv-settings tr.sv-log-warn td { background: rgba(255,152,0,.06); } #sv-settings tr.sv-log-error td { background: rgba(244,67,54,.08); } #sv-settings tr.sv-log-debug td.sv-log-m { opacity: .75; } #sv-settings tr.sv-log-has td.sv-log-m { cursor: pointer; } #sv-settings tr.sv-log-has .fa-caret-right { width: 8px; opacity: .7; transition: transform .15s; } #sv-settings tr.sv-log-has.open .fa-caret-right { transform: rotate(90deg); } #sv-settings .sv-log-d { display: none; margin: 4px 0 2px; max-height: 320px; overflow: auto; white-space: pre-wrap; word-break: break-word; font-size: .9em; opacity: .85; cursor: text; } #sv-settings tr.open .sv-log-d { display: block; } #sv-settings .sv-log-empty { margin: 0; padding: 12px; } ]]> /{docker-stack.yml,.env} */ require_once __DIR__ . '/common.php'; header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: no-store'); /** What the current action does – logged with its result when reply() is called (settings → Log) */ $SV_ACT = ''; function act(string $what): void { $GLOBALS['SV_ACT'] = $what; } function reply(bool $ok, array $extra = []): void { if ($GLOBALS['SV_ACT'] !== '') { $detail = trim(($ok ? '' : ($extra['error'] ?? '') . "\n") . ($extra['log'] ?? '')); sv_log($ok ? 'info' : 'error', 'action', $GLOBALS['SV_ACT'] . ($ok ? '' : ' – ' . sv_t('failed')), $detail); } echo json_encode(['ok' => $ok] + $extra, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') reply(false, ['error' => sv_t('Only POST allowed')]); $action = $_POST['action'] ?? ''; /* ---------- Service/task actions (independent of the stack folder) ---------- */ if ($action === 'logs') { $task = $_POST['task'] ?? ''; if (!preg_match('/^[a-z0-9]{10,64}$/', $task)) reply(false, ['error' => sv_t('Invalid task ID')]); $tail = max(50, min(2000, (int)($_POST['tail'] ?? 300))); [$rc, $out] = sv_run([$DOCKER, 'service', 'logs', '--no-task-ids', '--timestamps', '--tail', (string)$tail, $task], null, [], 30); reply($rc === 0, ['log' => $out !== '' ? $out : sv_t('(no output)')]); } if ($action === 'svc-restart') { $svc = $_POST['service'] ?? ''; if (!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/', $svc)) reply(false, ['error' => sv_t('Invalid service name')]); act(sv_t('Restart service {0}', $svc)); [$rc, $out] = sv_run([$DOCKER, 'service', 'update', '--force', '--detach', $svc]); reply($rc === 0, ['log' => $rc === 0 ? sv_t('{0} is being rolled out again.', $svc) : $out]); } if ($action === 'place') { // Runtime only: the next "Stack Up" sets constraints and labels from docker-stack.yml again // mode='' → automatic: no node binding, no preference // mode=fixed → fixed: node.hostname==N (runs only there, not at all if it is down) // mode=prefer → preferred: label swarm-view.prefer=N; runs elsewhere while N is down, the watchdog brings it back $svc = $_POST['service'] ?? ''; $node = $_POST['node'] ?? ''; $mode = $_POST['mode'] ?? ($node === '' ? '' : 'fixed'); if (!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/', $svc)) reply(false, ['error' => sv_t('Invalid service name')]); if (!in_array($mode, ['', 'fixed', 'prefer'], true)) reply(false, ['error' => sv_t('Invalid mode')]); if ($mode === '') $node = ''; elseif (!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/', $node)) reply(false, ['error' => sv_t('Invalid node name')]); act(sv_t('Placement of {0}: {1}', $svc, $mode === 'fixed' ? sv_t('only {0}', $node) : ($mode === 'prefer' ? sv_t('prefer {0}', $node) : sv_t('automatic')))); [$rc, $out] = sv_run([$DOCKER, 'service', 'inspect', $svc, '--format', '{{json .}}']); $svcObj = $rc === 0 ? json_decode($out, true) : null; $spec = $svcObj['Spec'] ?? null; if (!is_array($spec)) reply(false, ['error' => sv_t('Service "{0}" not found', $svc), 'log' => $out]); if (isset($spec['Mode']['Global'])) reply(false, ['error' => sv_t('Global services run on all nodes')]); // change the watchdog state only while holding its lock @mkdir($STATE_DIR, 0755, true); $lock = fopen("$STATE_DIR/monitor.lock", 'c'); if ($lock) flock($lock, LOCK_EX); $state = sv_state_read('monitor'); unset($state['rebalance'][$svc]); $cons = $spec['TaskTemplate']['Placement']['Constraints'] ?? []; $hadPrefer = trim($spec['Labels']['swarm-view.prefer'] ?? '') !== ''; $args = [$DOCKER, 'service', 'update', '--detach']; foreach ($cons as $c) { if (sv_is_node_constraint($c)) array_push($args, '--constraint-rm', $c); } $log = []; if ($mode === 'fixed') { array_push($args, '--constraint-add', "node.hostname==$node"); if ($hadPrefer) array_push($args, '--label-rm', 'swarm-view.prefer'); $log[] = sv_t('{0} now runs only on {1}.', $svc, $node); } elseif ($mode === 'prefer') { array_push($args, '--label-add', "swarm-view.prefer=$node"); // already on N? then do not move. Otherwise move now (like the watchdog's return: constraint, removed again afterwards) [, $tout] = sv_run([$DOCKER, 'service', 'ps', $svc, '--filter', 'desired-state=running', '--format', '{{.Node}}|{{.CurrentState}}']); $rows = array_filter(explode("\n", trim($tout))); $onN = $rows && !array_filter($rows, fn($r) => !str_starts_with($r, "$node|Running")); [, $nout] = sv_run([$DOCKER, 'node', 'inspect', $node, '--format', '{{.Status.State}}|{{.Spec.Availability}}']); $ready = trim($nout) === 'ready|active'; if (!$onN && $ready) { array_push($args, '--constraint-add', "node.hostname==$node"); $state['rebalance'][$svc] = ['since' => sv_now(), 'node' => $node]; $log[] = sv_t('{0} is moved to {1}; if the node goes down it may run elsewhere.', $svc, $node); } elseif (!$ready) { $log[] = sv_t('{0} is not available right now – {1} stays where it is and moves back as soon as {0} runs stable again.', $node, $svc); } else { $log[] = sv_t('{0} already runs on {1}; if the node goes down it may run elsewhere.', $svc, $node); } // no return without the watchdog → switch it on automatically $cfg = sv_cfg(); if ($cfg['REBALANCE'] !== 'yes') { $cfg['REBALANCE'] = 'yes'; sv_cfg_write($cfg); sv_cron_apply($cfg); $log[] = sv_t('Automatic return switched on in the settings.'); } } else { if ($hadPrefer) array_push($args, '--label-rm', 'swarm-view.prefer'); $log[] = sv_t('{0}: Swarm decides again.', $svc); } if (count($args) === 4) { sv_state_write('monitor', $state); reply(true, ['log' => sv_t('No change needed.')]); } $args[] = $svc; [$rc, $out] = sv_run($args, null, [], 60); if ($rc !== 0) unset($state['rebalance'][$svc]); sv_state_write('monitor', $state); if ($lock) { flock($lock, LOCK_UN); fclose($lock); } reply($rc === 0, $rc === 0 ? ['log' => implode("\n", $log)] : ['error' => sv_t('{0} failed', 'service update'), 'log' => $out]); } if ($action === 'cleanup') { act(sv_t('Cleanup')); $cfg = sv_cfg(); [$ok, $log] = sv_cleanup($cfg['CLEANUP_IMAGES'] === 'yes', 40); reply($ok, ['log' => $log]); } if ($action === 'svc-update' || $action === 'svc-rollback') { $svc = $_POST['service'] ?? ''; if (!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/', $svc)) reply(false, ['error' => sv_t('Invalid service name')]); act($action === 'svc-rollback' ? sv_t('Rollback {0}', $svc) : sv_t('Update {0}', $svc)); if ($action === 'svc-rollback') { [$rc, $out] = sv_run([$DOCKER, 'service', 'rollback', '--detach', $svc], null, [], 60); reply($rc === 0, $rc === 0 ? ['log' => sv_t('{0} is rolled back to the previous version.', $svc)] : ['error' => sv_t('{0} failed', 'Rollback'), 'log' => $out]); } [$rc, $img] = sv_run([$DOCKER, 'service', 'inspect', $svc, '--format', '{{.Spec.TaskTemplate.ContainerSpec.Image}}']); if ($rc !== 0) reply(false, ['error' => sv_t('Service "{0}" not found', $svc), 'log' => $img]); $ref = preg_replace('/@[^@\/]+$/', '', trim($img)); // --image without digest → Docker resolves the current digest from the registry [$rc, $out] = sv_run([$DOCKER, 'service', 'update', '--detach', '--with-registry-auth', '--image', $ref, $svc], null, [], 120); if ($rc === 0) { $u = sv_state_read('updates'); if (isset($u['services'][$svc])) { $u['services'][$svc]['update'] = false; sv_state_write('updates', $u); } } reply($rc === 0, $rc === 0 ? ['log' => sv_t('{0} is updated to the newest version of {1}.', $svc, $ref)] : ['error' => sv_t('{0} failed', 'Update'), 'log' => $out]); } if ($action === 'update-check') { require_once __DIR__ . '/updates.php'; // top level → Unraid's Docker classes available globally act(sv_t('Update check')); $u = sv_check_updates(); $avail = array_keys(array_filter($u['services'], fn($x) => $x['update'])); $log = sv_t('{0} services checked.', count($u['services'])) . ' ' . ($avail ? sv_t('Updates available: {0}', implode(', ', $avail)) : sv_t('Everything is up to date.')); if ($u['errors']) $log .= "\n\n" . sv_t('Could not be checked:') . "\n" . implode("\n", array_unique($u['errors'])); reply(true, ['log' => $log, 'checked' => $u['checked']]); } if ($action === 'notify-test') { $ok = sv_notify(sv_t('Test notification'), sv_t('Swarm View can notify you.'), $_POST['level'] ?? 'normal'); reply($ok, $ok ? ['log' => sv_t('Test notification sent.')] : ['error' => sv_t('{0} failed', 'notify')]); } if ($action === 'log-clear') { if (!sv_log_clear()) reply(false, ['error' => sv_t('The log could not be cleared')]); sv_log('info', 'settings', sv_t('Log cleared.')); reply(true, ['log' => sv_t('Log cleared.')]); } if ($action === 'settings') { $cfg = sv_cfg(); // missing fields keep their previous value $pick = fn($k, array $allowed) => isset($_POST[$k]) && in_array($_POST[$k], $allowed, true) ? $_POST[$k] : $cfg[$k]; $in = [ 'REMOTE_ROWS' => $pick('REMOTE_ROWS', ['always', 'advanced', 'never']), 'HOST_COLUMN' => $pick('HOST_COLUMN', ['yes', 'no']), 'FOLDER_LOAD' => $pick('FOLDER_LOAD', ['total', 'local']), 'LANGUAGE' => $pick('LANGUAGE', ['auto', 'en', 'de']), 'ORPHAN_IMAGES' => $pick('ORPHAN_IMAGES', ['show', 'swarm', 'hide']), 'SWARM_POSITION' => $pick('SWARM_POSITION', ['top', 'middle', 'bottom']), 'REFRESH' => isset($_POST['REFRESH']) ? (string)max(5, min(300, (int)$_POST['REFRESH'])) : $cfg['REFRESH'], 'DEPLOY_PRUNE' => $pick('DEPLOY_PRUNE', ['yes', 'no']), 'CLEANUP_SCHEDULE' => $pick('CLEANUP_SCHEDULE', ['off', 'daily', 'weekly']), 'CLEANUP_IMAGES' => $pick('CLEANUP_IMAGES', ['yes', 'no']), ]; $yn = ['yes', 'no']; $lvl = ['normal', 'warning', 'alert']; $num = fn($k, $min, $max) => isset($_POST[$k]) && is_numeric($_POST[$k]) ? (string)max($min, min($max, (int)$_POST[$k])) : $cfg[$k]; $in += [ 'UPDATE_CHECK' => $pick('UPDATE_CHECK', $yn), 'UPDATE_INTERVAL' => $num('UPDATE_INTERVAL', 1, 168), 'NOTIFY_ENABLED' => $pick('NOTIFY_ENABLED', $yn), 'NOTIFY_NODE' => $pick('NOTIFY_NODE', $yn), 'NOTIFY_NODE_DELAY' => $num('NOTIFY_NODE_DELAY', 0, 120), 'NOTIFY_NODE_LEVEL' => $pick('NOTIFY_NODE_LEVEL', $lvl), 'NOTIFY_CRASH' => $pick('NOTIFY_CRASH', $yn), 'NOTIFY_CRASH_COUNT' => $num('NOTIFY_CRASH_COUNT', 2, 50), 'NOTIFY_CRASH_WINDOW' => $num('NOTIFY_CRASH_WINDOW', 2, 240), 'NOTIFY_CRASH_LEVEL' => $pick('NOTIFY_CRASH_LEVEL', $lvl), 'NOTIFY_PENDING' => $pick('NOTIFY_PENDING', $yn), 'NOTIFY_PENDING_DELAY' => $num('NOTIFY_PENDING_DELAY', 0, 240), 'NOTIFY_PENDING_LEVEL' => $pick('NOTIFY_PENDING_LEVEL', $lvl), 'NOTIFY_MOVED' => $pick('NOTIFY_MOVED', $yn), 'NOTIFY_MOVED_LEVEL' => $pick('NOTIFY_MOVED_LEVEL', $lvl), 'NOTIFY_UPDATES' => $pick('NOTIFY_UPDATES', $yn), 'NOTIFY_UPDATES_LEVEL' => $pick('NOTIFY_UPDATES_LEVEL', $lvl), 'NOTIFY_RECOVERY' => $pick('NOTIFY_RECOVERY', $yn), 'NOTIFY_REPEAT' => $num('NOTIFY_REPEAT', 0, 168), 'NOTIFY_IGNORE' => $cfg['NOTIFY_IGNORE'], 'REBALANCE' => $pick('REBALANCE', $yn), 'REBALANCE_DELAY' => $num('REBALANCE_DELAY', 1, 120), 'STATS' => $pick('STATS', $yn), 'STATS_INTERVAL' => $num('STATS_INTERVAL', 5, 300), 'LOG_LEVEL' => $pick('LOG_LEVEL', array_keys(SV_LOG_LEVELS)), ]; if (isset($_POST['NOTIFY_IGNORE'])) { $re = str_replace('"', '', trim((string)$_POST['NOTIFY_IGNORE'])); if ($re !== '' && @preg_match('~' . str_replace('~', '\~', $re) . '~', '') === false) { reply(false, ['error' => sv_t('Invalid regular expression in "Ignore services"')]); } $in['NOTIFY_IGNORE'] = $re; } if (!sv_cfg_write($in)) reply(false, ['error' => sv_t('Settings could not be saved')]); $changes = []; foreach ($in as $k => $v) if ((string)($cfg[$k] ?? '') !== (string)$v) $changes[] = "$k: {$cfg[$k]} → $v"; if ($changes) sv_log('info', 'settings', sv_t('Settings saved.'), implode("\n", $changes)); $log = [sv_t('Settings saved.'), sv_cron_apply($in)]; // automatic return switched off: the watchdog may not run anymore → finish pending returns now if ($in['REBALANCE'] !== 'yes' && ($gone = sv_rebalance_forget(null, true))) { $log[] = sv_t('Pending returns stopped: {0}', implode(', ', $gone)); sv_log('info', 'settings', sv_t('Pending returns stopped: {0}', implode(', ', $gone))); } // Worth a popup: watchdog runs, agent (re)started or stopped, swarm values changed $notable = sv_monitor_needed($in) && !sv_monitor_needed($cfg); $sw0 = sv_swarm_settings(); if ($sw0['active'] && $sw0['manager']) { $log[] = sv_agent_apply($in, $agentChanged); $notable = $notable || $agentChanged; if ($agentChanged) sv_log(str_contains(end($log), "\n") ? 'error' : 'info', 'agent', strtok(end($log), "\n"), end($log)); } // only touch swarm cluster values when they changed $sw = sv_swarm_settings(); if ($sw['active'] && $sw['manager']) { $args = [$DOCKER, 'swarm', 'update']; $hist = isset($_POST['HISTORY_LIMIT']) ? max(1, min(20, (int)$_POST['HISTORY_LIMIT'])) : null; $hb = isset($_POST['HEARTBEAT']) ? max(1, min(60, (int)$_POST['HEARTBEAT'])) : null; if ($hist !== null && $hist !== $sw['historyLimit']) array_push($args, '--task-history-limit', (string)$hist); if ($hb !== null && $hb !== $sw['heartbeat']) array_push($args, '--dispatcher-heartbeat', "{$hb}s"); if (count($args) > 3) { [$rc, $out] = sv_run($args); if ($rc !== 0) reply(false, ['error' => sv_t('{0} failed', 'swarm update'), 'log' => implode("\n", $log) . "\n\n" . $out]); if ($hist !== null && $hist !== $sw['historyLimit']) $log[] = sv_t('Task history: {0} containers per service', $hist); if ($hb !== null && $hb !== $sw['heartbeat']) $log[] = "Heartbeat: {$hb} s"; $notable = true; } } reply(true, ['log' => implode("\n", $log), 'notable' => $notable, 'reload' => ($in['LANGUAGE'] ?? '') !== ($cfg['LANGUAGE'] ?? '')]); } if ($action === 'node-availability') { $node = $_POST['node'] ?? ''; $avail = $_POST['availability'] ?? ''; if (!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/', $node)) reply(false, ['error' => sv_t('Invalid node')]); if (!in_array($avail, ['active', 'pause', 'drain'], true)) reply(false, ['error' => sv_t('Invalid availability')]); act(sv_t('Node {0}: availability {1}', $node, $avail)); [$rc, $out] = sv_run([$DOCKER, 'node', 'update', '--availability', $avail, $node]); $txt = ['active' => sv_t('active'), 'pause' => sv_t('paused (no new containers)'), 'drain' => sv_t('in maintenance (containers are moved away)')][$avail]; reply($rc === 0, $rc === 0 ? ['log' => sv_t('{0} is now {1}.', $node, $txt)] : ['error' => sv_t('{0} failed', 'node update'), 'log' => $out]); } $name = $_POST['name'] ?? ''; if (!sv_valid_name($name)) reply(false, ['error' => sv_t('Invalid stack name – allowed: a-z, 0-9, - and _ (max. 63 characters)')]); $dir = "$STACK_ROOT/$name"; $yml = "$dir/$STACK_FILE"; $env = "$dir/.env"; function normalize(string $s): string { $s = str_replace(["\r\n", "\r"], "\n", $s); return rtrim($s) === '' ? '' : rtrim($s) . "\n"; } function deployed(string $name): bool { global $DOCKER; [$rc, $out] = sv_run([$DOCKER, 'stack', 'ls', '--format', '{{.Name}}']); return $rc === 0 && in_array($name, explode("\n", $out), true); } function validate(): array { global $DOCKER, $yml, $env, $dir, $STACK_FILE; [$rc, $out] = sv_run([$DOCKER, 'stack', 'config', '-c', $STACK_FILE], $dir, sv_parse_env($env), 30); if ($rc !== 0 && preg_match('/unknown command|is not a docker command/i', $out)) { return [true, sv_t('Note: "docker stack config" not available – file not checked.')]; } return [$rc === 0, $rc === 0 ? sv_t('File is valid.') : $out]; } $TEMPLATE = << sv_t('Stack "{0}" already exists', $name)]); if (!@mkdir($dir, 0755, true)) reply(false, ['error' => sv_t('Folder could not be created: {0}', $dir)]); file_put_contents($yml, sprintf($TEMPLATE, $name)); file_put_contents($env, "# KEY=VALUE\n"); reply(true, ['yml' => file_get_contents($yml), 'env' => file_get_contents($env)]); case 'get': if (!is_file($yml)) reply(false, ['error' => sv_t('Stack "{0}" is not managed by Swarm View', $name)]); reply(true, [ 'yml' => file_get_contents($yml), 'env' => is_file($env) ? file_get_contents($env) : '', 'path' => $dir, 'deployed' => deployed($name), ]); case 'describe': if (!is_dir($dir)) reply(false, ['error' => sv_t('Stack "{0}" does not exist', $name)]); $desc = trim(preg_replace('/\s+/u', ' ', (string)($_POST['description'] ?? ''))); if (mb_strlen($desc) > 300) reply(false, ['error' => sv_t('Description is too long (max. 300 characters)')]); if ($desc === '') @unlink("$dir/description.txt"); elseif (file_put_contents("$dir/description.txt", $desc . "\n") === false) reply(false, ['error' => sv_t('Description could not be saved')]); reply(true, ['description' => $desc]); case 'save': act(sv_t('Save stack {0}', $name)); if (!is_dir($dir)) reply(false, ['error' => sv_t('Stack "{0}" does not exist', $name)]); $ymlNew = normalize($_POST['yml'] ?? ''); if ($ymlNew === '') reply(false, ['error' => sv_t('docker-stack.yml must not be empty')]); file_put_contents($yml, $ymlNew); file_put_contents($env, normalize($_POST['env'] ?? '')); [$valid, $log] = validate(); reply(true, ['valid' => $valid, 'log' => $log]); case 'deploy': $update = ($_POST['mode'] ?? '') === 'update'; act($update ? sv_t('Update Stack {0}', $name) : sv_t('Stack Up {0}', $name)); if (!is_file($yml)) reply(false, ['error' => sv_t('No {0} for "{1}"', $STACK_FILE, $name)]); [$valid, $vlog] = validate(); if (!$valid) reply(false, ['error' => sv_t('Stack file invalid'), 'log' => $vlog]); // Stack Up: resolve images only if they changed in the file (no restart of unchanged services) // Update Stack: ask the registry for new versions $cmd = [$DOCKER, 'stack', 'deploy', '--detach=true', '--with-registry-auth', '--resolve-image', $update ? 'always' : 'changed']; if (sv_cfg()['DEPLOY_PRUNE'] === 'yes') $cmd[] = '--prune'; array_push($cmd, '-c', $STACK_FILE, $name); [$rc, $out] = sv_run($cmd, $dir, sv_parse_env($env), 300); // the deploy sets constraints and labels from the file again → returns in progress of this stack are void if ($rc === 0) sv_rebalance_forget(fn($svc) => str_starts_with($svc, "{$name}_"), false); reply($rc === 0, ['log' => ($update ? sv_t('Update: pulling the newest image versions.') . "\n" : '') . ($out ?: sv_t('Deploy started.'))]); case 'remove': act(sv_t('Stack Down {0}', $name)); [$rc, $out] = sv_run([$DOCKER, 'stack', 'rm', $name]); reply($rc === 0, ['log' => $out]); case 'restart': act(sv_t('Restart stack {0}', $name)); [$rc, $out] = sv_run([$DOCKER, 'stack', 'services', $name, '--format', '{{.Name}}']); if ($rc !== 0) reply(false, ['log' => $out]); $log = []; $ok = true; foreach (array_filter(explode("\n", $out)) as $svc) { [$r, $o] = sv_run([$DOCKER, 'service', 'update', '--force', '--detach', $svc]); $ok = $ok && $r === 0; $log[] = "$svc: " . ($r === 0 ? sv_t('restarted') : $o); } reply($ok, ['log' => implode("\n", $log) ?: sv_t('No services in the stack.')]); case 'delete': act(sv_t('Delete stack {0}', $name)); if (deployed($name)) reply(false, ['error' => sv_t('Stack is still deployed – "Stack Down" first')]); if (!is_dir($dir)) reply(false, ['error' => sv_t('Stack "{0}" does not exist', $name)]); [$rc, $out] = sv_run(['rm', '-rf', '--', $dir]); reply($rc === 0, ['log' => $rc === 0 ? sv_t('Files of "{0}" deleted.', $name) : $out]); default: reply(false, ['error' => sv_t('Unknown action')]); } ]]> &1', $out, $rc); $txt = implode("\n", $out); if ($rc !== 0) { $errors[] = "$ctx: " . trim($txt); return null; } return $txt; } /** Parses output of --format '{{json .}}' (one JSON object per line). */ function jsonLines(?string $txt): array { if ($txt === null) return []; $rows = []; foreach (explode("\n", $txt) as $line) { $line = trim($line); if ($line === '') continue; $d = json_decode($line, true); if (is_array($d)) $rows[] = $d; } return $rows; } function jsonDoc(?string $txt): array { if ($txt === null) return []; $d = json_decode($txt, true); return is_array($d) ? $d : []; } /** "a=b,c=d" from `docker ps` → map. Commas in values are kept as long as no "key=" follows. */ function parseLabels(string $s): array { $map = []; if ($s === '') return $map; foreach (preg_split('/,(?=[A-Za-z0-9_.\-\/]+=)/', $s) as $kv) { $p = strpos($kv, '='); if ($p === false) continue; $map[substr($kv, 0, $p)] = substr($kv, $p + 1); } return $map; } function args(array $ids): string { return implode(' ', array_map('escapeshellarg', $ids)); } $hostname = gethostname() ?: 'Unraid'; /* ---------- Swarm-Status ---------- */ $info = jsonDoc(dk("info --format '{{json .Swarm}}'", 'docker info')); $swarm = [ 'state' => $info['LocalNodeState'] ?? 'unknown', 'manager' => !empty($info['ControlAvailable']), 'nodeId' => $info['NodeID'] ?? '', 'historyLimit' => $info['Cluster']['Spec']['Orchestration']['TaskHistoryRetentionLimit'] ?? null, ]; $swarm['active'] = $swarm['state'] === 'active'; $nodes = []; $stacks = []; $selfHost = $hostname; if ($swarm['active'] && $swarm['manager']) { /* ---------- Nodes ---------- */ $nodeIds = array_column(jsonLines(dk("node ls --format '{{json .}}'", 'node ls')), 'ID'); if ($nodeIds) { foreach (jsonDoc(dk('node inspect ' . args($nodeIds), 'node inspect')) as $n) { $isSelf = ($n['ID'] ?? '') === $swarm['nodeId']; $h = $n['Description']['Hostname'] ?? ($n['ID'] ?? '?'); if ($isSelf) $selfHost = $h; $nodes[] = [ 'id' => $n['ID'] ?? '', 'hostname' => $h, 'self' => $isSelf, 'role' => $n['Spec']['Role'] ?? '', 'availability' => $n['Spec']['Availability'] ?? '', 'state' => $n['Status']['State'] ?? '', 'addr' => $n['Status']['Addr'] ?? '', 'leader' => !empty($n['ManagerStatus']['Leader']), 'arch' => $n['Description']['Platform']['Architecture'] ?? '', 'cpus' => round(($n['Description']['Resources']['NanoCPUs'] ?? 0) / 1e9, 1), 'memGB' => round(($n['Description']['Resources']['MemoryBytes'] ?? 0) / 1073741824, 1), 'engine' => $n['Description']['Engine']['EngineVersion'] ?? '', 'labels' => (object)($n['Spec']['Labels'] ?? []), ]; } // Self zuerst, Rest alphabetisch usort($nodes, fn($a, $b) => [$b['self'], $a['hostname']] <=> [$a['self'], $b['hostname']]); } /* ---------- Services ---------- */ $svcLs = jsonLines(dk("service ls --format '{{json .}}'", 'service ls')); if ($svcLs) { // join by name: `service ls` always shortens IDs to 12 characters, `inspect` returns them in full $lsByName = array_column($svcLs, null, 'Name'); $svcArg = args(array_column($svcLs, 'ID')); $services = []; foreach (jsonDoc(dk("service inspect $svcArg", 'service inspect')) as $s) { $name = $s['Spec']['Name'] ?? '?'; $stack = $s['Spec']['Labels']['com.docker.stack.namespace'] ?? ''; $ls = $lsByName[$name] ?? []; $img = $s['Spec']['TaskTemplate']['ContainerSpec']['Image'] ?? ($ls['Image'] ?? ''); $prevImg = $s['PreviousSpec']['TaskTemplate']['ContainerSpec']['Image'] ?? ''; $portList = array_map(fn($p) => [ 'target' => $p['TargetPort'] ?? 0, 'published' => $p['PublishedPort'] ?? 0, 'proto' => $p['Protocol'] ?? 'tcp', ], $s['Endpoint']['Ports'] ?? ($s['Spec']['EndpointSpec']['Ports'] ?? [])); $services[$name] = [ 'id' => $s['ID'] ?? '', 'name' => $name, 'short' => ($stack !== '' && str_starts_with($name, "{$stack}_")) ? substr($name, strlen($stack) + 1) : $name, 'stack' => $stack, 'image' => preg_replace('/@sha256:[0-9a-f]+$/i', '', $img), // no registry digest = locally built image (e.g. local/node-red-mcp) → only on nodes that have it 'localImage' => $img !== '' && strpos($img, '@') === false, 'mode' => isset($s['Spec']['Mode']['Global']) ? 'global' : 'replicated', 'replicas' => $ls['Replicas'] ?? '', 'desired' => isset($s['Spec']['Mode']['Replicated']) ? (int)($s['Spec']['Mode']['Replicated']['Replicas'] ?? 0) : null, 'ports' => implode(', ', array_map(fn($p) => $p['published'] ? "{$p['published']}→{$p['target']}/{$p['proto']}" : "{$p['target']}/{$p['proto']}", $portList)), 'constraints' => $s['Spec']['TaskTemplate']['Placement']['Constraints'] ?? [], 'platforms' => array_values(array_unique(array_filter(array_map( fn($p) => $p['Architecture'] ?? '', $s['Spec']['TaskTemplate']['Placement']['Platforms'] ?? [] )))), 'labels' => (object)($s['Spec']['TaskTemplate']['ContainerSpec']['Labels'] ?? []), 'prefer' => trim($s['Spec']['Labels']['swarm-view.prefer'] ?? ''), // display name in Unraid's list (replacement for container_name, which Swarm ignores) 'alias' => mb_substr(trim($s['Spec']['TaskTemplate']['ContainerSpec']['Labels']['swarm-view.name'] ?? ($s['Spec']['Labels']['swarm-view.name'] ?? '')), 0, 64), // offer rollback only if the image version changed (not for placement, labels …) 'canRollback' => $prevImg !== '' && $prevImg !== $img, 'rollbackTo' => $prevImg !== '' && $prevImg !== $img ? sv_short_ref($prevImg) : '', 'internal' => !empty($s['Spec']['Labels']['swarm-view.agent']) || !empty($s['Spec']['Labels']['swarm-view.cleanup']), 'mounts' => array_map(fn($m) => [ 'type' => $m['Type'] ?? '', 'source' => $m['Source'] ?? '', 'target' => $m['Target'] ?? '', 'ro' => !empty($m['ReadOnly']), ], $s['Spec']['TaskTemplate']['ContainerSpec']['Mounts'] ?? []), 'portList' => $portList, 'tasks' => [], ]; } /* ---------- Tasks (what runs where) ---------- */ $tasks = jsonLines(dk("service ps $svcArg --no-trunc --filter desired-state=running --format '{{json .}}'", 'service ps')); foreach ($tasks as $t) { $tn = $t['Name'] ?? ''; $dot = strrpos($tn, '.'); $sn = $dot === false ? $tn : substr($tn, 0, $dot); if (!isset($services[$sn])) continue; $node = $t['Node'] ?? ''; $services[$sn]['tasks'][] = [ 'id' => $t['ID'] ?? '', 'slot' => $dot === false ? '' : substr(substr($tn, $dot + 1), 0, 12), 'node' => $node, 'local' => $node !== '' && $node === $selfHost, 'current' => $t['CurrentState'] ?? '', 'error' => $t['Error'] ?? '', ]; } /* ---------- Details of tasks on other nodes: times, networks, container ID (one call) ---------- */ $remoteIds = []; foreach ($services as $sv) foreach ($sv['tasks'] as $t) if ($t['id'] !== '' && !$t['local'] && $t['node'] !== '') $remoteIds[] = $t['id']; $detail = []; if ($remoteIds) { foreach (array_chunk($remoteIds, 60) as $chunk) { [, $o] = sv_run(array_merge([$DOCKER, 'inspect', '--type', 'task'], $chunk), null, [], 20); foreach ((json_decode(substr($o, (int)strpos($o, '[')), true) ?: []) as $ti) { $nets = []; foreach ($ti['NetworksAttachments'] ?? [] as $na) { $nets[] = [ 'name' => $na['Network']['Spec']['Name'] ?? '', 'addr' => preg_replace('#/\d+$#', '', $na['Addresses'][0] ?? ''), ]; } $detail[$ti['ID'] ?? ''] = [ 'created' => $ti['CreatedAt'] ?? '', 'since' => $ti['Status']['Timestamp'] ?? '', 'containerId' => substr($ti['Status']['ContainerStatus']['ContainerID'] ?? '', 0, 12), 'networks' => $nets, ]; } } } foreach ($services as &$sv) foreach ($sv['tasks'] as &$t) if (isset($detail[$t['id']])) $t += $detail[$t['id']]; unset($sv, $t); // Node-Auswahl: aktuell per Constraint festgelegter Node ('' = Swarm entscheidet) $updates = sv_state_read('updates'); $rebal = sv_state_read('monitor')['rebalance'] ?? []; foreach ($services as &$svc) { // a return to the preferred node is only shown while it really runs: the watchdog's temporary // node.hostname constraint is set, the tasks have not arrived yet and it is not overdue (watchdog: 10 min) $ph = $rebal[$svc['name']] ?? null; $cn = sv_constraint_node($svc['constraints']); $tmp = $ph && $cn !== '' && $cn === ($ph['node'] ?? '') && sv_now() - (int)($ph['since'] ?? 0) <= 660; $arrived = $tmp && $svc['tasks'] && !array_filter($svc['tasks'], fn($t) => !(stripos($t['current'], 'Running') === 0 && $t['node'] === $cn)); $svc['placeNode'] = $tmp ? '' : $cn; // the temporary binding is not a fixed node $svc['rebalancing'] = $tmp && !$arrived; $u = $updates['services'][$svc['name']] ?? null; $svc['update'] = $u ? (bool)$u['update'] : null; // replicas: from `service ls`; if missing, compute from the tasks if (!preg_match('/^\d+\/\d+/', (string)$svc['replicas'])) { $run = count(array_filter($svc['tasks'], fn($t) => stripos($t['current'], 'Running') === 0)); $want = $svc['desired'] ?? count($svc['tasks']); $svc['replicas'] = "$run/$want"; } } unset($svc); // do not show internal helper services (agent, cleanup job) as stacks $services = array_filter($services, fn($x) => !$x['internal']); foreach ($services as $svc) { $key = $svc['stack'] !== '' ? $svc['stack'] : '(no stack)'; $stacks[$key][] = $svc; } uksort($stacks, fn($a, $b) => [$a === '(no stack)', $a] <=> [$b === '(no stack)', $b]); $stacks = array_map( fn($name, $svcs) => ['name' => $name, 'services' => array_values( (function ($l) { usort($l, fn($a, $b) => strcmp($a['short'], $b['short'])); return $l; })($svcs) )], array_keys($stacks), array_values($stacks) ); } } /* ---------- CPU/RAM from the agent ---------- */ $cfgAll = sv_cfg(); $stats = ['enabled' => $cfgAll['STATS'] === 'yes', 'nodes' => (object)[], 'tasks' => (object)[]]; if ($stats['enabled'] && $swarm['active'] && $swarm['manager']) { $tasksStats = []; $nodeStats = []; foreach (sv_agent_read((int)$cfgAll['STATS_INTERVAL']) as $host => $d) { $mt = (int)($d['memTotal'] ?? 0); $nodeStats[$host] = [ 'cpu' => round(($d['cpu'] ?? 0) / 10, 1), 'mem' => $mt ? round(100 * ($mt - (int)($d['memAvail'] ?? 0)) / $mt, 1) : null, 'memGB' => round($mt / 1048576, 1), 'stale' => !empty($d['stale']), 'ncpu' => (int)($d['ncpu'] ?? 0), 'ts' => (int)($d['ts'] ?? 0), ]; if (!empty($d['stale'])) continue; // do not show container values of a stale state as current foreach ($d['stats'] ?? [] as $c) { // Containername eines Swarm-Tasks: .. $nm = $c['Name'] ?? ''; $tid = substr($nm, (int)strrpos($nm, '.') + 1); if (strlen($tid) < 20) continue; $mem = $c['MemUsage'] ?? ''; $approx = false; // node without memory cgroup: fallback value from the RSS sum of the container processes if (preg_match('#^0B\s*/\s*0B$#', trim($mem)) && isset($d['rss'][$nm])) { $mem = sprintf('%.2fMiB / %.2fGiB', $d['rss'][$nm] / 1024, (int)($d['memTotal'] ?? 0) / 1048576); $approx = true; } $tasksStats[$tid] = ['cpu' => $c['CPUPerc'] ?? '', 'mem' => $mem, 'memPerc' => $c['MemPerc'] ?? '', 'node' => $host, 'ncpu' => (int)($d['ncpu'] ?? 0), 'memTotal' => (int)($d['memTotal'] ?? 0) * 1024, 'memApprox' => $approx]; } } $stats['nodes'] = (object)$nodeStats; $stats['tasks'] = (object)$tasksStats; } /* ---------- Local containers (for the host column in Unraid's table) ---------- */ $containers = []; foreach (jsonLines(dk("ps -a --format '{{json .}}'", 'docker ps')) as $c) { $labels = parseLabels($c['Labels'] ?? ''); $containers[$c['Names'] ?? ''] = [ 'swarmStack' => $labels['com.docker.stack.namespace'] ?? '', 'swarmService' => $labels['com.docker.swarm.service.name'] ?? '', 'compose' => $labels['com.docker.compose.project'] ?? '', ]; } echo json_encode([ 'ok' => empty($errors), 'host' => $selfHost, 'swarm' => $swarm, 'nodes' => $nodes, 'stacks' => $stacks, 'containers' => (object)$containers, 'managed' => sv_managed_stacks(), 'stackInfo' => (object)array_combine(sv_managed_stacks(), array_map(fn($n) => [ 'path' => "$STACK_ROOT/$n", 'description' => is_file("$STACK_ROOT/$n/description.txt") ? trim((string)file_get_contents("$STACK_ROOT/$n/description.txt")) : '', ], sv_managed_stacks())), 'stats' => $stats, 'updates' => ['enabled' => $cfgAll['UPDATE_CHECK'] === 'yes', 'checked' => sv_state_read('updates')['checked'] ?? null], 'config' => (function () { $c = sv_cfg(); return [ 'remoteRows' => $c['REMOTE_ROWS'], 'hostColumn' => $c['HOST_COLUMN'] === 'yes', 'folderLoad' => $c['FOLDER_LOAD'], 'orphans' => $c['ORPHAN_IMAGES'], 'rebalance' => $c['REBALANCE'] === 'yes', 'rebalanceDelay' => (int)$c['REBALANCE_DELAY'], 'refresh' => (int)$c['REFRESH'], ]; })(), 'errors' => $errors, 'time' => date('H:i:s'), ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ]]> 'auto', // auto (Unraid's language) | en | de 'REMOTE_ROWS' => 'always', // always | advanced | never 'HOST_COLUMN' => 'yes', 'SWARM_POSITION' => 'bottom', // top | middle | bottom – position of the Swarm section on the Docker page 'ORPHAN_IMAGES' => 'swarm', // show | swarm | hide – orphan images in Unraid's list 'FOLDER_LOAD' => 'total', // total | local – CPU/RAM of Folder View folders 'REFRESH' => '15', // seconds 'DEPLOY_PRUNE' => 'yes', 'CLEANUP_SCHEDULE' => 'off', // off | daily | weekly 'CLEANUP_IMAGES' => 'yes', // update hints 'UPDATE_CHECK' => 'no', 'UPDATE_INTERVAL' => '12', // hours // notifications 'NOTIFY_ENABLED' => 'no', 'NOTIFY_NODE' => 'yes', 'NOTIFY_NODE_DELAY' => '2', // minutes offline before notifying 'NOTIFY_NODE_LEVEL' => 'alert', 'NOTIFY_CRASH' => 'yes', 'NOTIFY_CRASH_COUNT' => '3', // failed starts … 'NOTIFY_CRASH_WINDOW' => '10', // … within minutes 'NOTIFY_CRASH_LEVEL' => 'warning', 'NOTIFY_PENDING' => 'yes', 'NOTIFY_PENDING_DELAY' => '5', // minutes not placeable 'NOTIFY_PENDING_LEVEL' => 'warning', 'NOTIFY_MOVED' => 'no', // service failed over to another node / returned 'NOTIFY_MOVED_LEVEL' => 'normal', 'NOTIFY_UPDATES' => 'yes', 'NOTIFY_UPDATES_LEVEL' => 'normal', 'NOTIFY_RECOVERY' => 'yes', // all-clear when a problem is resolved 'NOTIFY_REPEAT' => '0', // hours until a reminder (0 = never) 'NOTIFY_IGNORE' => '', // regex for service names to ignore // preferred node 'REBALANCE' => 'no', 'REBALANCE_DELAY' => '5', // minutes the preferred node must be stable // CPU/RAM agent 'STATS' => 'no', 'STATS_INTERVAL' => '10', // seconds // log (settings → Log): debug | info | warn | error – what is recorded 'LOG_LEVEL' => 'info', ]; function sv_cfg(): array { global $CFG_FILE; $c = is_file($CFG_FILE) ? (@parse_ini_file($CFG_FILE, false, INI_SCANNER_RAW) ?: []) : []; return array_merge(SV_DEFAULTS, array_intersect_key($c, SV_DEFAULTS)); } function sv_cfg_write(array $cfg): bool { global $CFG_FILE; @mkdir(dirname($CFG_FILE), 0755, true); $out = ''; foreach (array_merge(SV_DEFAULTS, array_intersect_key($cfg, SV_DEFAULTS)) as $k => $v) { $out .= $k . '="' . str_replace('"', '', (string)$v) . "\"\n"; } $ok = file_put_contents($CFG_FILE, $out) !== false; sv_menu_write($cfg['SWARM_POSITION'] ?? SV_DEFAULTS['SWARM_POSITION']); return $ok; } /** * Position of the Swarm section on the Docker page. SwarmView.page reads its menu rank via * Menu="/boot/config/plugins/swarm-view/menu.cfg MENU=Docker:3" * from this file (Unraid's PageBuilder: get_file_key). Pages are sorted naturally by "": * Docker:0 → before "1DockerContainers" · Docker:1 → after "1DockerContainers" ("S" > "D"), before Compose (rank 2) · Docker:3 → at the end */ function sv_menu_write(string $pos): void { global $CFG_FILE; $rank = ['top' => '0', 'middle' => '1', 'bottom' => '3'][$pos] ?? '3'; @file_put_contents(dirname($CFG_FILE) . '/menu.cfg', "MENU=\"Docker:$rank\"\n"); } /** Valid stack name? (also used as folder name and service prefix) */ function sv_valid_name(string $n): bool { return (bool)preg_match('/^[a-z0-9][a-z0-9_-]{0,62}$/', $n); } /** Names of all stacks managed by Swarm View (folders with docker-stack.yml) */ function sv_managed_stacks(): array { global $STACK_ROOT, $STACK_FILE; $out = []; foreach (glob("$STACK_ROOT/*/$STACK_FILE") ?: [] as $f) { $n = basename(dirname($f)); if (sv_valid_name($n)) $out[] = $n; } sort($out); return $out; } /** Parse .env (KEY=VALUE) – handles comments, "export " and quotes */ function sv_parse_env(string $file): array { $env = []; if (!is_file($file)) return $env; foreach (file($file, FILE_IGNORE_NEW_LINES) as $line) { $line = trim($line); if ($line === '' || $line[0] === '#') continue; if (str_starts_with($line, 'export ')) $line = trim(substr($line, 7)); $p = strpos($line, '='); if ($p === false) continue; $k = trim(substr($line, 0, $p)); $v = trim(substr($line, $p + 1)); if (strlen($v) >= 2 && ($v[0] === '"' || $v[0] === "'") && $v[-1] === $v[0]) $v = substr($v, 1, -1); if (preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $k)) $env[$k] = $v; } return $env; } /** * Run a command without a shell (array form → no quoting problems). * @return array [returncode, kombinierte Ausgabe] */ function sv_run(array $cmd, ?string $cwd = null, array $extraEnv = [], int $timeout = 120): array { $env = array_merge(getenv(), $extraEnv); $p = proc_open($cmd, [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['redirect', 1]], $pipes, $cwd, $env); if (!is_resource($p)) return [127, sv_t('Could not start command: {0}', implode(' ', $cmd))]; fclose($pipes[0]); stream_set_blocking($pipes[1], false); $out = ''; $start = time(); while (true) { $chunk = fread($pipes[1], 8192); if ($chunk !== false && $chunk !== '') { $out .= $chunk; continue; } $st = proc_get_status($p); if (!$st['running']) { $out .= stream_get_contents($pipes[1]); break; } if (time() - $start > $timeout) { proc_terminate($p); $out .= "\n[Timeout nach {$timeout}s]"; break; } usleep(50000); } fclose($pipes[1]); $rc = proc_close($p); if (isset($st) && !$st['running'] && $st['exitcode'] !== -1) $rc = $st['exitcode']; return [$rc, trim($out)]; } /* ---------- Node selection (runtime only, until the next Stack Up) ---------- */ /** Constraints that bind a service to a node (hostname/role/id) */ function sv_is_node_constraint(string $c): bool { return (bool)preg_match('/^\s*node\.(hostname|role|id)\s*(==|!=)/', $c); } /** Node from a hostname constraint ("node.hostname == X" in any spelling) */ function sv_constraint_node(array $cons): string { foreach ($cons as $c) { if (preg_match('/^\s*node\.hostname\s*==\s*(\S+)\s*$/', $c, $m)) return $m[1]; } return ''; } /* ---------- Cleanup (button, settings and cron) ---------- */ /** * Starts a one-off job on every node that deletes stopped Swarm containers * (and optionally unused images). Waits at most $wait seconds. * @return array [ok, log] */ function sv_cleanup(bool $images, int $wait = 40): array { global $DOCKER; $job = 'swarm-view-cleanup'; sv_run([$DOCKER, 'service', 'rm', $job]); // leftovers of an earlier run sleep(1); $cmd = 'echo "== $(hostname)"; docker container prune -f --filter label=com.docker.swarm.service.id'; if ($images) $cmd .= '; docker image prune -f'; [$rc, $out] = sv_run([ $DOCKER, 'service', 'create', '--detach', '--name', $job, '--mode', 'global-job', '--mount', 'type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock', '--label', 'swarm-view.cleanup=1', '--hostname', '{{.Node.Hostname}}', 'docker:cli', 'sh', '-c', $cmd, ], null, [], 60); if ($rc !== 0) return [false, sv_t('Cleanup job could not be started:') . "\n$out"]; $done = false; for ($i = 0; $i < max(1, intdiv($wait, 2)) && !$done; $i++) { sleep(2); [$prc, $ps] = sv_run([$DOCKER, 'service', 'ps', $job, '--format', '{{.CurrentState}}']); $states = array_filter(explode("\n", $ps)); $done = $prc === 0 && $states && !array_filter($states, fn($st) => !preg_match('/^(Complete|Failed|Rejected|Shutdown)/i', $st)); } [, $jl] = sv_run([$DOCKER, 'service', 'logs', '--no-task-ids', '--raw', $job], null, [], 20); if ($done) { sv_run([$DOCKER, 'service', 'rm', $job]); return [true, sv_t('Cleanup job finished on all nodes:') . "\n\n" . trim($jl)]; } return [true, sv_t('The cleanup job is still running (e.g. an image download on a slow node) – it is removed at the next cleanup. Output so far:') . "\n\n" . trim($jl)]; } /** Write the cron file: scheduled cleanup + watchdog every minute (if a watchdog feature is on) */ function sv_cron_apply(array $cfg): string { global $CRON_FILE; $lines = ['# Swarm View']; $msg = []; $when = ['daily' => '17 4 * * *', 'weekly' => '17 4 * * 0'][$cfg['CLEANUP_SCHEDULE']] ?? ''; if ($when) { $lines[] = "$when /usr/bin/php -q /usr/local/emhttp/plugins/swarm-view/scripts/cleanup.php > /dev/null 2>&1"; $msg[] = sv_t('Automatic cleanup: {0} (04:17)', sv_t($cfg['CLEANUP_SCHEDULE'])); } else { $msg[] = sv_t('Automatic cleanup: off'); } if (sv_monitor_needed($cfg)) { $lines[] = "* * * * * /usr/bin/php -q /usr/local/emhttp/plugins/swarm-view/scripts/monitor.php > /dev/null 2>&1"; $msg[] = sv_t('Background watchdog: active (every minute)'); } if (count($lines) > 1) file_put_contents($CRON_FILE, implode("\n", $lines) . "\n"); else @unlink($CRON_FILE); if (is_executable('/usr/local/sbin/update_cron')) exec('/usr/local/sbin/update_cron'); return implode("\n", $msg); } function sv_monitor_needed(array $cfg): bool { return $cfg['NOTIFY_ENABLED'] === 'yes' || $cfg['UPDATE_CHECK'] === 'yes' || $cfg['REBALANCE'] === 'yes'; } /* ---------- Zustand (RAM, /tmp) ---------- */ function sv_state_read(string $name): array { global $STATE_DIR; $f = "$STATE_DIR/$name.json"; $d = is_file($f) ? json_decode((string)file_get_contents($f), true) : null; return is_array($d) ? $d : []; } function sv_state_write(string $name, array $data): void { global $STATE_DIR; @mkdir($STATE_DIR, 0755, true); $tmp = "$STATE_DIR/.$name.json." . getmypid(); file_put_contents($tmp, json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); rename($tmp, "$STATE_DIR/$name.json"); } /* ---------- Log (RAM, settings → Log) ---------- */ const SV_LOG_LEVELS = ['debug' => 0, 'info' => 1, 'warn' => 2, 'error' => 3]; const SV_LOG_MAX = 1048576; // bytes; above that the oldest half is dropped /** * One log entry: sv_log(level, source, translated message, optional details). * $src: watchdog | action | settings | agent. Entries below LOG_LEVEL are not written. */ function sv_log(string $level, string $src, string $msg, ?string $detail = null): void { global $LOG_FILE; if (!isset(SV_LOG_LEVELS[$level])) $level = 'info'; $min = SV_LOG_LEVELS[sv_cfg()['LOG_LEVEL']] ?? 1; if (SV_LOG_LEVELS[$level] < $min) return; $e = ['t' => sv_now(), 'l' => $level, 's' => $src, 'm' => $msg]; $detail = trim((string)$detail); if ($detail !== '' && $detail !== $msg) $e['d'] = mb_substr($detail, 0, 4000); @mkdir(dirname($LOG_FILE), 0755, true); $fh = @fopen($LOG_FILE, 'a+'); if (!$fh) return; flock($fh, LOCK_EX); fwrite($fh, json_encode($e, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE) . "\n"); fflush($fh); $size = fstat($fh)['size'] ?? 0; if ($size > SV_LOG_MAX) { // keep the newer half, starting at a line boundary fseek($fh, $size - intdiv(SV_LOG_MAX, 2)); fgets($fh); $rest = stream_get_contents($fh); ftruncate($fh, 0); rewind($fh); fwrite($fh, $rest); } flock($fh, LOCK_UN); fclose($fh); } /** Last $limit entries (newest last), at least level $min */ function sv_log_read(int $limit = 500, string $min = 'debug'): array { global $LOG_FILE; $minN = SV_LOG_LEVELS[$min] ?? 0; $lines = is_file($LOG_FILE) ? (@file($LOG_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []) : []; $res = []; for ($i = count($lines) - 1; $i >= 0 && count($res) < $limit; $i--) { $e = json_decode($lines[$i], true); if (!is_array($e) || (SV_LOG_LEVELS[$e['l'] ?? ''] ?? 1) < $minN) continue; $res[] = $e; } return array_reverse($res); } function sv_log_clear(): bool { global $LOG_FILE; return !is_file($LOG_FILE) || @file_put_contents($LOG_FILE, '') !== false; } /* ---------- Return to the preferred node: bookkeeping ---------- */ /** * Forget returns in progress (watchdog state), holding the watchdog lock. * $filter(name) selects the services (null = all). With $release the temporary * node.hostname constraint of the return is removed again (otherwise the caller resets the spec itself). * @return string[] names of the services */ function sv_rebalance_forget(?callable $filter, bool $release): array { global $DOCKER, $STATE_DIR; @mkdir($STATE_DIR, 0755, true); $lock = @fopen("$STATE_DIR/monitor.lock", 'c'); if ($lock) flock($lock, LOCK_EX); $state = sv_state_read('monitor'); $done = []; foreach ($state['rebalance'] ?? [] as $name => $ph) { if ($filter && !$filter($name)) continue; if ($release) { [$rc, $out] = sv_run([$DOCKER, 'service', 'inspect', $name, '--format', '{{json .Spec.TaskTemplate.Placement.Constraints}}']); $cons = $rc === 0 ? (json_decode($out, true) ?: []) : []; foreach ($cons as $c) { if (sv_constraint_node([$c]) === ($ph['node'] ?? '')) sv_run([$DOCKER, 'service', 'update', '--detach', '--constraint-rm', $c, $name]); } } unset($state['rebalance'][$name], $state['rebalanceFail'][$name]); $done[] = $name; } if ($done) sv_state_write('monitor', $state); if ($lock) { flock($lock, LOCK_UN); fclose($lock); } return $done; } /* ---------- Unraid-Benachrichtigung ---------- */ function sv_notify(string $subject, string $desc, string $level = 'normal', string $message = ''): bool { global $NOTIFY; if (!in_array($level, ['normal', 'warning', 'alert'], true)) $level = 'normal'; $args = [$NOTIFY, '-e', 'Swarm View', '-s', $subject, '-d', $desc, '-i', $level, '-l', '/Docker']; if ($message !== '') array_push($args, '-m', $message); [$rc] = sv_run($args, null, [], 20); return $rc === 0; } /* ---------- CPU/RAM agent (global service, output via service logs) ---------- */ /** The agent's shell loop: node CPU/RAM from /proc + docker stats, one JSON line per round */ function sv_agent_script(): string { return <<<'SH' ptot=""; pidle="" while true; do set -- $(head -n1 /proc/stat); shift tot=0; for v in "$@"; do tot=$((tot + v)); done idle=$(($4 + $5)); cpu=0 if [ -n "$ptot" ] && [ $((tot - ptot)) -gt 0 ]; then cpu=$((1000 * ((tot - ptot) - (idle - pidle)) / (tot - ptot))); fi ptot=$tot; pidle=$idle mt=$(awk '/^MemTotal:/{print $2}' /proc/meminfo); ma=$(awk '/^MemAvailable:/{print $2}' /proc/meminfo) st=$(docker stats --no-stream --format '{{json .}}' 2>/dev/null | paste -sd, -) # without memory cgroup (Raspberry Pi) docker stats reports "0B / 0B" – then sum the processes' RSS per container (KiB) rss="" case "$st" in *'"MemUsage":"0B / 0B"'*) for n in $(docker ps --format '{{.Names}}'); do kb=$(docker top "$n" -o pid,rss 2>/dev/null | awk 'NR>1{s+=$2} END{print s+0}') rss="$rss${rss:+,}\"$n\":${kb:-0}" done;; esac echo "{\"node\":\"$NODE\",\"ts\":$(date +%s),\"cpu\":$cpu,\"ncpu\":$(nproc),\"memTotal\":$mt,\"memAvail\":$ma,\"stats\":[$st],\"rss\":{$rss}}" sleep "$INTERVAL" done SH; } /** Create, update or remove the agent according to the settings */ const SV_AGENT_VERSION = '2'; // increase when the agent script changes → the agent is recreated function sv_agent_apply(array $cfg, ?bool &$changed = null): string { $changed = false; global $DOCKER; $want = $cfg['STATS'] === 'yes'; $interval = (string)max(5, min(300, (int)$cfg['STATS_INTERVAL'])); [$rc, $out] = sv_run([$DOCKER, 'service', 'inspect', SV_AGENT, '--format', '{{index .Spec.Labels "swarm-view.agent.interval"}}/{{index .Spec.Labels "swarm-view.agent.version"}}']); $exists = $rc === 0; if (!$want) { if ($exists) sv_run([$DOCKER, 'service', 'rm', SV_AGENT]); $changed = $exists; return sv_t('CPU/RAM agent: off'); } if ($exists && trim($out) === "$interval/" . SV_AGENT_VERSION) return sv_t('CPU/RAM agent: active (every {0} s)', $interval); if ($exists) sv_run([$DOCKER, 'service', 'rm', SV_AGENT]); [$rc, $out] = sv_run([ $DOCKER, 'service', 'create', '--detach', '--name', SV_AGENT, '--mode', 'global', '--mount', 'type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock', '--env', 'NODE={{.Node.Hostname}}', '--env', "INTERVAL=$interval", '--hostname', '{{.Node.Hostname}}', '--label', 'swarm-view.agent=1', '--label', "swarm-view.agent.interval=$interval", '--label', 'swarm-view.agent.version=' . SV_AGENT_VERSION, '--log-driver', 'json-file', '--log-opt', 'max-size=256k', '--log-opt', 'max-file=1', '--limit-memory', '64M', '--restart-condition', 'any', 'docker:cli', 'sh', '-c', sv_agent_script(), ], null, [], 60); $changed = true; return $rc === 0 ? sv_t('CPU/RAM agent: started (every {0} s)', $interval) : sv_t('CPU/RAM agent could not be started:') . "\n$out"; } /** Latest values of all nodes from the agent's logs */ function sv_agent_read(int $interval): array { global $DOCKER; // if a node is unreachable, "service logs" ends with an error – the lines of the other nodes are still in the output. // so ignore the return code and evaluate everything that parses as JSON. [, $out] = sv_run([$DOCKER, 'service', 'logs', '--raw', '--tail', '1', SV_AGENT], null, [], 15); $nodes = []; foreach (explode("\n", $out) as $line) { $d = json_decode(trim($line), true); if (!is_array($d) || empty($d['node'])) continue; if (isset($nodes[$d['node']]) && $nodes[$d['node']]['ts'] >= ($d['ts'] ?? 0)) continue; $nodes[$d['node']] = $d; } // remember the last known values per node: if a node is missing (off, rebooting) its values stay visible as "stale" $cache = sv_state_read('agent'); foreach ($nodes as $n => $d) $cache[$n] = $d; foreach ($cache as $n => $d) if (time() - (int)($d['ts'] ?? 0) > 86400) unset($cache[$n]); if ($nodes) sv_state_write('agent', $cache); foreach ($cache as $n => &$d) $d['stale'] = (time() - (int)($d['ts'] ?? 0)) > 3 * $interval + 10; unset($d); return $cache; } /** Swarm cluster values from docker info */ function sv_swarm_settings(): array { global $DOCKER; [$rc, $out] = sv_run([$DOCKER, 'info', '--format', '{{json .Swarm}}']); $sw = $rc === 0 ? (json_decode($out, true) ?: []) : []; $spec = $sw['Cluster']['Spec'] ?? []; return [ 'active' => ($sw['LocalNodeState'] ?? '') === 'active', 'manager' => !empty($sw['ControlAvailable']), 'historyLimit' => $spec['Orchestration']['TaskHistoryRetentionLimit'] ?? null, 'heartbeat' => isset($spec['Dispatcher']['HeartbeatPeriod']) ? (int)round($spec['Dispatcher']['HeartbeatPeriod'] / 1e9) : null, ]; } /** "repo:tag@sha256:abcd…" → "tag (abcd1234)" – short version for rollback labels */ function sv_short_ref(string $img): string { $dg = ''; if (($p = strpos($img, '@')) !== false) { $dg = substr($img, $p + 1); $img = substr($img, 0, $p); } $last = substr($img, (int)strrpos($img, '/')); $tag = strpos($last, ':') !== false ? substr($last, strrpos($last, ':') + 1) : 'latest'; return $tag . ($dg ? ' (' . substr(preg_replace('/^sha256:/', '', $dg), 0, 8) . ')' : ''); } ]]> .json as * { "English text": "translation" }; placeholders are {0}, {1}, … * Language: plugin setting LANGUAGE (auto | en | de); "auto" follows Unraid's display language. */ /** Unraid's display language as a two-letter code ('' = English / unknown) */ function sv_unraid_lang(): string { $file = getenv('SV_DYNAMIX_CFG') ?: '/boot/config/plugins/dynamix/dynamix.cfg'; $ini = @parse_ini_file($file, true); $loc = (string)($ini['display']['locale'] ?? ''); return strtolower(substr($loc, 0, 2)); } /** Active language code */ function sv_lang(): string { static $lang = null; if ($lang !== null) return $lang; $set = function_exists('sv_cfg') ? (sv_cfg()['LANGUAGE'] ?? 'auto') : 'auto'; $code = $set === 'auto' ? sv_unraid_lang() : $set; $lang = ($code !== '' && $code !== 'en' && is_file(__DIR__ . "/../lang/$code.json")) ? $code : 'en'; return $lang; } /** Dictionary of the active language (English → target) */ function sv_lang_dict(): array { static $dict = null; if ($dict !== null) return $dict; $lang = sv_lang(); $dict = $lang === 'en' ? [] : (json_decode((string)@file_get_contents(__DIR__ . "/../lang/$lang.json"), true) ?: []); return $dict; } /** Translate: sv_t('{0} is back on {1}.', $svc, $node) */ function sv_t(string $en, ...$args): string { $s = sv_lang_dict()[$en] ?? $en; foreach ($args as $i => $v) $s = str_replace('{' . $i . '}', (string)$v, $s); return $s; } /** Translate and HTML-escape (for pages) */ function sv_e(string $en, ...$args): string { return htmlspecialchars(sv_t($en, ...$args), ENT_QUOTES); } /** Singular/plural: sv_tn($n, '{0} service', '{0} services') */ function sv_tn(int $n, string $one, string $many): string { return sv_t($n === 1 ? $one : $many, $n); } /** '; } ]]> ","now":ts,"entries":[{t,l,s,m,d?}, …]} (oldest first) */ header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: no-store'); require_once __DIR__ . '/common.php'; $min = $_GET['min'] ?? 'debug'; if (!isset(SV_LOG_LEVELS[$min])) $min = 'debug'; $limit = max(1, min(5000, (int)($_GET['limit'] ?? 1000))); echo json_encode([ 'ok' => true, 'level' => sv_cfg()['LOG_LEVEL'], 'now' => sv_now(), 'entries' => sv_log_read($limit, $min), ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE); ]]> return after an outage * - update check at the configured interval */ require_once __DIR__ . '/updates.php'; /** Report a problem – with delay, reminder and all-clear */ class SvAlerts { public array $st; private array $cfg; private array $seen = []; public array $sent = []; // for tests/log public function __construct(array &$state, array $cfg) { $this->st = &$state; $this->st['alerts'] ??= []; $this->cfg = $cfg; } /** Problem $key exists right now. Notifies after $delayMin minutes, reminds after NOTIFY_REPEAT hours. */ public function problem(string $key, int $delayMin, string $level, string $subject, string $desc): void { $this->seen[$key] = true; $now = sv_now(); $a = &$this->st['alerts'][$key]; $a ??= ['since' => $now, 'notified' => 0, 'subject' => $subject]; $a['subject'] = $subject; if ($now - $a['since'] < $delayMin * 60) return; $repeat = (int)$this->cfg['NOTIFY_REPEAT'] * 3600; if ($a['notified'] && (!$repeat || $now - $a['notified'] < $repeat)) return; $this->send($a['notified'] ? "Erinnerung: $subject" : $subject, $desc, $level); $a['notified'] = $now; } /** At the end of a run: problems not seen anymore are resolved → all-clear if wanted */ public function finish(array $handledPrefixes): void { foreach ($this->st['alerts'] as $key => $a) { $handled = false; foreach ($handledPrefixes as $p) if (str_starts_with($key, $p)) $handled = true; if (!$handled || isset($this->seen[$key])) continue; if ($a['notified'] && $this->cfg['NOTIFY_RECOVERY'] === 'yes') { $this->send(sv_t('Resolved: {0}', $a['subject']), sv_t('The problem no longer exists.'), 'normal'); } unset($this->st['alerts'][$key]); } } public function send(string $subject, string $desc, string $level, string $msg = ''): void { $this->sent[] = "[$level] $subject – $desc"; sv_log($level === 'normal' ? 'info' : 'warn', 'watchdog', sv_t('Notification: {0}', $subject), $desc); // history for the settings page (status) $this->st['history'] ??= []; $this->st['history'][] = ['t' => sv_now(), 'level' => $level, 'subject' => $subject, 'desc' => $desc]; $this->st['history'] = array_slice($this->st['history'], -20); sv_notify($subject, $desc, $level, $msg); } } function sv_monitor_run(array $cfg, bool $verbose = false): array { global $DOCKER; $log = []; $t0 = microtime(true); $state = sv_state_read('monitor'); $now = sv_now(); // event: status feed + syslog + log; debug only goes to the log $ev = function (string $level, string $msg, ?string $detail = null) use (&$log) { $log[] = $msg; sv_log($level, 'watchdog', $msg, $detail); }; $dbg = fn(string $msg, ?string $detail = null) => sv_log('debug', 'watchdog', $msg, $detail); $sw = sv_swarm_settings(); if (!$sw['active'] || !$sw['manager']) { if (empty($state['noManager'])) { sv_log('warn', 'watchdog', sv_t('No active Swarm manager on this server – the watchdog does nothing.')); $state['noManager'] = 1; sv_state_write('monitor', $state); } return [sv_t('No active Swarm manager on this server – the watchdog does nothing.')]; } if (!empty($state['noManager'])) { unset($state['noManager']); sv_log('info', 'watchdog', sv_t('Swarm manager active again – the watchdog continues.')); } /* ---------- Daten sammeln ---------- */ [$rc, $out] = sv_run([$DOCKER, 'node', 'ls', '--format', '{{json .}}']); if ($rc !== 0) sv_log('error', 'watchdog', sv_t('{0} failed', 'docker node ls'), $out); $nodes = []; foreach (explode("\n", $rc === 0 ? $out : '') as $l) { $n = json_decode(trim($l), true); if (is_array($n) && !empty($n['Hostname'])) $nodes[$n['Hostname']] = [ 'ready' => strtolower($n['Status'] ?? '') === 'ready', 'avail' => strtolower($n['Availability'] ?? ''), ]; } // how long has each node been "ready" without interruption? $state['readySince'] ??= []; foreach ($nodes as $h => $n) { if ($n['ready']) $state['readySince'][$h] ??= $now; else unset($state['readySince'][$h]); } // node state changes for the log if ($rc === 0) { $state['nodeState'] ??= []; $label = ['active' => sv_t('online'), 'down' => sv_t('offline'), 'drain' => sv_t('in maintenance'), 'pause' => sv_t('paused')]; $known = $state['nodeState']; foreach ($nodes as $h => $n) { $st = !$n['ready'] ? 'down' : ($n['avail'] ?: 'active'); $prev = $state['nodeState'][$h] ?? null; if ($prev !== null && $prev !== $st) { sv_log($st === 'down' ? 'warn' : 'info', 'watchdog', sv_t('Node {0} is {1} (before: {2}).', $h, $label[$st] ?? $st, $label[$prev] ?? $prev)); } elseif ($prev === null && $known) { sv_log('info', 'watchdog', sv_t('Node {0} joined the swarm ({1}).', $h, $label[$st] ?? $st)); } $state['nodeState'][$h] = $st; } foreach (array_keys($state['nodeState']) as $h) { if (!isset($nodes[$h])) { sv_log('info', 'watchdog', sv_t('Node {0} left the swarm.', $h)); unset($state['nodeState'][$h]); } } } $ignore = trim($cfg['NOTIFY_IGNORE']); $ignored = function (string $svc) use ($ignore): bool { return $ignore !== '' && @preg_match('~' . str_replace('~', '\~', $ignore) . '~', $svc) === 1; }; $services = []; foreach (sv_services_inspect() as $s) { $lab = $s['Spec']['Labels'] ?? []; if (!empty($lab['swarm-view.agent']) || !empty($lab['swarm-view.cleanup'])) continue; $name = $s['Spec']['Name']; $services[$name] = [ 'id' => $s['ID'], 'global' => isset($s['Spec']['Mode']['Global']), 'prefer' => trim($lab['swarm-view.prefer'] ?? ''), 'cons' => $s['Spec']['TaskTemplate']['Placement']['Constraints'] ?? [], 'archs' => array_values(array_filter(array_map(fn($p) => $p['Architecture'] ?? '', $s['Spec']['TaskTemplate']['Placement']['Platforms'] ?? []))), 'updated' => strtotime($s['UpdatedAt'] ?? '') ?: 0, 'tasks' => [], ]; } if ($services) { [$rc, $out] = sv_run(array_merge([$DOCKER, 'service', 'ps', '--no-trunc', '--filter', 'desired-state=running', '--format', '{{json .}}'], array_keys($services)), null, [], 30); if ($rc !== 0) sv_log('error', 'watchdog', sv_t('{0} failed', 'docker service ps'), $out); foreach (explode("\n", $rc === 0 ? $out : '') as $l) { $t = json_decode(trim($l), true); if (!is_array($t)) continue; $tn = $t['Name'] ?? ''; $sn = substr($tn, 0, (int)strrpos($tn, '.')); if (!isset($services[$sn])) continue; $services[$sn]['tasks'][] = [ 'id' => $t['ID'] ?? '', 'node' => $t['Node'] ?? '', 'running' => (bool)preg_match('/^Running/i', $t['CurrentState'] ?? ''), 'pending' => ($t['Node'] ?? '') === '' || (bool)preg_match('/^Pending/i', $t['CurrentState'] ?? ''), 'error' => $t['Error'] ?? '', ]; } } $alerts = new SvAlerts($state, $cfg); $notifyOn = $cfg['NOTIFY_ENABLED'] === 'yes'; /* ---------- Node offline / wieder online ---------- */ if ($notifyOn && $cfg['NOTIFY_NODE'] === 'yes') { foreach ($nodes as $h => $n) { if (!$n['ready'] && $n['avail'] !== 'drain') { $alerts->problem("node:$h", (int)$cfg['NOTIFY_NODE_DELAY'], $cfg['NOTIFY_NODE_LEVEL'], sv_t('Node {0} is offline', $h), sv_t('Swarm cannot reach {0} anymore. Services without a fixed node are moved to other nodes.', $h)); } } } /* ---------- Crash-Loop (viele neue Tasks in kurzer Zeit) ---------- */ $state['taskSeen'] ??= []; $state['restarts'] ??= []; $window = max(1, (int)$cfg['NOTIFY_CRASH_WINDOW']) * 60; foreach ($services as $name => $s) { $prevIds = $state['taskSeen'][$name] ?? null; $ids = array_column($s['tasks'], 'id'); // count new task IDs – unless the service was just changed on purpose (deploy/update/move) if ($prevIds !== null && $s['updated'] < ($state['lastRun'] ?? 0)) { foreach (array_diff($ids, $prevIds) as $new) $state['restarts'][$name][] = $now; } $state['taskSeen'][$name] = $ids; $state['restarts'][$name] = array_values(array_filter($state['restarts'][$name] ?? [], fn($t) => $now - $t < $window)); if (!$state['restarts'][$name]) unset($state['restarts'][$name], $state['crashLogged'][$name]); $cnt = count($state['restarts'][$name] ?? []); if ($cnt >= max(2, (int)$cfg['NOTIFY_CRASH_COUNT']) && empty($state['crashLogged'][$name])) { $state['crashLogged'][$name] = 1; sv_log('warn', 'watchdog', sv_t('{0} keeps restarting', $name) . ' – ' . sv_t('{0} restarts in {1} minutes.', $cnt, $cfg['NOTIFY_CRASH_WINDOW']), implode("\n", array_unique(array_filter(array_column($s['tasks'], 'error'))))); } if ($notifyOn && $cfg['NOTIFY_CRASH'] === 'yes' && !$ignored($name)) { $cnt = count($state['restarts'][$name] ?? []); if ($cnt >= max(2, (int)$cfg['NOTIFY_CRASH_COUNT'])) { $err = implode('; ', array_unique(array_filter(array_column($s['tasks'], 'error')))); $alerts->problem("crash:$name", 0, $cfg['NOTIFY_CRASH_LEVEL'], sv_t('{0} keeps restarting', $name), sv_t('{0} restarts in {1} minutes.', $cnt, $cfg['NOTIFY_CRASH_WINDOW']) . ($err ? ' ' . sv_t('Error: {0}', $err) : '')); } } } foreach (array_keys($state['taskSeen']) as $n) if (!isset($services[$n])) unset($state['taskSeen'][$n], $state['restarts'][$n], $state['crashLogged'][$n]); /* ---------- Not placeable: log (independent of notifications) ---------- */ $state['pendingLogged'] ??= []; foreach ($services as $name => $s) { $pend = array_filter($s['tasks'], fn($t) => $t['pending']); if ($pend && empty($state['pendingLogged'][$name])) { $state['pendingLogged'][$name] = $now; sv_log('warn', 'watchdog', sv_t('{0} cannot start', $name) . ' – ' . sv_t('Swarm finds no suitable node: {0}', implode('; ', array_unique(array_filter(array_column($pend, 'error')))) ?: sv_t('no suitable node'))); } elseif (!$pend && !empty($state['pendingLogged'][$name])) { unset($state['pendingLogged'][$name]); sv_log('info', 'watchdog', sv_t('{0} found a node again.', $name)); } } foreach (array_keys($state['pendingLogged']) as $n) if (!isset($services[$n])) unset($state['pendingLogged'][$n]); /* ---------- Nicht platzierbar ---------- */ if ($notifyOn && $cfg['NOTIFY_PENDING'] === 'yes') { foreach ($services as $name => $s) { if ($ignored($name)) continue; $pend = array_filter($s['tasks'], fn($t) => $t['pending']); if ($pend) { $err = implode('; ', array_unique(array_filter(array_column($pend, 'error')))) ?: sv_t('no suitable node'); $alerts->problem("pending:$name", (int)$cfg['NOTIFY_PENDING_DELAY'], $cfg['NOTIFY_PENDING_LEVEL'], sv_t('{0} cannot start', $name), sv_t('Swarm finds no suitable node: {0}', $err)); } } } /* ---------- Failed over / returned ---------- */ $state['placement'] ??= []; foreach ($services as $name => $s) { $where = array_values(array_unique(array_filter(array_map(fn($t) => $t['running'] ? $t['node'] : '', $s['tasks'])))); sort($where); $before = $state['placement'][$name] ?? null; if ($where) $state['placement'][$name] = $where; if ($before !== null && $where && $before !== $where) { $planned = $s['updated'] >= ($state['lastRun'] ?? 0) || isset($state['rebalance'][$name]); sv_log($planned ? 'debug' : 'info', 'watchdog', sv_t('{0} now runs on {1}', $name, implode(', ', $where)) . ' (' . sv_t('Before: {0}', implode(', ', $before)) . ')' . ($planned ? ' – ' . sv_t('after a change of the service') : '')); } if ($notifyOn && $cfg['NOTIFY_MOVED'] === 'yes' && !$ignored($name) && $before !== null && $where && $before !== $where && $s['updated'] < ($state['lastRun'] ?? 0) && !isset($state['rebalance'][$name])) { $alerts->send(sv_t('{0} now runs on {1}', $name, implode(', ', $where)), sv_t('Before: {0}', implode(', ', $before)), $cfg['NOTIFY_MOVED_LEVEL']); } } foreach (array_keys($state['placement']) as $n) if (!isset($services[$n])) unset($state['placement'][$n]); /* ---------- Preferred node: return after an outage ---------- */ $state['rebalance'] ??= []; $state['rebalanceFail'] ??= []; // services that no longer exist (only when the service list could be read) if ($services) foreach (['rebalance', 'rebalanceFail'] as $k) foreach (array_keys($state[$k]) as $n) if (!isset($services[$n])) unset($state[$k][$n]); if ($cfg['REBALANCE'] === 'yes') { $arch = null; foreach ($services as $name => $s) { $P = $s['prefer']; $phase = $state['rebalance'][$name] ?? null; if ($P === '' || $s['global']) { if ($phase) $dbg(sv_t('{0}: no preferred node anymore – return forgotten.', $name)); unset($state['rebalance'][$name], $state['rebalanceFail'][$name]); continue; } $running = array_filter($s['tasks'], fn($t) => $t['running']); if ($phase) { // step 2: arrived on the target node? → remove the temporary constraint again (no restart) $T = (string)$phase['node']; $tmp = array_values(array_filter($s['cons'], fn($c) => sv_constraint_node([$c]) === $T)); if (!$tmp) { // no temporary binding (removed by hand, Stack Up …) → nothing is returning unset($state['rebalance'][$name]); $dbg(sv_t('{0}: return to {1} forgotten – the temporary node binding is gone.', $name, $T)); continue; } $onT = $s['tasks'] && !array_filter($s['tasks'], fn($t) => !($t['running'] && $t['node'] === $T)); $age = $now - (int)$phase['since']; // target node fails during the return: release the binding at once so Swarm can fail over $tGone = !(($nodes[$T] ?? null) && $nodes[$T]['ready'] && $nodes[$T]['avail'] === 'active'); $down = !$running && $age > 300; // the return took the service down and it does not start on the target $timeout = $age > 600; $changed = $T !== $P; // preferred node changed meanwhile if (!$onT && !$tGone && !$down && !$timeout && !$changed) { $dbg(sv_t('{0}: return to {1} in progress ({2} s).', $name, $T, $age)); continue; } foreach ($tmp as $c) { [$rc, $o] = sv_run([$DOCKER, 'service', 'update', '--detach', '--constraint-rm', $c, $name]); if ($rc !== 0) sv_log('error', 'watchdog', sv_t('{0}: the temporary node binding could not be removed.', $name), $o); } unset($state['rebalance'][$name]); $errs = implode("\n", array_unique(array_filter(array_column($s['tasks'], 'error')))); if ($onT) { unset($state['rebalanceFail'][$name]); $ev('info', sv_t('{0} is back on {1}.', $name, $T)); if ($notifyOn && $cfg['NOTIFY_MOVED'] === 'yes') $alerts->send(sv_t('{0} is back on {1}', $name, $T), sv_t('Automatic return to the preferred node.'), $cfg['NOTIFY_MOVED_LEVEL']); } elseif ($tGone) { $ev('warn', sv_t('{0}: return cancelled, {1} is not available.', $name, $T)); } elseif ($changed) { $ev('info', sv_t('{0}: return to {1} stopped – the placement was changed.', $name, $T)); } else { // failed: do not try again every few minutes (each attempt restarts the service) $f = $state['rebalanceFail'][$name] ?? []; $n = (($f['node'] ?? '') === $T ? (int)($f['n'] ?? 0) : 0) + 1; $wait = min(1440, 30 * 2 ** ($n - 1)); $state['rebalanceFail'][$name] = ['node' => $T, 'n' => $n, 'until' => $now + $wait * 60]; $ev('warn', ($down ? sv_t('{0} does not start on {1} – return cancelled, Swarm runs it elsewhere again.', $name, $T) : sv_t('{0}: return to {1} cancelled (timeout).', $name, $T)) . ' ' . sv_t('Next attempt in {0} minutes.', $wait), $errs); } continue; } // step 1: check the conditions and set the constraint $fail = $state['rebalanceFail'][$name] ?? null; if ($fail && ($fail['node'] ?? '') !== $P) { unset($state['rebalanceFail'][$name]); $fail = null; } if (!$running) continue; // not running at all → nothing to move if (!array_filter($running, fn($t) => $t['node'] !== $P)) { // already runs there if ($fail) unset($state['rebalanceFail'][$name]); continue; } $node = $nodes[$P] ?? null; if (!$node || !$node['ready'] || $node['avail'] !== 'active') { $dbg(sv_t('{0} waits for {1}: node not available.', $name, $P)); continue; } $stable = $now - ($state['readySince'][$P] ?? $now); if ($stable < (int)$cfg['REBALANCE_DELAY'] * 60) { $dbg(sv_t('{0} waits for {1}: node stable for {2} of {3} minutes.', $name, $P, intdiv($stable, 60), $cfg['REBALANCE_DELAY'])); continue; } if (array_filter($s['cons'], 'sv_is_node_constraint')) { $dbg(sv_t('{0}: fixed node in the constraints – no return.', $name)); continue; } $arch ??= sv_node_archs(); if ($s['archs'] && isset($arch[$P]) && !in_array($arch[$P], $s['archs'], true)) { $dbg(sv_t('{0}: the image is not available for {1} ({2}).', $name, $P, $arch[$P])); continue; } if ($fail && $fail['until'] > $now) { $dbg(sv_t('{0}: last return to {1} failed – next attempt at {2}.', $name, $P, date('H:i', (int)$fail['until']))); continue; } [$rc, $o] = sv_run([$DOCKER, 'service', 'update', '--detach', '--constraint-add', "node.hostname==$P", $name]); if ($rc === 0) { $state['rebalance'][$name] = ['since' => $now, 'node' => $P]; $ev('info', sv_t('{0} is moved back to the preferred node {1}.', $name, $P)); } else { $ev('error', sv_t('{0}: moving back failed: {1}', $name, mb_substr($o, 0, 200)), $o); } } } elseif ($state['rebalance']) { // feature switched off: finish pending returns cleanly foreach ($state['rebalance'] as $name => $ph) { sv_run([$DOCKER, 'service', 'update', '--detach', '--constraint-rm', "node.hostname=={$ph['node']}", $name]); $ev('info', sv_t('{0}: return to {1} stopped – automatic return is switched off.', $name, $ph['node'])); } $state['rebalance'] = []; $state['rebalanceFail'] = []; } /* ---------- Update check at the interval ---------- */ if ($cfg['UPDATE_CHECK'] === 'yes') { $upd = sv_updates_cached(); if ($now - (int)($upd['checked'] ?? 0) >= max(1, (int)$cfg['UPDATE_INTERVAL']) * 3600) { $upd = sv_check_updates(); $avail = array_keys(array_filter($upd['services'], fn($u) => $u['update'])); $ev('info', sv_t('Update check: {0}', $avail ? implode(', ', $avail) : sv_t('everything up to date')), $upd['errors'] ? implode("\n", array_unique($upd['errors'])) : null); // notify only newly found versions $new = array_values(array_filter($avail, fn($n) => ($upd['notified'][$n] ?? '') !== $upd['services'][$n]['remote'])); if ($new && $notifyOn && $cfg['NOTIFY_UPDATES'] === 'yes') { $alerts->send(count($new) === 1 ? sv_t('Update available: {0}', $new[0]) : sv_t('{0} Swarm updates available', count($new)), implode(', ', $new), $cfg['NOTIFY_UPDATES_LEVEL']); } foreach ($new as $n) $upd['notified'][$n] = $upd['services'][$n]['remote']; $upd['notified'] = array_intersect_key($upd['notified'], array_flip($avail)); sv_state_write('updates', $upd); } } // all-clear only for checks that were active in this run $handled = []; if ($notifyOn && $cfg['NOTIFY_NODE'] === 'yes') $handled[] = 'node:'; if ($notifyOn && $cfg['NOTIFY_CRASH'] === 'yes') $handled[] = 'crash:'; if ($notifyOn && $cfg['NOTIFY_PENDING'] === 'yes') $handled[] = 'pending:'; $alerts->finish($handled); if (!$notifyOn) $state['alerts'] = []; $state['lastRun'] = $now; $dbg(sv_t('Watchdog run: {0} nodes, {1} services, {2} s.', count($nodes), count($services), round(microtime(true) - $t0, 1))); // events (return, update check …) for the status display $state['events'] ??= []; foreach ($log as $l) $state['events'][] = ['t' => $now, 'text' => $l]; $state['events'] = array_slice($state['events'], -20); sv_state_write('monitor', $state); return array_merge($log, array_map(fn($m) => "Gemeldet: $m", $alerts->sent)); } /** Hostname → Architektur (amd64/arm64) */ function sv_node_archs(): array { global $DOCKER; [$rc, $out] = sv_run([$DOCKER, 'node', 'ls', '-q']); $ids = array_filter(explode("\n", $rc === 0 ? $out : '')); if (!$ids) return []; [$rc, $out] = sv_run(array_merge([$DOCKER, 'node', 'inspect'], array_values($ids))); $map = ['x86_64' => 'amd64', 'aarch64' => 'arm64', 'armv7l' => 'arm']; $res = []; foreach ((json_decode($rc === 0 ? $out : '[]', true) ?: []) as $n) { $a = $n['Description']['Platform']['Architecture'] ?? ''; $res[$n['Description']['Hostname'] ?? ''] = $map[$a] ?? $a; } return $res; } ]]> getRemoteVersionV2($ref); return is_string($d) && str_starts_with($d, 'sha256:') ? $d : null; } catch (Throwable $e) { return null; } } /** All services with their full spec */ function sv_services_inspect(): array { global $DOCKER; [$rc, $ids] = sv_run([$DOCKER, 'service', 'ls', '-q']); $ids = array_filter(explode("\n", $rc === 0 ? $ids : '')); if (!$ids) return []; [$rc, $out] = sv_run(array_merge([$DOCKER, 'service', 'inspect'], array_values($ids)), null, [], 30); $d = $rc === 0 ? json_decode($out, true) : null; return is_array($d) ? $d : []; } /** * Checks all Swarm services for new image versions and stores the result. * @return array ['checked' => ts, 'services' => [name => [...]], 'errors' => [...]] */ function sv_check_updates(): array { $prev = sv_state_read('updates'); $res = ['checked' => sv_now(), 'services' => [], 'errors' => [], 'notified' => $prev['notified'] ?? []]; $cache = []; foreach (sv_services_inspect() as $s) { $name = $s['Spec']['Name'] ?? ''; if ($name === '' || !empty($s['Spec']['Labels']['swarm-view.agent']) || !empty($s['Spec']['Labels']['swarm-view.cleanup'])) continue; [$ref, $cur] = sv_image_parts($s['Spec']['TaskTemplate']['ContainerSpec']['Image'] ?? ''); if ($cur === '') { // without a digest (e.g. a locally built image) it cannot be checked $res['services'][$name] = ['ref' => $ref, 'current' => '', 'remote' => '', 'update' => false, 'note' => 'kein Digest (lokales Image?)']; continue; } if (!array_key_exists($ref, $cache)) $cache[$ref] = sv_remote_digest($ref); $remote = $cache[$ref]; if ($remote === null) $res['errors'][] = "$ref: " . sv_t('registry not reachable or image unknown'); $res['services'][$name] = [ 'ref' => $ref, 'current' => $cur, 'remote' => (string)$remote, 'update' => $remote !== null && $remote !== $cur, ]; } sv_state_write('updates', $res); return $res; } /** Result of the last check (for api.php) */ function sv_updates_cached(): array { return sv_state_read('updates'); } ]]> Object.assign({ remoteRows: 'always', hostColumn: true, refresh: 15 }, (SV.data && SV.data.config) || {}); /* ---------- Translation ---------- * Source language is English. The page injects window.SwarmViewLang (English → target language) * when Unraid (or the plugin setting) uses another language. Placeholders: {0}, {1}, … */ const DICT = window.SwarmViewLang || {}; const LANG = window.SwarmViewLangCode || 'en'; function t(s, ...args) { let r = Object.prototype.hasOwnProperty.call(DICT, s) ? DICT[s] : s; args.forEach((v, i) => { r = r.split(`{${i}}`).join(v); }); return r; } /** Singular/plural: tn(n, '{0} update', '{0} updates') */ const tn = (n, one, many) => t(n === 1 ? one : many, n); /* ---------- Helpers ---------- */ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const isAdvanced = () => { const $t = $('input.advancedview'); if ($t.length) return $t.is(':checked'); return /(?:^|;\s*)docker_listview_mode=advanced/.test(document.cookie); }; const applyViewMode = () => $('body').toggleClass('sv-advanced', isAdvanced()); /** * Expanded/collapsed per stack: { name: true|false }. Applies to both views. * Without a stored state: advanced view = expanded, basic view = collapsed. */ const openState = () => { try { const v = JSON.parse(sessionStorage.getItem(OPEN_KEY) || '{}'); if (Array.isArray(v)) return Object.fromEntries(v.map((n) => [n, true])); // old format return v && typeof v === 'object' ? v : {}; } catch (e) { return {}; } }; const isOpen = (name) => { const v = openState()[name]; return v === undefined ? isAdvanced() : !!v; }; const setOpen = (name, open) => { const st = openState(); st[name] = !!open; try { sessionStorage.setItem(OPEN_KEY, JSON.stringify(st)); } catch (e) { /* ignore */ } }; // Node badges: server icon = local, arrow = on another node; the text is only the node name const localBadge = (host, extra) => `${esc(host)}${extra || ''}`; const remoteBadge = (host, extra) => `${esc(host)}${extra || ''}`; function placeBadge(t_) { const tip = esc([t_.current, t_.error].filter(Boolean).join(' – ')); if (!t_.node) return `${esc(t('not placed'))}`; return `${t_.local ? localBadge(t_.node) : remoteBadge(t_.node)}`; } /** Groups tasks per node: "Tower ×2", "pi ×1" */ function aggregateBadges(tasks) { const per = new Map(); for (const tk of tasks) { const k = tk.node || ''; const e = per.get(k) || { n: 0, local: tk.local }; e.n++; per.set(k, e); } let out = ''; for (const [node, e] of per) { const cnt = e.n > 1 ? ` ×${e.n}` : ''; if (!node) out += `${esc(t('not placed'))}${cnt}`; else if (e.local) out += localBadge(node, cnt); else out += remoteBadge(node, cnt); } return out || '–'; } function replicaSum(services) { let run = 0, want = 0; for (const sv of services) { const m = String(sv.replicas || '').match(/^(\d+)\/(\d+)/); if (m) { run += +m[1]; want += +m[2]; } } return { run, want }; } // Status: all running = green · some = orange · none = red · 0 replicas on purpose = grey const replicaClass = (run, want) => (want === 0 ? 'sv-dim' : run === want ? 'sv-ok' : run === 0 ? 'sv-bad' : 'sv-warn'); const statusIcon = (run, want) => want === 0 ? `` : run === want ? '' : run === 0 ? '' : ''; /* ---------- Node selection ---------- */ const ARCH = { x86_64: 'amd64', amd64: 'amd64', aarch64: 'arm64', arm64: 'arm64', armv7l: 'arm', armhf: 'arm' }; function findService(fullName) { if (!SV.data) return null; for (const st of SV.data.stacks) for (const sv of st.services) if (sv.name === fullName) return sv; return null; } /** * Can the service run on node n? → { ok, note } * - architecture: platforms from the registry (empty = unknown = ok) * - local image (no registry digest): only nodes it currently runs on – the image surely exists there * - node ready and active (unless ignoreState) */ function nodeCheck(sv, n, ignoreState = false) { const arch = ARCH[n.arch] || n.arch; if ((sv.platforms || []).length && !sv.platforms.includes(arch)) return { ok: false, note: t('no {0} image', arch) }; if (sv.localImage) { const where = new Set((sv.tasks || []).filter((tk) => tk.node && /^running/i.test(tk.current)).map((tk) => tk.node)); if (where.size && !where.has(n.hostname)) return { ok: false, note: t('local image') }; } if (!ignoreState && (n.state !== 'ready' || n.availability !== 'active')) return { ok: false, note: n.state !== 'ready' ? t('unreachable') : t('maintenance') }; return { ok: true, note: '' }; } /** Current placement as select value: '' | 'fixed:N' | 'prefer:N' */ const placeValue = (sv) => (sv.placeNode && !sv.rebalancing ? `fixed:${sv.placeNode}` : sv.prefer ? `prefer:${sv.prefer}` : ''); /** * ` + `` + `${pref}` + `${fixed}`; } $(document).on('click', '.sv-place', (e) => e.stopPropagation()); /** Change the placement of a service (value: '' | 'fixed:N' | 'prefer:N') – with confirmation */ function placeService(svc, value) { const sv = findService(svc) || {}; const short = sv.short || svc; const [mode, node] = value ? String(value).split(':') : ['', '']; const keep = t('Applies until the next Stack Up – then docker-stack.yml counts again.'); const c = cfg(); let title, text; if (mode === 'prefer') { title = t('Prefer "{0}" on {1}?', short, node); text = t('Runs on {0} while the node is available. If it goes down, Swarm starts the service on another node; once {0} has been stable for {1} minutes, it returns automatically.', node, c.rebalanceDelay || 5) + ` ${keep} ` + t('Permanently: in docker-stack.yml under deploy: labels: swarm-view.prefer: {0}', node) + (c.rebalance ? '' : `\n\n${t('The automatic return will be switched on in the settings for this.')}`); } else if (mode === 'fixed') { title = t('Pin "{0}" to {1}?', short, node); text = `${t('The service runs only on {0}. If the node is down, it does not start.', node)} ${keep}`; } else { title = t('Place "{0}" automatically?', short); text = `${t('Swarm decides again where the service runs (may restart).')} ${keep}`; } confirmBox(title, text, () => { SV.busy = true; $('.sv-place').prop('disabled', true); post({ action: 'place', service: svc, mode, node: node || '' }) .done((r) => showResult(t('Placement: {0}', short), r)) .fail((x) => showResult(t('Placement: {0}', short), failResult(x))) .always(() => { SV.busy = false; SV.load(); setTimeout(SV.load, 3000); setTimeout(SV.load, 8000); }); }); } $(document).on('change', '.sv-place', function () { const $sel = $(this); const cur = String($sel.data('current') || ''); placeService(String($sel.data('service')), $sel.val()); // restore the old value if cancelled (the next render sets it anyway) setTimeout(() => { if (!SV.busy) $sel.val(cur); }, 0); }); /* ---------- Actions ---------- */ const ACTIONS = '/plugins/swarm-view/include/actions.php'; // Unraid's $.ajaxPrefilter adds the CSRF token to POSTs automatically const post = (d) => $.ajax({ url: ACTIONS, type: 'POST', data: d, dataType: 'json', timeout: 310000 }); const failResult = (x) => ({ ok: false, error: t('Request failed ({0})', x.status || t('timeout')), log: x.responseText || '' }); function showResult(title, r) { const text = [r.error, r.log].filter(Boolean).join('\n\n') || (r.ok ? 'OK' : t('Error')); if (typeof swal === 'function') { setTimeout(() => swal({ title, text: `
${esc(text)}
`, html: true, type: r.ok ? 'success' : 'error' }), 150); } else { alert(`${title}\n\n${text}`); } } function confirmBox(title, text, cb) { if (typeof swal === 'function') { swal({ title, text, type: 'warning', showCancelButton: true, confirmButtonText: t('Yes'), cancelButtonText: t('Cancel') }, (ok) => { if (ok) cb(); }); } else if (confirm(`${title}\n\n${text}`)) cb(); } /* ---------- Loading ---------- */ // Unraid's loadlist() starts its spinner with a timer (timers.docker). If two loadlist() // calls overlap, one timer is lost and the spinner stays forever. // So: only trigger a reload when no container list is currently loading. const LIST_URL = /DockerContainers\.php/; let reloadWanted = false; let keyAtLastListLoad = null; // which remote containers were in the DOM at the last list load const currentRemoteKey = () => (cfg().remoteRows === 'never' ? '' : SV.remoteTasks().map((r) => r.name).sort().join('|')); // Folder View builds its folders asynchronously after the list arrived. A second list load while it is still building // can leave folders empty (Folder View 2 does not cope with overlapping builds) – so wait for its "done" event. let fvBuilding = false, fvTimer = null, fvHooked = false; function fvDone() { fvBuilding = false; clearTimeout(fvTimer); if (reloadWanted && !SV.listPending) { reloadWanted = false; setTimeout(maybeReloadList, 0); } } function hookFolderViewDone() { if (fvHooked || !folderViewActive()) return; try { folderEvents.addEventListener('docker-post-folders-creation', fvDone); fvHooked = true; } catch (e) { /* not there */ } } $(document).ajaxSend((e, x, o) => { if (!LIST_URL.test(o.url || '')) return; SV.listPending++; hookFolderViewDone(); if (fvHooked) { fvBuilding = true; clearTimeout(fvTimer); fvTimer = setTimeout(fvDone, 10000); // safety net if Folder View never reports back } }); // same task as Unraid's callback → the rows about to be inserted come from exactly this data $(document).ajaxSuccess((e, x, o) => { if (LIST_URL.test(o.url || '')) keyAtLastListLoad = SV.data ? currentRemoteKey() : ''; }); $(document).ajaxComplete((e, x, o) => { if (!LIST_URL.test(o.url || '')) return; SV.listPending = Math.max(0, SV.listPending - 1); // evaluate after Unraid's callback + Folder View (microtasks) setTimeout(() => { if (SV.listPending) return; // safety net: hide an orphaned spinner setTimeout(() => { if (!SV.listPending) $('div.spinner.fixed').hide(); }, 700); if (reloadWanted && !fvBuilding) { reloadWanted = false; maybeReloadList(); } }, 50); }); function maybeReloadList() { if (!folderViewActive() || typeof window.loadlist !== 'function' || !SV.data) return; if (keyAtLastListLoad === null || keyAtLastListLoad === currentRemoteKey()) return; if (SV.listPending || fvBuilding) { reloadWanted = true; return; } window.loadlist(); } function render() { if (!SV.data) return; SV.renderMsg(); SV.renderNodes(); SV.renderStacks(); SV.decorateDockerTable(); // new/vanished remote containers → Folder View has to sort again maybeReloadList(); } function folderViewActive() { try { return typeof folderEvents !== 'undefined'; } catch (e) { return false; } } let refreshTimer = null; let refreshEvery = 0; function scheduleRefresh() { const sec = Math.max(5, +cfg().refresh || REFRESH_MS / 1000); if (sec === refreshEvery && refreshTimer) return; refreshEvery = sec; clearInterval(refreshTimer); refreshTimer = setInterval(() => { if (!document.hidden) SV.load(); }, sec * 1000); } function load() { $.ajax({ url: API, dataType: 'json', cache: false, timeout: 20000 }) .done((d) => { SV.data = d; render(); if (refreshTimer) scheduleRefresh(); }) .fail((x, status) => { $('#sv-msg').attr('class', 'sv-msg error') .text(t('Swarm API not reachable ({0}).', x.status || status)).show(); }); } /** Called at the end of containers.js once all parts are loaded */ function start() { // fetch data as early as possible so remote containers are there on the first list load SV.load(); // follow Unraid's "Basic/Advanced View" switch – bound right away (not on ready) so our columns are // shown/hidden before Folder View 3 measures the table in its own (later bound) change handler $(document).on('change', 'input.advancedview', applyViewMode); $(function () { applyViewMode(); SV.decorateDockerTable(); scheduleRefresh(); }); } Object.assign(SV, { t, tn, LANG, esc, cfg, isAdvanced, applyViewMode, isOpen, setOpen, localBadge, remoteBadge, placeBadge, aggregateBadges, replicaSum, replicaClass, statusIcon, ARCH, findService, nodeCheck, placeSelect, placeService, ACTIONS, post, failResult, showResult, confirmBox, load, start, }); })(jQuery); ]]>
`${n} ${n === 1 ? one : dative ? manyDat : many}`; if (sec < 1) return dative ? 'weniger als einer Sekunde' : 'weniger als 1 Sekunde'; if (sec < 60) return pl(Math.floor(sec), 'Sekunde', 'Sekunden', 'Sekunden'); const min = Math.floor(sec / 60); if (min === 1) return dative ? 'etwa einer Minute' : 'etwa 1 Minute'; if (min < 60) return pl(min, 'Minute', 'Minuten', 'Minuten'); const h = Math.round(sec / 3600); if (h === 1) return dative ? 'etwa einer Stunde' : 'etwa 1 Stunde'; if (h < 48) return pl(h, 'Stunde', 'Stunden', 'Stunden'); if (h < 24 * 7 * 2) return pl(Math.floor(h / 24), 'Tag', 'Tage', 'Tagen'); if (h < 24 * 30 * 2) return pl(Math.floor(h / 24 / 7), 'Woche', 'Wochen', 'Wochen'); if (h < 24 * 365 * 2) return pl(Math.floor(h / 24 / 30), 'Monat', 'Monate', 'Monaten'); return pl(Math.floor(h / 24 / 365), 'Jahr', 'Jahre', 'Jahren'); } const pl = (n, unit) => `${n} ${unit}${n === 1 ? '' : 's'}`; if (sec < 1) return 'less than a second'; if (sec < 60) return pl(Math.floor(sec), 'second'); const min = Math.floor(sec / 60); if (min === 1) return 'about a minute'; if (min < 60) return pl(min, 'minute'); const h = Math.round(sec / 3600); if (h === 1) return 'about an hour'; if (h < 48) return pl(h, 'hour'); if (h < 24 * 7 * 2) return pl(Math.floor(h / 24), 'day'); if (h < 24 * 30 * 2) return pl(Math.floor(h / 24 / 7), 'week'); if (h < 24 * 365 * 2) return pl(Math.floor(h / 24 / 30), 'month'); return pl(Math.floor(h / 24 / 365), 'year'); } const since = (iso) => { const ms = Date.parse(iso || ''); return isNaN(ms) ? null : (Date.now() - ms) / 1000; }; const timesHtml = (r) => { const up = since(r.since), cr = since(r.created); const state = String(r.current).split(' ')[0] || t('Stopped'); const first = r.running ? (up != null ? t('Uptime: {0}', duration(up)) : t('running')) : (up != null ? t('{0}: {1} ago', state, duration(up, true)) : state); return `
${esc(first)}${cr != null ? `
${esc(t('Created {0} ago', duration(cr, true)))}
` : ''}
`; }; /* ---------- Display name (label swarm-view.name) ---------- * Swarm names containers itself (service.slot.task-id) and ignores container_name. * The real name stays as text in the DOM – Folder View, autostart order and Unraid's menus keep * working with it. CSS (::before) shows only the display name. */ function aliasFor(sv, slot) { if (!sv || !sv.alias) return ''; return (sv.desired || 0) > 1 && slot ? `${sv.alias}.${slot}` : sv.alias; } function setAlias(el, alias, realName) { if (!el) return; if (!alias) { if (el.hasAttribute('data-sv-alias')) { el.removeAttribute('data-sv-alias'); el.removeAttribute('title'); el.style.removeProperty('--sv-fs'); } return; } if (el.getAttribute('data-sv-alias') === alias) return; if (!el.hasAttribute('data-sv-alias')) el.style.setProperty('--sv-fs', getComputedStyle(el).fontSize || ''); el.setAttribute('data-sv-alias', alias); el.setAttribute('title', `Container: ${realName}`); } /** real name → display name, for Folder View's folder previews */ function aliasMap() { const m = new Map(); for (const r of Object.values(remoteIndex)) if (r.alias) m.set(r.name, r.alias); for (const [name, c] of Object.entries((SV.data && SV.data.containers) || {})) { if (!c.swarmService) continue; const a = aliasFor(findService(c.swarmService), (name.slice(c.swarmService.length + 1).split('.')[0]) || ''); if (a) m.set(name, a); } return m; } const SWARM_STOP_HINT = t('Swarm container: stopping it in Unraid does not last – Swarm starts it again. Use "Stack Down" in the Swarm section to stop it.'); const shortSvc = (svc, stack) => (stack && svc.startsWith(stack + '_') ? svc.slice(stack.length + 1) : svc); function hostCell(name) { if (!SV.data) return '…'; const c = (SV.data.containers || {})[name] || {}; if (!c.swarmService) return `${esc(t('local'))}`; let html = localBadge(SV.data.host); html += `
Swarm: ${esc(c.swarmStack || '–')} / ${esc(shortSvc(c.swarmService, c.swarmStack))}
`; const sel = placeSelect(findService(c.swarmService)); if (sel) html += `
${sel}
`; return html; } /** WebUI URL like Unraid: [IP] → Unraid IP (routing mesh), [PORT:x] → published port */ function webUiFor(sv) { const host = location.hostname; const pubFor = (target) => { const p = (sv.portList || []).find((x) => +x.target === +target); return p ? p.published : target; }; const tpl = (sv.labels || {})['net.unraid.docker.webui']; if (tpl) return tpl.replace(/\[IP\]/g, host).replace(/\[PORT:(\d+)\]/g, (m, p) => pubFor(p)); const first = (sv.portList || []).find((p) => p.published && p.proto === 'tcp'); return first ? `http://${host}:${first.published}` : ''; } /** All Swarm tasks NOT running on this host – with a stable name stack_service.slot */ function remoteTasks() { if (!SV.data || !SV.data.swarm.active) return []; const managed = new Set(SV.data.managed || []); const out = []; for (const st of SV.data.stacks) { for (const sv of st.services) { for (const tk of sv.tasks) { if (!tk.node || tk.local || !tk.id) continue; const image = String(sv.image || ''); out.push({ elId: `sv-${tk.id.slice(0, 12)}`, sid: `sv${tk.id.slice(0, 10)}`, // "short id" like Unraid's: CPU/RAM spans and Folder View use it name: `${sv.name}.${tk.slot}`, taskId: tk.id, service: sv.name, stack: st.name === '(no stack)' ? '' : st.name, managed: managed.has(st.name), node: tk.node, running: /^running/i.test(tk.current), current: tk.current, image, tag: image.includes(':') ? image.split(':').pop() : 'latest', icon: (sv.labels || {})['net.unraid.docker.icon'] || QUESTION_ICON, labels: sv.labels || {}, ports: sv.portList || [], mounts: (sv.mounts || []).filter((m) => m.type === 'bind'), webui: webUiFor(sv), placeHtml: placeSelect(sv), update: sv.update, canRollback: sv.canRollback, rollbackTo: sv.rollbackTo || '', stats: ((SV.data.stats || {}).tasks || {})[tk.id] || null, short: sv.short || sv.name, alias: aliasFor(sv, tk.slot), created: tk.created || '', since: tk.since || '', containerId: tk.containerId || '', networks: tk.networks || [], }); } } } return out; } /** Row with the same markup as Unraid's DockerContainers.php (so Folder View & co. understand it) */ function remoteRowCells(r) { const host = location.hostname; const dash = '–'; const ports = r.ports.map((p) => `${p.target}:${String(p.proto).toUpperCase()}`).join('
') || dash; const lan = r.ports.filter((p) => p.published).map((p) => `${esc(host)}:${p.published}`).join('
') || dash; const vols = r.mounts.map((m) => `${esc(m.target)}${esc(m.source)}`).join('
') || dash; const nets = r.networks.map((n) => esc(n.name)).join('
') || dash; const ips = r.networks.map((n) => esc(n.addr)).filter(Boolean).join('
') || dash; const upd = updateLine(r.update); const by = r.image.replace(/:[^:/]*$/, ''); return ` ${esc(r.name)}
${r.running ? esc(t('started')) : esc(r.current.split(' ')[0] || '?')}
Swarm: ${esc(r.stack || '–')} / ${esc(r.short)}
${esc(r.containerId ? t('Container ID: {0}', r.containerId) : t('Task ID: {0}', r.taskId.slice(0, 12)))}
${esc(t('By: {0}', by))}
${upd}
${esc(r.tag)}
${nets} ${ips} ${ports} ${lan} ${vols} …

… ${cfg().hostColumn ? `${remoteBadge(r.node)}${r.placeHtml ? `
${r.placeHtml}
` : ''}` : ''} Swarm ${timesHtml(r)}`; } /** Version column: update status (only when the update check is on) */ function updateLine(u) { if (u) return ` ${esc(t('Update available'))}`; if (u === false) return ` ${esc(t('up-to-date'))}`; return ''; } const rowSig = (r, mode) => JSON.stringify(Object.assign({}, r, { stats: null })) + mode + cfg().hostColumn; /* ---------- CPU/RAM: remote containers like Unraid's rows, folder totals for Folder View ---------- */ const UNITS = { B: 1, KiB: 2 ** 10, MiB: 2 ** 20, GiB: 2 ** 30, TiB: 2 ** 40, kB: 1e3, KB: 1e3, MB: 1e6, GB: 1e9, TB: 1e12 }; const memToB = (m) => { const x = String(m || '').trim().match(/^([\d.,]+)\s*([A-Za-z]*)$/); return x ? parseFloat(x[1].replace(',', '.')) * (UNITS[x[2] || 'B'] || 1) : 0; }; const bToMem = (b) => { const u = ['B', 'KiB', 'MiB', 'GiB', 'TiB']; let i = 0; while (b >= 1024 && i < u.length - 1) { b /= 1024; i++; } return b ? `${b.toFixed(2)} ${u[i]}` : '0 B'; }; const pct = (v) => `${(Math.round(v * 100) / 100).toFixed(2)}%`; const selfNode = () => (SV.data.nodes || []).find((n) => n.self) || {}; const nodeCpus = (host) => ((SV.data.nodes || []).find((n) => n.hostname === host) || {}).cpus || 0; /** Values of a remote container: cpu = % of its node's CPUs (like Unraid), cores = cores in use */ function remoteLoad(r) { const st = r.stats; if (!st) return null; const ncpu = st.ncpu || nodeCpus(r.node) || 1; const raw = parseFloat(String(st.cpu).replace(',', '.')) || 0; // docker stats: 100 % = 1 core const [used, lim] = String(st.mem || '').split('/').map((x) => x.trim()); const usedB = memToB(used); // "0B / 0B": Docker on that node measures no memory (memory cgroup off, typical on a Raspberry Pi) const noMem = !memToB(lim); const limB = noMem ? 0 : memToB(lim); return { node: r.node, ncpu, cores: raw / 100, cpu: Math.min(raw / ncpu, 100), usedB, limB, memText: st.mem || '', noMem }; } function updateRemoteLoads() { const enabled = (SV.data.stats || {}).enabled; for (const r of Object.values(remoteIndex)) { $(`tr.sv-remote-row[data-sv-name="${r.name}"] > td.sv-times`).html(timesHtml(r)); const l = remoteLoad(r); const $cpu = $(`span.cpu-${r.sid}`), $mem = $(`span.mem-${r.sid}`), $bar = $(`[id="cpu-${r.sid}"]`); if (!l) { $cpu.text(enabled ? '…' : '–'); $mem.text(enabled ? '…' : '–').attr('title', enabled ? t('No values from the agent yet') : t('The CPU/RAM agent is off in the settings')); $bar.css('width', 0); continue; } $cpu.text(pct(l.cpu)); $bar.css('width', pct(l.cpu)); if (l.noMem) $mem.text(t('RAM not measurable')).attr('title', t('Docker on {0} measures no memory: cgroup_enable=memory is missing in /boot/firmware/cmdline.txt', r.node)); else $mem.text(l.memText).attr('title', r.stats.memApprox ? t("Estimated from the processes' memory (RSS) – Docker on {0} measures no container memory (memory cgroup off)", r.node) : t('CPU value relative to {0} cores of {1}', l.ncpu, r.node)); } } /** * Folder View computes a folder's CPU/RAM only from Unraid's local values. When it writes its sum, * we remember the local value and – depending on the setting – write the sum over all nodes on top. * The split per node goes into the tooltip. */ function folderParts(id, $row) { const remote = $(`tr.sv-remote-row.folder-${id}-element`).get().map((tr) => { const r = Object.values(remoteIndex).find((x) => x.name === tr.getAttribute('data-sv-name')); return r ? remoteLoad(r) : null; }).filter(Boolean); const hasLocal = $(`.folder-${id}-element`).not('.sv-remote-row').length > 0; const $c = $row.find(`span.cpu-folder-${id}`).first(), $m = $row.find(`span.mem-folder-${id}`).first(); const local = { cpu: parseFloat(String($c.attr('data-sv-local') ?? $c.text()).replace(',', '.')) || 0, mem: String($m.attr('data-sv-local') ?? $m.text()).split('/').map((x) => memToB(x.trim())), }; return { remote, hasLocal, local, $c, $m }; } function updateFolder(row) { const m = String(row.className).match(/(?:^|\s)folder-id-(\S+)/); if (!m || !SV.data) return; const id = m[1]; const $row = $(row); const { remote, hasLocal, local, $c, $m } = folderParts(id, $row); const $td = $row.children('td.folder-advanced'); const anyRemote = $(`tr.sv-remote-row.folder-${id}-element`).length > 0; if (!anyRemote) { $td.removeAttr('title'); return; } // sum up per node const me = selfNode(); const per = new Map(); if (hasLocal) per.set(me.hostname || t('local'), { cores: local.cpu / 100 * (me.cpus || 1), ncpu: me.cpus || 1, used: local.mem[0] || 0, lim: local.mem[1] || 0 }); for (const l of remote) { const e = per.get(l.node) || { cores: 0, ncpu: l.ncpu, used: 0, lim: 0, noMem: false }; e.cores += l.cores; e.used += l.usedB; e.lim = Math.max(e.lim, l.limB); e.noMem = e.noMem || l.noMem; per.set(l.node, e); } const lines = [...per].map(([n, e]) => `${n}: ${t('{0} of {1} cores', pct(e.cores / e.ncpu * 100), e.ncpu)} · ` + (e.noMem ? t('RAM not measurable (cgroup_enable=memory missing)') : `${bToMem(e.used)}${e.lim ? ' / ' + bToMem(e.lim) : ''}`)); const missing = $(`tr.sv-remote-row.folder-${id}-element`).length - remote.length; if (missing > 0) lines.push(`(${tn(missing, '{0} container without values', '{0} containers without values')})`); if (cfg().folderLoad === 'local') { // back to Folder View's values in case we wrote the sum before for (const $s of [$c, $m]) if ($s.attr('data-sv-written') && $s.text() === $s.attr('data-sv-written')) $s.text($s.attr('data-sv-local')); $td.attr('title', `${t('Local only. With other nodes:')}\n${lines.join('\n')}`); return; } let cores = 0, ncpu = 0, used = 0, lim = 0; for (const e of per.values()) { cores += e.cores; ncpu += e.ncpu; if (!e.noMem) { used += e.used; lim += e.lim; } } const cpu = ncpu ? Math.min(cores / ncpu * 100, 100) : 0; const cpuText = pct(cpu), memText = `${bToMem(used)} / ${bToMem(lim)}`; if ($c.attr('data-sv-local') === undefined) $c.attr('data-sv-local', $c.text()); if ($m.attr('data-sv-local') === undefined) $m.attr('data-sv-local', $m.text()); $c.attr('data-sv-written', cpuText).text(cpuText); $m.attr('data-sv-written', memText).text(memText); $row.find(`[id="cpu-folder-${id}"]`).css('width', cpuText); $td.attr('title', `${tn(per.size, 'Total over {0} node', 'Total over {0} nodes')} (${t('{0} cores', ncpu)}):\n${lines.join('\n')}`); } function watchFolder(row) { if (row.__svLoadObs) return; const obs = new MutationObserver((muts) => { for (const mu of muts) { const span = mu.target.nodeType === 1 ? mu.target : mu.target.parentElement; if (!span || !/(?:^|\s)(cpu|mem)-folder-/.test(span.className)) continue; // not our own write → Folder View delivered new local values if (span.textContent !== span.getAttribute('data-sv-written')) span.setAttribute('data-sv-local', span.textContent); } if (muts.some((mu) => { const sp = mu.target.nodeType === 1 ? mu.target : mu.target.parentElement; return sp && sp.textContent !== sp.getAttribute('data-sv-written'); })) updateFolder(row); }); const td = $(row).children('td.folder-advanced').get(0); if (!td) return; obs.observe(td, { childList: true, characterData: true, subtree: true }); row.__svLoadObs = obs; } function updateLoads() { if (!SV.data) return; updateRemoteLoads(); $('#docker_list > tr.folder').each(function () { watchFolder(this); updateFolder(this); }); } /** Keep remote containers in the DOM up to date – rows are kept (even when Folder View moved them into folders) */ function syncRemoteRows() { const list = document.getElementById('docker_list'); if (!list) return; const mode = cfg().remoteRows; const tasks = mode === 'never' ? [] : remoteTasks(); remoteIndex = Object.fromEntries(tasks.map((r) => [r.elId, r])); const want = new Map(tasks.map((r) => [r.name, r])); $(list).find('tr.sv-remote-row').each(function () { const name = this.getAttribute('data-sv-name'); const r = want.get(name); if (!r) { $(this).remove(); return; } const sig = rowSig(r, mode); $(this).toggleClass('sv-adv', mode === 'advanced'); if (this.getAttribute('data-sv-sig') !== sig) { this.innerHTML = remoteRowCells(r); this.setAttribute('data-sv-sig', sig); } want.delete(name); }); for (const r of want.values()) { const tr = document.createElement('tr'); tr.className = 'sortable sv-remote-row' + (mode === 'advanced' ? ' sv-adv' : ''); tr.setAttribute('data-sv-name', r.name); tr.setAttribute('data-sv-sig', rowSig(r, mode)); tr.innerHTML = remoteRowCells(r); list.appendChild(tr); } // show the mover only when Unraid's sorting is unlocked $(list).find('tr.sv-remote-row i.mover').toggle($.cookie && $.cookie('lockbutton') != null); } /** * Adapt a Folder View folder row to the host column. * Folder View sets the width of its wide cell to "number of columns − 5", or fixed to 6 with the folder * option "update column". Both assume 10 columns. Instead of a fixed number, the folder's CPU cell is * moved to the position of the "CPU & Memory load" column and an empty host cell is added after it. */ function fixFolderRow(tr, $tbl) { const ths = $tbl.find('thead tr').first().children('th').get(); const loadIdx = ths.findIndex((th) => th.classList.contains('load')); const cpu = $(tr).children('td.folder-advanced').get(0); if (loadIdx < 0 || !cpu) return; let pos = 0; for (const td of $(tr).children('td').get()) { if (td === cpu) break; pos += +td.getAttribute('colspan') || 1; } const diff = loadIdx - pos; if (diff) { const wide = $(tr).children('td').filter((i, td) => $(td).children('div.folder-storage').length).get(0) || $(cpu).prevAll('td[colspan]').get(0); if (wide) wide.setAttribute('colspan', Math.max(1, (+wide.getAttribute('colspan') || 1) + diff)); } if (!$(cpu).next('td.sv-hostcol').length) $(cpu).after(''); } /** Local Swarm containers in Unraid's list: update status, start/stop hint, display name */ /* Unraid renders the name of containers without template as plain text. Folder View 2 finds rows only via * ".appname a" and therefore never sorts Swarm containers into folders – give their name the same as template * containers (text stays identical, so Unraid, Folder View 3 and the autostart order are unaffected). */ const SWARM_TASK_NAME = /^\S+\.[a-z0-9]+\.[a-z0-9]{25}$/; function linkLocalSwarmName($tr) { const $an = $tr.children('td.ct-name').find('.appname').first(); if (!$an.length || $an.children('a').length) return; const name = $an.text().trim(); if (SWARM_TASK_NAME.test(name)) $an.empty().append($('').text(name)); } function localSwarmRow($tr) { const name = $tr.find('.appname').first().text().trim(); const c = SV.data && (SV.data.containers || {})[name]; if (!c || !c.swarmService) return; const sv = findService(c.swarmService) || {}; const $u = $tr.children('td.updatecolumn'); const html = updateLine(sv.update); let $line = $u.children('div.sv-updline'); if (!$line.length) $line = $('
').prependTo($u); if ($line.html() !== html) $line.html(html); $tr.find('td.ct-name span.state').first().attr('title', SWARM_STOP_HINT); setAlias($tr.find('td.ct-name .appname').get(0), aliasFor(sv, (name.slice(c.swarmService.length + 1).split('.')[0]) || ''), name); } /* ---------- Hide orphan images (Unraid: tr.advanced with addDockerImageContext) ---------- */ const ORPHAN_KEY = 'swarmview_orphans_show'; const normImg = (s) => String(s || '').trim().replace(/@sha256:[0-9a-f]+$/i, '').replace(/^docker\.io\//, '').replace(/^library\//, '') .replace(/^([^/:]+)$/, '$1:latest').replace(/^([^:]*\/[^/:]+)$/, '$1:latest'); function hideOrphans($tbl) { // without Swarm data (API error, Swarm off, worker node) behave like Unraid and hide nothing const swarmReady = !!(SV.data && SV.data.swarm && SV.data.swarm.active && SV.data.swarm.manager); const mode = swarmReady ? (cfg().orphans || 'swarm') : 'show'; const $rows = $('#docker_list > tr').filter(function () { return $(this).find('span[onclick^="addDockerImageContext"]').length > 0; }); $('#docker_list > tr.sv-orphan-sum').remove(); $rows.removeClass('sv-orphan-hidden'); if (mode === 'show' || !$rows.length) return; const swarmImgs = new Set(); for (const st of (SV.data && SV.data.stacks) || []) for (const sv of st.services) swarmImgs.add(normImg(sv.image)); let reserve = 0, old = 0, other = 0; const hide = $rows.filter(function () { const m = String($(this).find('span[onclick^="addDockerImageContext"]').attr('onclick')).match(/addDockerImageContext\('[^']*','([^']*)'\)/); // ":" (older Docker versions) counts as an image without name, like an empty tag list const tags = (m ? m[1] : '').split(',').map((x) => x.trim()).filter((x) => x && !/^(:)?$/.test(x)); if (!tags.length) { old++; return true; } if (tags.some((x) => swarmImgs.has(normImg(x)))) { reserve++; return true; } if (mode === 'hide') { other++; return true; } return false; }); if (!hide.length) return; let show = false; try { show = sessionStorage.getItem(ORPHAN_KEY) === '1'; } catch (e) { /* ignore */ } if (!show) hide.addClass('sv-orphan-hidden'); const parts = [reserve && tn(reserve, '{0} reserve for Swarm services', '{0} reserve for Swarm services'), old && tn(old, '{0} old version without name', '{0} old versions without name'), other && t('{0} other', other)].filter(Boolean); const cols = $tbl.find('thead tr').first().children('th').length || 10; const $sum = $(` ${esc(show ? tn(hide.length, '{0} orphan image shown', '{0} orphan images shown') : tn(hide.length, '{0} orphan image hidden', '{0} orphan images hidden'))} (${esc(parts.join(', '))}) · ${esc(show ? t('hide again') : t('show'))}`); $sum.insertBefore(hide.first()); // Unraid toggles .advanced via jQuery when the view changes – the row follows the view like the image rows $sum.toggle(isAdvancedView()); } const isAdvancedView = () => $('body').hasClass('sv-advanced'); $(document).on('click', '.sv-orphan-toggle, .sv-orphan-sum .sv-dim', function (e) { e.preventDefault(); let show = false; try { show = sessionStorage.getItem(ORPHAN_KEY) === '1'; sessionStorage.setItem(ORPHAN_KEY, show ? '0' : '1'); } catch (er) { /* ignore */ } hideOrphans($('#docker_containers')); }); function decorateDockerTable() { const list = document.getElementById('docker_list'); const $tbl = $('#docker_containers'); if (!list || !$tbl.length) return; if (observer) observer.disconnect(); hookFolderView(); const withHost = cfg().hostColumn; let headerChanged = false; if (!withHost) { // remove the column (if it was active before) if ($tbl.find('thead th.sv-hostcol').length) headerChanged = true; $tbl.find('thead th.sv-hostcol').remove(); $('#docker_list > tr:not(.sv-remote-row)').children('td.sv-hostcol').remove(); } // header: "Host" after "CPU & Memory load" if (withHost && !$tbl.find('thead th.sv-hostcol').length) { const $load = $tbl.find('thead th.load'); const $th = $('Host'); if ($load.length) $load.after($th); else $tbl.find('thead th').eq(7).after($th); headerChanged = true; } // Folder View 3 fixes the column widths from its own measurement and caches them per view – // a column added later would keep a width of ~0. Let it measure again. if (headerChanged && typeof window.fv3ResetWidthSnapshots === 'function' && typeof window.fv3ScheduleWidthFix === 'function') { try { window.fv3ResetWidthSnapshots(); window.fv3ScheduleWidthFix(); } catch (e) { /* Folder View internals changed */ } } $('#docker_list > tr').each(function () { const $tr = $(this); if ($tr.hasClass('sv-remote-row')) return; // our own rows if ($tr.hasClass('folder')) { if (withHost) fixFolderRow(this, $tbl); return; } // Folder View folder if ($tr.hasClass('sortable') && /^swarm-view-(agent|cleanup)\./.test($tr.find('.appname').first().text().trim())) { $tr.addClass('sv-internal-row'); return; } if ($tr.hasClass('sortable')) { linkLocalSwarmName($tr); localSwarmRow($tr); if (!withHost) return; let $td = $tr.children('td.sv-hostcol'); if (!$td.length) { $td = $(''); const $cpu = $tr.children('td.advanced').last(); ($cpu.length ? $cpu : $tr.children('td').eq(7)).after($td); } $td.html(hostCell($tr.find('.appname').first().text().trim())); } else if (withHost && !this.svFixed) { const $c = $tr.children('td[colspan]').last(); if ($c.length) $c.attr('colspan', (+$c.attr('colspan') || 1) + 1); this.svFixed = true; } }); syncRemoteRows(); updateLoads(); hideOrphans($tbl); // font size for display names in our own rows: take it from a normal name const ref = $('#docker_list tr:not(.sv-remote-row) .appname:not([data-sv-alias])').get(0); const fs = ref ? getComputedStyle(ref).fontSize : ''; $('#docker_list tr.sv-remote-row .appname[data-sv-alias]').each(function () { if (!this.style.getPropertyValue('--sv-fs')) this.style.setProperty('--sv-fs', fs || getComputedStyle(this.parentElement).fontSize); }); // rename Folder View's folder previews (cloned names) as well const am = aliasMap(); $('#docker_list .folder-preview span.appname').each(function () { const real = $(this).text().trim(); setAlias(this, am.get(real) || (this.hasAttribute('data-sv-alias') ? '' : null), real); }); if (!observer) observer = new MutationObserver(() => decorateDockerTable()); observer.observe(list, { childList: true }); } /* ---------- Context menu for remote containers (like Unraid's addDockerContainerContext) ---------- */ window.svRemoteContext = function (elId, target) { const r = remoteIndex[elId]; if (!r || typeof context === 'undefined') return; const opts = []; if (r.running && r.webui) { opts.push({ text: 'WebUI', icon: 'fa-globe', action: (e) => { e.preventDefault(); window.open(r.webui, '_blank'); } }); opts.push({ divider: true }); } if (r.update) opts.push({ text: 'Update', icon: 'fa-flash', action: (e) => { e.preventDefault(); serviceAction('svc-update', r.service); } }); if (r.canRollback) opts.push({ text: t('Rollback to {0}', r.rollbackTo || t('previous version')), icon: 'fa-undo', action: (e) => { e.preventDefault(); serviceAction('svc-rollback', r.service); } }); opts.push({ text: t('Restart'), icon: 'fa-refresh', action: (e) => { e.preventDefault(); confirmBox(t('Restart "{0}"?', r.service), t('The service is rolled out again with --force (all replicas).'), () => { post({ action: 'svc-restart', service: r.service }) .done((res) => showResult(t('Restart: {0}', r.service), res)) .fail((x) => showResult(t('Restart: {0}', r.service), failResult(x))) .always(() => { SV.load(); setTimeout(SV.load, 4000); }); }); }, }); const svObj = findService(r.service); if (svObj && svObj.mode !== 'global' && SV.data.nodes.length > 1) { for (const n of SV.data.nodes) { if (n.hostname === r.node || !nodeCheck(svObj, n).ok) continue; opts.push({ text: t('Move to {0} (fixed)', n.hostname), icon: 'fa-exchange', action: (e) => { e.preventDefault(); placeService(svObj.name, `fixed:${n.hostname}`); } }); } } opts.push({ divider: true }); opts.push({ text: 'Logs', icon: 'fa-navicon', action: (e) => { e.preventDefault(); openLogs(r); } }); if (r.managed) { opts.push({ text: t('Edit stack'), icon: 'fa-wrench', action: (e) => { e.preventDefault(); openEditor(r.stack); }, }); } opts.push({ divider: true }); opts.push({ text: t('Runs on: {0}', r.node), icon: 'fa-external-link', action: (e) => e.preventDefault() }); context.settings({ right: false, above: false }); const sel = '#' + (target || elId); context.destroy(sel); context.attach(sel, opts); }; /* ---------- Log window ---------- */ let logTask = null; function ensureLogBox() { if ($('#sv-logbox').length) return; $('body').append(``); $('#sv-logbox-close').on('click', () => { $('#sv-logbox').hide(); logTask = null; }); $('#sv-logbox-refresh').on('click', () => logTask && fetchLogs(logTask)); $('#sv-logbox').on('click', (e) => { if (e.target.id === 'sv-logbox') $('#sv-logbox-close').trigger('click'); }); } function fetchLogs(r) { $('#sv-logbox-text').text(t('Loading logs …')); post({ action: 'logs', task: r.taskId, tail: 500 }) .done((res) => { const $p = $('#sv-logbox-text').text(res.log || res.error || ''); $p.scrollTop($p[0].scrollHeight); }) .fail((x) => $('#sv-logbox-text').text(failResult(x).error)); } function openLogs(r) { ensureLogBox(); logTask = r; $('#sv-logbox-title').text(`${r.name} @ ${r.node}`); // use the theme background (light/dark) const bg = getComputedStyle(document.body).backgroundColor; if (bg && !/rgba\(0, 0, 0, 0\)|transparent/.test(bg)) $('#sv-logbox .sv-logbox-inner').css('background', bg); $('#sv-logbox').show(); fetchLogs(r); } /* ---------- Folder View: add remote containers to its container list ---------- */ function hookFolderView() { let fe; try { fe = folderEvents; } catch (e) { return; } // Folder View (2) not installed if (!fe || fe.__svHooked) return; fe.__svHooked = true; fe.addEventListener('docker-pre-folders-creation', (ev) => { const { order, containersInfo, folders } = ev.detail || {}; if (!Array.isArray(order) || !containersInfo) return; for (const r of Object.values(remoteIndex)) { if (!containersInfo[r.name]) { containersInfo[r.name] = { Id: `swarm-${r.taskId}`, shortId: r.sid, shortImageId: '', Labels: r.labels, Mounts: r.mounts.map((m) => ({ Type: 'bind', Source: m.source, Destination: m.target })), info: { Name: r.name, State: { Running: r.running, Paused: false, Autostart: false, Updated: true, manager: 'swarm', WebUi: r.webui, TSWebUi: '' }, Config: { Image: r.image }, Ports: r.ports.map((p) => ({ PrivatePort: p.target, PublicPort: p.published, Type: p.proto })), registry: '', Support: '', Project: '', ReadMe: '', DonateLink: '', Shell: 'sh', template: null, }, }; } if (!order.includes(r.name)) order.push(r.name); } // display names for folders: a folder's regex or container list may also mean the display name. // For that the real name is added to the folder's list in memory only (never saved). const am = aliasMap(); if (folders && am.size) { for (const f of Object.values(folders)) { if (!f) continue; if (!Array.isArray(f.containers)) f.containers = []; let re = null; try { if (f.regex && String(f.regex).trim()) re = new RegExp(f.regex); } catch (e) { re = null; } for (const [real, alias] of am) { if (!order.includes(real) || f.containers.includes(real)) continue; if ((re && !re.test(real) && re.test(alias)) || f.containers.includes(alias)) f.containers.push(real); } } } }); } Object.assign(SV, { decorateDockerTable, remoteTasks, hookFolderView, openLogs }); SV.start(); })(jQuery); ]]>
')).show(); } else if (!s.active) { $m.attr('class', 'sv-msg info') .html(esc(t('Swarm is not active on this host. Initialise it with')) + ' docker swarm init --advertise-addr <Unraid-IP>.') .show(); } else if (!s.manager) { $m.attr('class', 'sv-msg info').text(t('This host is only a worker – stacks are only visible on a manager.')).show(); } else { $m.hide(); } } /* ---------- Header: summary + node cards ---------- */ const bar = (label, pct) => { const v = Math.max(0, Math.min(100, Math.round(+pct || 0))); const cls = v >= 90 ? 'sv-bar-bad' : v >= 70 ? 'sv-bar-warn' : ''; return `
${label}${v} %
`; }; function nodeCard(n) { const st = (((SV.data.stats || {}).nodes) || {})[n.hostname]; const role = n.role === 'manager' ? (n.leader ? 'Manager' : t('Manager (reserve)')) : 'Worker'; const down = n.state !== 'ready'; const maint = !down && n.availability !== 'active'; const labels = Object.entries(n.labels || {}).map(([k, v]) => `${k}=${v}`).join(', '); const tip = esc(`${n.addr} · ${n.arch} · Docker ${n.engine}${labels ? ' · ' + labels : ''}`); const state = down ? `${esc(t('unreachable'))}` : maint ? `${esc(n.availability === 'drain' ? t('maintenance') : t('paused'))}` : `${esc(t('ready'))}`; const statsOn = (SV.data.stats || {}).enabled; const since = st && st.ts ? new Date(st.ts * 1000).toLocaleTimeString(SV.LANG === 'de' ? 'de-DE' : undefined, { hour: '2-digit', minute: '2-digit' }) : ''; const load = !statsOn ? `
${esc(t('Load: switch on the CPU/RAM agent in the settings'))}
` : down ? `
${esc(since ? t('Node unreachable – last values {0}', since) : t('Node unreachable'))}
` : !st ? `
${esc(t('The agent has not reported values yet (it restarts after the node reboots)'))}
` : st.stale ? `
${esc(since ? t('no current values – last {0}', since) : t('no current values'))}
` : bar('CPU', st.cpu) + bar('RAM', st.mem); return `
${esc(n.hostname)} ${esc(role)} · ${n.cpus} CPU · ${n.memGB} GB${state}
${load}
`; } function renderNodes() { if (!SV.data.nodes.length) { $('#sv-nodes').empty(); return; } const services = SV.data.stacks.flatMap((st) => st.services); const tasks = services.flatMap((sv) => sv.tasks); const remote = tasks.filter((tk) => tk.node && !tk.local && /^running/i.test(tk.current)).length; const upd = services.filter((sv) => sv.update).length; const nStacks = SV.data.stacks.filter((st) => st.name !== PSEUDO).length; const parts = [tn(nStacks, '{0} stack', '{0} stacks'), tn(services.length, '{0} service', '{0} services'), tn(remote, '{0} container on other nodes', '{0} containers on other nodes')].map(esc); if (upd) parts.push(`${esc(tn(upd, '{0} update', '{0} updates'))}`); $('#sv-nodes').html(`
${parts.join(' · ')}
${SV.data.nodes.map(nodeCard).join('')}
`); } /* ---------- Update / rollback ---------- */ function serviceAction(act, svc) { const short = (findService(svc) || {}).short || svc; const texts = { 'svc-update': [t('Update "{0}"?', short), t('The newest image version is pulled and the service is rolled out again.')], 'svc-rollback': [t('Roll back "{0}"?', short), t('Rollback to {0} (docker service rollback).', (findService(svc) || {}).rollbackTo || t('the previous version'))], }; confirmBox(texts[act][0], texts[act][1], () => { SV.busy = true; $('.sv-svc-act').prop('disabled', true); post({ action: act, service: svc }) .done((r) => showResult(act === 'svc-update' ? `Update: ${short}` : `Rollback: ${short}`, r)) .fail((x) => showResult(short, failResult(x))) .always(() => { SV.busy = false; SV.load(); setTimeout(SV.load, 4000); }); }); } /* ---------- Menus (Unraid's context menu, like the container icons) ---------- */ function attachMenu(el, opts) { if (typeof context === 'undefined' || !el.id) return; context.settings({ right: false, above: 'auto' }); context.destroy('#' + el.id); context.attach('#' + el.id, opts); } const item = (text, icon, fn) => ({ text, icon, action: (e) => { e.preventDefault(); fn(); } }); function restartService(sv) { confirmBox(t('Restart "{0}"?', sv.short), t('The service is rolled out again with --force (all replicas).'), () => { post({ action: 'svc-restart', service: sv.name }) .done((r) => showResult(t('Restart: {0}', sv.short), r)) .fail((x) => showResult(t('Restart: {0}', sv.short), failResult(x))) .always(() => { SV.load(); setTimeout(SV.load, 4000); }); }); } /** ⋮ on a service row */ SV.serviceMenu = function (el) { const sv = findService(String($(el).data('service'))); if (!sv || SV.busy) return; const opts = []; if (sv.update) opts.push(item('Update', 'fa-flash', () => serviceAction('svc-update', sv.name))); if (sv.canRollback) opts.push(item(t('Rollback to {0}', sv.rollbackTo || t('previous version')), 'fa-undo', () => serviceAction('svc-rollback', sv.name))); opts.push(item(t('Restart'), 'fa-refresh', () => restartService(sv))); if (sv.mode !== 'global' && SV.data.nodes.length > 1) { const on = new Set(sv.tasks.map((tk) => tk.node)); for (const n of SV.data.nodes) { if ((on.size === 1 && on.has(n.hostname)) || !nodeCheck(sv, n).ok) continue; opts.push(item(t('Move to {0} (fixed)', n.hostname), 'fa-exchange', () => placeService(sv.name, `fixed:${n.hostname}`))); } if (sv.placeNode || sv.prefer) opts.push(item(t('Place automatically'), 'fa-random', () => placeService(sv.name, ''))); } const logTasks = sv.tasks.filter((tk) => tk.node && tk.id); if (logTasks.length) { opts.push({ divider: true }); for (const tk of logTasks.slice(0, 6)) { opts.push(item(logTasks.length > 1 ? `Logs (${tk.node}${tk.slot ? ' #' + tk.slot : ''})` : 'Logs', 'fa-navicon', () => SV.openLogs({ taskId: tk.id, name: `${sv.name}${tk.slot ? '.' + tk.slot : ''}`, node: tk.node }))); } } attachMenu(el, opts); }; /** Gear on a stack row */ SV.stackMenu = function (el) { const name = String($(el).data('name')); const e = stackList().find((x) => x.name === name); if (!e || SV.busy) return; const opts = []; if (e.managed) { opts.push(item(t('Edit'), 'fa-wrench', () => openEditor(name))); opts.push(item(t('Description'), 'fa-pencil', () => editDescription(name))); } if (e.st) opts.push(item(t('Restart'), 'fa-refresh', () => stackAction('restart', name))); if (e.managed && !e.st) { opts.push({ divider: true }); opts.push(item(t('Delete files'), 'fa-trash', () => deleteStack(name))); } attachMenu(el, opts); }; function editDescription(name) { const cur = (((SV.data.stackInfo || {})[name]) || {}).description || ''; const save = (v) => { if (v === false || v === null) return; post({ action: 'describe', name, description: String(v).trim() }) .done((r) => { if (!r.ok) showResult(t('Description'), r); SV.load(); }) .fail((x) => showResult(t('Description'), failResult(x))); }; if (typeof swal === 'function') { swal({ title: t('Description for "{0}"', name), text: t('Shown below the stack name (empty = none).'), type: 'input', showCancelButton: true, closeOnConfirm: true, inputValue: cur, confirmButtonText: t('Save'), cancelButtonText: t('Cancel'), }, (v) => setTimeout(() => save(v), 150)); } else { save(prompt(`${t('Description for "{0}"', name)}:`, cur)); } } function deleteStack(name) { confirmBox(t('Delete the stack files of "{0}"?', name), t('docker-stack.yml, .env and the description are removed from the flash drive.'), () => { post({ action: 'delete', name }) .done((r) => { if (r.ok) { if (edName === name) closeEditor(); SV.load(); } showResult(t('Delete: {0}', name), r); }) .fail((x) => showResult(t('Delete: {0}', name), failResult(x))); }); } /** Merge deployed stacks and stacks managed by Swarm View */ function stackList() { const deployed = new Map(SV.data.stacks.map((s) => [s.name, s])); const managed = new Set(SV.data.managed || []); const names = [...new Set([...deployed.keys(), ...managed])].sort((a, b) => (a === PSEUDO) - (b === PSEUDO) || a.localeCompare(b)); return names.map((n) => ({ name: n, st: deployed.get(n) || null, managed: managed.has(n) })); } const btn = (act, name, label, enabled = true) => ``; /** Drop the registry: "ghcr.io/music-assistant/server:latest" → "music-assistant/server:latest" */ const shortImage = (img) => { let s = String(img || ''); const parts = s.split('/'); if (parts.length > 1 && /[.:]|^localhost$/.test(parts[0])) s = parts.slice(1).join('/'); s = s.replace(/^library\//, ''); return s.slice(s.lastIndexOf('/') + 1).includes(':') ? s : `${s}:latest`; }; // placement rules from the file; node.hostname is already shown by the select const extraConstraints = (sv) => (sv.constraints || []).filter((c) => !/^\s*node\.hostname\s*==/.test(c)); let menuSeq = 0; const COLS = 5; function serviceRow(name, sv, open) { const m = String(sv.replicas || '').match(/^(\d+)\/(\d+)/); const rc = m ? replicaClass(+m[1], +m[2]) : ''; const cons = extraConstraints(sv); const tip = esc([sv.ports && `Ports: ${sv.ports}`, cons.length && t('Rules: {0}', cons.join(', '))].filter(Boolean).join('\n')); const badges = (sv.update ? ` Update` : '') + (sv.prefer ? ` ${esc(sv.prefer)}` : '') + (sv.rebalancing ? ` ${esc(t('returning …'))}` : ''); const id = `sv-menu-${++menuSeq}`; return ` ${esc(sv.short)}${sv.mode === 'global' ? ' (global)' : ''}${badges}${sv.ports ? `${esc(sv.ports)}` : ''} ${esc(sv.replicas)} ${sv.tasks.length ? sv.tasks.map(placeBadge).join('') : '–'}${placeSelect(sv)}${cons.length ? `
${cons.map(esc).join(' · ')}
` : ''} ${esc(shortImage(sv.image))}${sv.update ? ` ` : ''} `; } function renderStacks() { const $tb = $('#sv-stacks tbody'); if (document.activeElement && $(document.activeElement).is('#sv-stacks .sv-place')) return; if ($('.dropdown-context:visible').length) return; // do not re-render an open menu away under the mouse const swarmOk = SV.data.swarm.active && SV.data.swarm.manager; $('#sv-add, #sv-cleanup').prop('disabled', !swarmOk || SV.busy); const hl = SV.data.swarm.historyLimit; $('#sv-history').html(hl != null && hl > 1 ? `${esc(t('Swarm keeps up to {0} containers per service', hl))} – ${esc(t('set it to 1 in the settings'))}` : ''); if (!swarmOk) { $tb.html(`${esc(t('No Swarm stacks available (Swarm not active or not a manager)'))}`); return; } const list = stackList(); if (!list.length) { $tb.html(`${esc(t('No Swarm stacks yet – create one below with "Add New Swarm Stack"'))}`); return; } menuSeq = 0; let rows = ''; for (const { name, st, managed } of list) { const services = st ? st.services : []; const tasks = services.flatMap((sv) => sv.tasks); const { run, want } = replicaSum(services); const open = !!st && isOpen(name); const pseudo = name === PSEUDO; const info = (SV.data.stackInfo || {})[name] || {}; const icon = pseudo ? '' : ``; const status = st ? statusIcon(run, want) : ``; const nUpd = services.filter((sv) => sv.update).length; const desc = info.description ? `
${esc(info.description)}
` : !managed && !pseudo ? `
${esc(t('deployed externally'))}
` : ''; const path = info.path ? `
${esc(info.path)}
` : ''; let cmds = ''; if (managed) cmds = btn('deploy', name, 'Stack Up') + btn('update', name, 'Update Stack', !!st) + btn('remove', name, 'Stack Down', !!st); else if (st && !pseudo) cmds = btn('remove', name, 'Stack Down'); rows += ` ${icon}${esc(pseudo ? t(PSEUDO) : name)}${status} ${desc}${path} ${st ? `${run}/${want}
${esc(tn(services.length, '{0} service', '{0} services'))}${nUpd ? ` · ${esc(tn(nUpd, '{0} update', '{0} updates'))}` : ''}
` : `${esc(t('not deployed'))}`} ${st ? aggregateBadges(tasks) : '–'} ${cmds} `; for (const sv of services) rows += serviceRow(name, sv, open); } $tb.html(rows); } $(document).on('click', '#sv-stacks tr.sv-stack', function (e) { if ($(e.target).closest('.sv-act, .sv-gear, .sv-edit').length) return; const name = String($(this).data('stack')); const $svc = $('#sv-stacks tr.sv-svc').filter(function () { return String($(this).data('stack')) === name; }); if (!$svc.length) return; const open = !isOpen(name); setOpen(name, open); $(this).find('.sv-caret').toggleClass('fa-chevron-right', !open).toggleClass('fa-chevron-down', open); $svc.toggleClass('sv-open', open); }); // view switched → the default for stacks not toggled yet changes $(document).on('change', 'input.advancedview', () => setTimeout(() => SV.data && renderStacks(), 0)); function runAction(act, name, $button) { SV.busy = true; $('.sv-act, #sv-editor input').prop('disabled', true); const old = $button ? $button.val() : ''; if ($button) $button.val(t('running …')); const req = act === 'update' ? { action: 'deploy', mode: 'update', name } : { action: act, name }; post(req) .done((r) => showResult(`${LABELS[act]}: ${name}`, r)) .fail((x) => showResult(`${LABELS[act]}: ${name}`, failResult(x))) .always(() => { SV.busy = false; $('.sv-act, #sv-editor input').prop('disabled', false); if ($button) $button.val(old); SV.load(); // Swarm needs a few seconds until tasks run setTimeout(SV.load, 4000); }); } function stackAction(act, name, $b) { if (act === 'remove') { confirmBox(t('Shut down stack "{0}"?', name), t('All services of the stack are removed. Volumes and data are kept.'), () => runAction(act, name, $b)); } else if (act === 'update') { confirmBox(t('Update stack "{0}"?', name), t('Swarm checks all services for newer image versions and rolls them out. Services without a new version stay unchanged.'), () => runAction(act, name, $b)); } else if (act === 'restart') { confirmBox(t('Restart stack "{0}"?', name), t('All services are rolled out again with --force.'), () => runAction(act, name, $b)); } else { runAction(act, name, $b); } } $(document).on('click', '#sv-stacks .sv-act', function (e) { e.stopPropagation(); stackAction($(this).data('act'), String($(this).data('name')), $(this)); }); /* ---------- Editor ---------- */ let edName = null; function switchTab(file) { $('.sv-ed-tab').removeClass('active').filter(`[data-file="${file}"]`).addClass('active'); $('#sv-ed-yml').toggle(file === 'yml'); $('#sv-ed-env').toggle(file === 'env'); } function edLog(ok, text) { $('#sv-ed-log').attr('class', `sv-log ${ok ? 'sv-log-ok' : 'sv-log-err'}`).text(text).show(); } function openEditor(name, preload) { const show = (r) => { edName = name; $('#sv-ed-name').text(name); $('#sv-ed-path').text(r.path || ''); $('#sv-ed-yml').val(r.yml || ''); $('#sv-ed-env').val(r.env || ''); $('#sv-ed-log').hide(); $('#sv-ed-delete').toggle(!r.deployed); switchTab('yml'); $('#sv-editor').show()[0].scrollIntoView({ behavior: 'smooth', block: 'start' }); }; if (preload) show(preload); else post({ action: 'get', name }).done((r) => (r.ok ? show(r) : showResult(t('Error'), r))).fail((x) => showResult(t('Error'), failResult(x))); } function closeEditor() { edName = null; $('#sv-editor').hide(); } function saveEditor() { return post({ action: 'save', name: edName, yml: $('#sv-ed-yml').val(), env: $('#sv-ed-env').val() }) .done((r) => edLog(r.ok && r.valid, r.ok ? `${t('Saved.')} ${r.log || ''}` : (r.error || t('Error')))) .fail((x) => edLog(false, failResult(x).error)); } $(document).on('click', '.sv-edit', function (e) { e.stopPropagation(); openEditor(String($(this).data('name'))); }); $(document).on('click', '.sv-ed-tab', function (e) { e.preventDefault(); switchTab($(this).data('file')); }); $(document).on('click', '#sv-ed-close', closeEditor); $(document).on('click', '#sv-ed-save', () => saveEditor().done(() => SV.load())); $(document).on('click', '#sv-ed-deploy', function () { const name = edName; saveEditor().done((r) => { if (r.ok && r.valid) runAction('deploy', name, $(this)); else edLog(false, `${t('Not deployed – the file is invalid:')}\n${r.log || r.error || ''}`); }); }); $(document).on('click', '#sv-ed-delete', () => deleteStack(edName)); // Tab key in the editor = 2 spaces (YAML) $(document).on('keydown', '.sv-ed-text', function (e) { if (e.key !== 'Tab') return; e.preventDefault(); const s = this.selectionStart; this.value = this.value.slice(0, s) + ' ' + this.value.slice(this.selectionEnd); this.selectionStart = this.selectionEnd = s + 2; }); /* ---------- Cleanup ---------- */ $(document).on('click', '#sv-cleanup', function () { const $b = $(this); const label = $b.val(); confirmBox(t('Clean up Swarm?'), t('Removes stopped Swarm containers and unused images on all nodes. Running containers are not touched. Swarm also keeps only the current container per service from now on.'), () => { SV.busy = true; $b.prop('disabled', true).val(t('cleaning up …')); post({ action: 'cleanup' }) .done((r) => showResult(t('Cleanup'), r)) .fail((x) => showResult(t('Cleanup'), failResult(x))) .always(() => { SV.busy = false; $b.prop('disabled', false).val(label); SV.load(); if (typeof window.loadlist === 'function' && !SV.listPending) window.loadlist(); }); }); }); /* ---------- New stack ---------- */ function createStack(raw) { const name = String(raw || '').trim().toLowerCase(); if (!name) return; post({ action: 'create', name }) .done((r) => { if (r.ok) { openEditor(name, r); SV.load(); } else showResult(t('New stack'), r); }) .fail((x) => showResult(t('New stack'), failResult(x))); } $(document).on('click', '#sv-add', () => { if (typeof swal === 'function') { swal({ title: t('New Swarm stack'), text: t('Name (a-z, 0-9, - and _)'), type: 'input', showCancelButton: true, closeOnConfirm: true, inputPlaceholder: 'stack_name', confirmButtonText: t('Create'), cancelButtonText: t('Cancel'), }, (v) => { if (v !== false) setTimeout(() => createStack(v), 150); }); } else { createStack(prompt(t('Name of the new Swarm stack (a-z, 0-9, - and _):'))); } }); Object.assign(SV, { renderMsg, renderNodes, renderStacks, openEditor, serviceAction }); })(jQuery); ]]>
chmod -R u=rwX,go=rX &plugdir; # activate the saved cleanup schedule (cleanup.cron) if [ -x /usr/local/sbin/update_cron ]; then /usr/local/sbin/update_cron; fi # bring the CPU/RAM agent to the new version (if enabled) timeout 60 /usr/bin/php -q &plugdir;/scripts/postinstall.php || true echo "" echo "Swarm View &version; installed - reload the Docker page." rm -rf &plugdir; rm -f /boot/config/plugins/&name;/cleanup.cron # remove helper services from the swarm (agent on all nodes, cleanup job) if [ -x /usr/bin/docker ]; then /usr/bin/docker service rm swarm-view-agent swarm-view-cleanup >/dev/null 2>&1; fi rm -rf /tmp/swarm-view if [ -x /usr/local/sbin/update_cron ]; then /usr/local/sbin/update_cron; fi echo "Swarm View removed (stack files and settings stay in /boot/config/plugins/&name;/)."