OpenNIT

Quelltext des aktuellen Standes

Fassung 1.1.1

sync-vms.php

4 KB
<?php
// Cron-Script: Hypervisor VM-Synchronisierung
//
// Synchronisiert VMs aller Hosts, die eine Hypervisor-URL konfiguriert haben.
// Empfohlenes Cron-Intervall (alle 30 Minuten):
//   */30 * * * *  /usr/bin/php /pfad/zu/bin/sync-vms.php >> /pfad/zu/storage/logs/sync-vms.log 2>&1

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../bootstrap.php';

use OpenNIT\Core\Database;
use OpenNIT\Hypervisor\HypervisorSyncService;

$dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__));
$dotenv->load();

$dbConfig      = require __DIR__ . '/../config/database.php';
$runtimeConfig = [];
$runtimeFile   = __DIR__ . '/../config/runtime.php';
if (file_exists($runtimeFile)) {
    $runtimeConfig = include $runtimeFile;
}

$db = new Database($dbConfig);

$timezone = $runtimeConfig['app']['timezone'] ?? 'Europe/Berlin';
date_default_timezone_set($timezone);

// Cron-Lauf tracken
$runId = null;
try {
    $runId = (int)$db->insert('cronjob_runs', [
        'job_name'   => 'vm_sync',
        'started_at' => date('Y-m-d H:i:s'),
        'status'     => 'running',
    ]);
} catch (\Throwable) {}

// Alle Hosts mit konfigurierter Hypervisor-URL laden
$hosts = $db->fetchAll(
    "SELECT id, name, hypervisor
     FROM vm_hosts
     WHERE hypervisor_url IS NOT NULL AND hypervisor_url != ''
     ORDER BY name ASC"
);

if (empty($hosts)) {
    $msg = 'Keine Hosts mit konfigurierter Hypervisor-URL gefunden.';
    echo '[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL;
    if ($runId) {
        try {
            $db->update('cronjob_runs', [
                'finished_at'     => date('Y-m-d H:i:s'),
                'status'          => 'success',
                'message'         => $msg,
                'items_processed' => 0,
            ], 'id = ?', [$runId]);
        } catch (\Throwable) {}
    }
    exit(0);
}

$appKey  = $runtimeConfig['app']['key'] ?? ($_ENV['APP_KEY'] ?? '');
$svc     = new HypervisorSyncService($db, $appKey);

$totalSynced  = 0;
$totalCreated = 0;
$totalUpdated = 0;
$errors       = [];

echo '[' . date('Y-m-d H:i:s') . '] Starte VM-Synchronisierung für ' . count($hosts) . ' Host(s)…' . PHP_EOL;

foreach ($hosts as $host) {
    $label = $host['name'] . ' [' . $host['hypervisor'] . ']';
    echo '[' . date('Y-m-d H:i:s') . '] Synchronisiere ' . $label . '…' . PHP_EOL;

    try {
        $result = $svc->syncHost((int)$host['id'], 0); // userId=0 = System/Cron

        if ($result['ok']) {
            $totalSynced  += $result['vms_synced'];
            $totalCreated += $result['vms_created'];
            $totalUpdated += $result['vms_updated'];
            echo '[' . date('Y-m-d H:i:s') . ']   OK: '
                . $result['vms_synced'] . ' VMs synced ('
                . $result['vms_created'] . ' neu, '
                . $result['vms_updated'] . ' aktualisiert)'
                . PHP_EOL;
        } else {
            $errors[] = $label . ': ' . $result['error'];
            echo '[' . date('Y-m-d H:i:s') . ']   FEHLER: ' . $result['error'] . PHP_EOL;
        }
    } catch (\Throwable $e) {
        $errors[] = $label . ': ' . $e->getMessage();
        echo '[' . date('Y-m-d H:i:s') . ']   EXCEPTION: ' . $e->getMessage() . PHP_EOL;
    }
}

$summary = $totalSynced . ' VMs gesamt synced ('
    . $totalCreated . ' neu, '
    . $totalUpdated . ' aktualisiert).'
    . (count($errors) ? ' Fehler bei ' . count($errors) . ' Host(s).' : '');

echo '[' . date('Y-m-d H:i:s') . '] Fertig. ' . $summary . PHP_EOL;

if ($runId) {
    try {
        $db->update('cronjob_runs', [
            'finished_at'     => date('Y-m-d H:i:s'),
            'status'          => empty($errors) ? 'success' : 'error',
            'message'         => $summary . (count($errors) ? ' Fehler: ' . implode('; ', $errors) : ''),
            'items_processed' => $totalSynced,
        ], 'id = ?', [$runId]);
    } catch (\Throwable) {}
}

exit(empty($errors) ? 0 : 1);