icingaweb2-module-director/library/Director/Cli/Command.php

116 lines
2.8 KiB
PHP
Raw Normal View History

<?php
namespace Icinga\Module\Director\Cli;
2022-07-11 10:03:23 +02:00
use gipfl\Json\JsonDecodeException;
use gipfl\Json\JsonString;
use Icinga\Cli\Command as CliCommand;
use Icinga\Module\Director\Application\MemoryLimit;
2016-11-01 18:28:36 +01:00
use Icinga\Module\Director\Core\CoreApi;
use Icinga\Module\Director\Db;
2016-02-17 16:43:29 +01:00
use Icinga\Module\Director\Objects\IcingaEndpoint;
use Icinga\Application\Config;
2018-06-13 21:34:27 +02:00
use RuntimeException;
class Command extends CliCommand
{
2016-11-01 18:28:36 +01:00
/** @var Db */
protected $db;
2016-11-01 18:28:36 +01:00
/** @var CoreApi */
2016-02-17 16:43:29 +01:00
private $api;
2016-03-16 20:28:52 +01:00
protected function renderJson($object, $pretty = true)
{
return JsonString::encode($object, $pretty ? JSON_PRETTY_PRINT : null) . "\n";
2016-03-16 20:28:52 +01:00
}
/**
* @param $json
* @return mixed
*/
2016-03-16 20:28:52 +01:00
protected function parseJson($json)
{
2022-07-11 10:03:23 +02:00
try {
return JsonString::decode($json);
} catch (JsonDecodeException $e) {
$this->fail('Invalid JSON: %s', $e->getMessage());
2016-03-16 20:28:52 +01:00
}
}
/**
* @param string $msg
* @return never-return
*/
2018-06-13 21:34:27 +02:00
public function fail($msg)
2016-03-16 20:28:52 +01:00
{
2018-06-13 21:34:27 +02:00
$args = func_get_args();
array_shift($args);
if (count($args)) {
$msg = vsprintf($msg, $args);
2016-03-16 20:28:52 +01:00
}
echo $this->screen->colorize("ERROR", 'red') . ": $msg\n";
exit(1);
2018-06-13 21:34:27 +02:00
}
/**
* @param null $endpointName
* @return CoreApi|\Icinga\Module\Director\Core\LegacyDeploymentApi
* @throws \Icinga\Exception\NotFoundError
*/
2016-02-17 16:43:29 +01:00
protected function api($endpointName = null)
{
if ($this->api === null) {
if ($endpointName === null) {
$endpoint = $this->db()->getDeploymentEndpoint();
} else {
$endpoint = IcingaEndpoint::load($endpointName, $this->db());
}
$this->api = $endpoint->api();
}
return $this->api;
}
/**
* Raise PHP resource limits
*
* @return self;
*/
protected function raiseLimits()
{
MemoryLimit::raiseTo('1024M');
ini_set('max_execution_time', 0);
if (version_compare(PHP_VERSION, '7.0.0') < 0) {
ini_set('zend.enable_gc', 0);
}
return $this;
}
2016-11-01 18:28:36 +01:00
/**
* @return Db
*/
protected function db()
{
if ($this->db === null) {
$resourceName = $this->params->get('dbResourceName');
if ($resourceName === null) {
// Hint: not using $this->Config() intentionally. This allows
// CLI commands in other modules to use this as a base class.
$resourceName = Config::module('director')->get('db', 'resource');
}
if ($resourceName) {
$this->db = Db::fromResourceName($resourceName);
} else {
2018-06-13 21:34:27 +02:00
throw new RuntimeException('Director is not configured correctly');
}
}
return $this->db;
}
}