protected-resources-list/plugins/quagga/QuaggaPlugin.php

89 lines
2.5 KiB
PHP

<?php
class QuaggaPlugin implements IPluggable
{
private PluginContext $context;
const REM_PREFIX = "! routes from file ";
public function restart(): string
{
$configfile = $this->context->getConfig()["quagga"]["file"];
if (!file_exists($configfile)) {
throw new RuntimeException("Quagga config file not found");
}
$networks = (new NetworkConfigReader())->getConfigs();
$routeParser = new RoutingTableReader();
$routes = $routeParser->getRoutes();
$defGatewayInterface = "";
$defGateway = "";
foreach ($routes as $route) {
if ($route["dst"] === "0.0.0.0/0") {
$defGatewayInterface = $route["dev"];
$defGateway = $route["gateway"];
break;
}
}
if (!$defGatewayInterface) {
throw new RuntimeException("Failed to detect default gateway interface");
}
$contents = file_get_contents($configfile);
$lines = explode("\n", $contents);
//remove existing routes
foreach ($lines as $key => $line) {
if (str_starts_with($line, self::REM_PREFIX) or str_starts_with($line, "ip route ") and str_contains($line . " ", $defGateway . " ")) {
unset($lines[$key]);
}
}
//add new routes
foreach ($this->context->getConfig()["networks"] as $key) {
$lines[] = self::REM_PREFIX . $key;
if (isset($networks[$key])) {
foreach ($networks[$key]["networks"] as $route) {
$lines[] = "ip route " . $route . " " . $defGateway;
}
}
}
foreach ($lines as $key => $line) {
if (trim($line) === "") {
unset($lines[$key]);
}
}
$backupFile = $configfile . ".sav";
unlink($backupFile);
rename($configfile, $backupFile);
file_put_contents($configfile, implode("\n", $lines));
//restart zebra
return shell_exec($this->context->getConfig()["quagga"]["restart_cmd"]);
}
public function init(PluginContext $context): void
{
$this->context = $context;
$this->checkConfig();
}
private function checkConfig(): void
{
$config = $this->context->getConfig();
if (!isset($config["quagga"])) {
$config["quagga"] = $this->context->getMetadata()["config"];
}
}
}