Files
thetool/scripts/monitoring/run-zabbix-device-sync.php

80 lines
2.4 KiB
PHP

#!/usr/bin/php
<?php
require("../../config/config.php");
require_once(LIBDIR . "/mvcfronk/mfRouter/mfRouter.php");
require_once(LIBDIR . "/mvcfronk/mfBase/mfBaseModel.php");
require_once(LIBDIR . "/mvcfronk/mfBase/mfBaseController.php");
const FRONKDB_SQLDEBUG = false;
const INTERNAL_USER_ID = 1;
const INTERNAL_USER_USERNAME = "admin";
$zabbix = new Zabbix(ZABBIX_API_URL, ZABBIX_API_KEY);
$log = fn($msg) => print "ZABBIX-DEVICE-SYNC: [" . date("Y-m-d H:i:s") . "] $msg\n";
if (isset($argv[1])) {
$deviceId = $argv[1];
$log("Child started for device ID: $deviceId");
if (!$device = DeviceModel::getOne($deviceId)) {
$log("Device $deviceId not found.");
exit(1);
}
$log("Processing: {$device->name} ({$device->ip})");
$hosts = array_merge($zabbix->getHosts(null, $device->ip), $zabbix->getHosts($device->name));
if (empty($hosts)) {
$log("{$device->name}({$device->ip}) not found in Zabbix.");
exit(0);
}
$hostId = $hosts[0]['hostid'];
$status = array_reduce($zabbix->getICMPItems($hostId), fn($carry, $item) => strpos($item['key_'], 'icmpping[') !== false ? $item['lastvalue'] + 1 : $carry, 0);
$log("Found in Zabbix: hostId=$hostId, status=$status");
$device->zabbix_online = $status;
$device->zabbix_host_id = $hostId;
$log($device->save() ? "Saved Zabbix status." : "Failed to save Zabbix status.");
$log("Child finished for device ID: $deviceId");
exit(0);
}
$devices = DeviceModel::getAll();
$maxProcesses = 32;
$activeProcesses = [];
$log("Parent started. Total devices: " . count($devices));
foreach ($devices as $device) {
if (count($activeProcesses) >= $maxProcesses) {
$log("Max processes reached. Waiting...");
$pid = pcntl_wait($status);
unset($activeProcesses[$pid]);
$log("Child $pid finished.");
}
if (($pid = pcntl_fork()) == -1) {
$log("Fork failed for device ID: {$device->id}");
die('Fork failed');
}
if ($pid) {
$activeProcesses[$pid] = true;
$log("Forked child $pid for device ID: {$device->id}");
} else {
exec("php " . __FILE__ . " " . $device->id);
exit(0);
}
}
while (count($activeProcesses) > 0) {
$log("Waiting for remaining children...");
$pid = pcntl_wait($status);
unset($activeProcesses[$pid]);
$log("Child $pid finished.");
}
$log("All children finished. Parent exiting.");
?>