From 426e574b85d363cd5a1fa256034dc2a281fc7272 Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Fri, 15 May 2020 17:24:05 +0200 Subject: [remoteaccess] New module --- .../remoteaccess/inc/remoteaccess.inc.php | 78 ++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 modules-available/remoteaccess/inc/remoteaccess.inc.php (limited to 'modules-available/remoteaccess/inc/remoteaccess.inc.php') diff --git a/modules-available/remoteaccess/inc/remoteaccess.inc.php b/modules-available/remoteaccess/inc/remoteaccess.inc.php new file mode 100644 index 00000000..1dbe02c3 --- /dev/null +++ b/modules-available/remoteaccess/inc/remoteaccess.inc.php @@ -0,0 +1,78 @@ + $group]); + } + + public static function ensureMachinesRunning() + { + $res = Database::simpleQuery("SELECT rg.groupid, rg.wolcount, GROUP_CONCAT(rxl.locationid) AS locs FROM remoteaccess_group rg + INNER JOIN remoteaccess_x_location rxl USING (groupid) + WHERE rg.active = 1 + GROUP BY groupid"); + + while ($row = $res->fetch(PDO::FETCH_ASSOC)) { + if ($row['wolcount'] <= 0) + continue; + // This can't really be anything but a CSV list, but better be safe + $locs = preg_replace('/[^0-9,]/', '', $row['locs']); + if (empty($locs)) + continue; + $active = Database::queryFirst("SELECT Count(*) AS cnt FROM machine m + INNER JOIN remoteaccess_machine rm USING (machineuuid) + WHERE m.locationid IN ($locs) AND m.state = 'IDLE'"); + $wantNum = $row['wolcount'] - (isset($active['cnt']) ? $active['cnt'] : 0); + if ($wantNum <= 0) + continue; + self::tryWakeMachines($locs, $wantNum); + } + } + + private static function tryWakeMachines($locs, $num) + { + $res = Database::simpleQuery("SELECT m.machineuuid, m.macaddr, m.clientip FROM machine m + LEFT JOIN remoteaccess_machine rm USING (machineuuid) + WHERE m.locationid IN ($locs) AND m.state IN ('OFFLINE', 'STANDBY') + ORDER BY rm.woltime ASC"); + $NOW = time(); + while ($num > 0) { + $list = []; + for ($i = 0; $i < $num && $row = $res->fetch(PDO::FETCH_ASSOC); ++$i) { + $list[] = $row; + Database::exec("INSERT INTO remoteaccess_machine (machineuuid, password, woltime) + VALUES (:uuid, NULL, :now) + ON DUPLICATE KEY UPDATE woltime = VALUES(woltime)", + ['uuid' => $row['machineuuid'], 'now' => $NOW]); + } + if (empty($list)) + break; // No more clients in this location + error_log('Trying to wake ' . count($list) . " in $locs"); + RebootControl::wakeMachines($list, $fails); + $num -= count($list) - count($fails); + if (!empty($fails)) { + error_log(count($fails) . ' failed'); + $failIds = ArrayUtil::flattenByKey($fails, 'machineuuid'); + // Reduce time so they won't be marked as wol_in_progress + Database::exec('UPDATE remoteaccess_machine SET woltime = :faketime WHERE machineuuid IN (:fails)', + ['faketime' => $NOW - 95, 'fails' => $failIds]); + } + } + if ($num > 0) { + error_log("Could not wake $num clients..."); + } + } + +} -- cgit v1.2.3-55-g7522