Пример #1
0
 protected function request($method, $url, $body = null, $raw = false)
 {
     $auth = base64_encode(sprintf('%s:%s', $this->user, $this->pass));
     $headers = array('Host: ' . $this->getPeerIdentity(), 'Authorization: Basic ' . $auth, 'Connection: close');
     if (!$raw) {
         $headers[] = 'Accept: application/json';
     }
     if ($body !== null) {
         $body = json_encode($body);
         $headers[] = 'Content-Type: application/json';
     }
     $opts = array('http' => array('protocol_version' => '1.1', 'user_agent' => 'Icinga Web 2.0 - Director', 'method' => strtoupper($method), 'content' => $body, 'header' => $headers, 'ignore_errors' => true), 'ssl' => array('verify_peer' => false));
     $context = stream_context_create($opts);
     Benchmark::measure('Rest Api, sending ' . $url);
     $res = file_get_contents($this->url($url), false, $context);
     if (substr(array_shift($http_response_header), 0, 10) !== 'HTTP/1.1 2') {
         throw new Exception($res);
     }
     Benchmark::measure('Rest Api, got response');
     if ($raw) {
         return $res;
     } else {
         return RestApiResponse::fromJsonResult($res);
     }
 }
 public function filterAction()
 {
     $flat = array();
     $filter = Filter::fromQueryString('vars.bpconfig=*');
     Benchmark::measure('ready');
     $objs = IcingaHost::loadAll($this->db());
     Benchmark::measure('db done');
     foreach ($objs as $host) {
         $flat[$host->id] = (object) array();
         foreach ($host->getProperties() as $k => $v) {
             $flat[$host->id]->{$k} = $v;
         }
     }
     Benchmark::measure('objects ready');
     $vars = IcingaHostVar::loadAll($this->db());
     Benchmark::measure('vars loaded');
     foreach ($vars as $var) {
         if (!array_key_exists($var->host_id, $flat)) {
             continue;
         }
         // Templates?
         $flat[$var->host_id]->{'vars.' . $var->varname} = $var->varvalue;
     }
     Benchmark::measure('vars done');
     foreach ($flat as $host) {
         if ($filter->matches($host)) {
             echo $host->object_name . "\n";
         }
     }
     return;
     Benchmark::measure('all done');
 }
 public function fetchData()
 {
     if ($this->getSetting('query_type') === 'resource') {
         return $this->fetchResourceData();
     }
     $result = array();
     $db = $this->db();
     Benchmark::measure('Pdb, going to fetch classes');
     $data = $db->classes();
     Benchmark::measure('Pdb, got classes, going to fetch facts');
     $facts = $db->fetchFacts();
     Benchmark::measure('Pdb, got facts, preparing result');
     foreach ($facts as $host => $f) {
         $f = $facts[$host];
         if (array_key_exists($host, $data)) {
             $classes = $data[$host];
         } else {
             $classes = array();
         }
         foreach (array_keys((array) $f) as $key) {
             if (preg_match('/(?:memoryfree|swapfree|uptime)/', $key)) {
                 unset($f->{$key});
             }
         }
         $result[] = (object) array('certname' => $host, 'classes' => $classes, 'facts' => $f);
     }
     Benchmark::measure('Pdb result ready');
     return $result;
 }
Пример #4
0
 protected function runScheduledSyncs()
 {
     // TODO: import-triggered:
     //      foreach $rule->involvedImports() -> if changedsince -> ... syncChangedRows
     foreach (SyncRule::loadAll($this->db) as $rule) {
         Benchmark::measure('Checking sync rule ' . $rule->rule_name);
         $mod = Sync::getExpectedModifications($rule);
         if (count($mod) > 0) {
             printf('Sync rule "%s" provides changes, triggering sync... ', $rule->rule_name);
             Benchmark::measure('Got modifications for sync rule ' . $rule->rule_name);
             if (Sync::run($rule)) {
                 Benchmark::measure('Successfully synced rule ' . $rule->rule_name);
                 print "SUCCEEDED\n";
             }
         }
     }
     return $this;
 }
Пример #5
0
 /**
  * Constructor
  *
  * @param string $baseDir   Icinga Web 2 base directory
  * @param string $configDir Path to Icinga Web 2's configuration files
  */
 protected function __construct($baseDir = null, $configDir = null)
 {
     if ($baseDir === null) {
         $baseDir = dirname($this->getBootstrapDirectory());
     }
     $this->baseDir = $baseDir;
     $this->appDir = $baseDir . '/application';
     $this->vendorDir = $baseDir . '/library/vendor';
     $this->libDir = realpath(__DIR__ . '/../..');
     $this->setupAutoloader();
     if ($configDir === null) {
         $configDir = getenv('ICINGAWEB_CONFIGDIR');
         if ($configDir === false) {
             $configDir = Platform::isWindows() ? $baseDir . '/config' : '/etc/icingaweb2';
         }
     }
     $canonical = realpath($configDir);
     $this->configDir = $canonical ? $canonical : $configDir;
     set_include_path(implode(PATH_SEPARATOR, array($this->vendorDir, get_include_path())));
     Benchmark::measure('Bootstrap, autoloader registered');
     Icinga::setApp($this);
     require_once dirname(__FILE__) . '/functions.php';
 }
Пример #6
0
 /**
  * Count all rows of the result set, ignoring limit and offset
  *
  * @return  int
  */
 public function count()
 {
     $query = clone $this;
     $query->limit(0, 0);
     Benchmark::measure('Counting all results started');
     $count = $this->ds->count($query);
     Benchmark::measure('Counting all results finished');
     return $count;
 }
Пример #7
0
 /**
  * Query the database and return all results
  *
  * @return array        An array containing subarrays with all results contained in the database
  */
 public function fetchAll()
 {
     Benchmark::measure('DB is fetching All');
     $result = $this->db->fetchAll($this->getSelectQuery());
     Benchmark::measure('DB fetch done');
     return $result;
 }
Пример #8
0
 /**
  * Return whether the current row of this query's result is valid
  *
  * @return  bool
  */
 public function valid()
 {
     if (!$this->iterator->valid()) {
         Benchmark::measure('Query result iteration finished');
         return false;
     }
     return true;
 }
Пример #9
0
 protected function dispatchEndless()
 {
     $loader = $this->cliLoader();
     $loader->parseParams();
     $screen = Screen::instance();
     while (true) {
         Benchmark::measure('Watch mode - loop begins');
         ob_start();
         $params = clone $this->params;
         $loader->dispatch($params);
         Benchmark::measure('Dispatch done');
         if ($this->showBenchmark) {
             Benchmark::dump();
         }
         Benchmark::reset();
         $out = ob_get_contents();
         ob_end_clean();
         echo $screen->clear() . $out;
         sleep($this->watchTimeout);
     }
 }
Пример #10
0
 /**
  * Render the benchmark
  *
  * @return string Benchmark HTML
  */
 protected function renderBenchmark()
 {
     return Benchmark::renderToHtml();
 }
 /**
  * Retrieve columns from the Elasticsearch indices.
  *
  * It will get you a merged list of columns available over the specified indices and types.
  *
  * @param   array   $indices    The indices or index patterns to get
  * @param   array   $types      An array of types to get columns for
  *
  * @throws  QueryException  When Elasticsearch returns an error
  *
  * @return  array           A list of column names
  *
  * @todo    Do a cached retrieval?
  */
 public function fetchColumns(array $indices = null, array $types = null)
 {
     Benchmark::measure('Retrieving columns for types: ' . (!empty($types) ? join(', ', $types) : '(all)'));
     $request = new GetMappingApiRequest($indices, $types);
     $response = $this->request($request);
     if (!$response->isSuccess()) {
         if ($response->getStatusCode() === 404) {
             return false;
         }
         throw new QueryException($this->renderErrorMessage($response));
     }
     // initialize with interal columns
     $columns = array('_index', '_type', '_id');
     foreach ($response->json() as $index => $mappings) {
         if (!array_key_exists('mappings', $mappings)) {
             continue;
         }
         foreach ($mappings['mappings'] as $type) {
             if (!array_key_exists('properties', $type)) {
                 continue;
             }
             foreach ($type['properties'] as $column => $detail) {
                 if ($column === '@version') {
                     continue;
                 }
                 if (array_key_exists('properties', $detail)) {
                     // ignore structured types
                     // TODO: support this later?
                     continue;
                 }
                 if (!in_array($column, $columns)) {
                     $columns[] = $column;
                 }
             }
         }
     }
     Benchmark::measure('Finished retrieving columns');
     return $columns;
 }
Пример #12
0
 public function fetchAll(Query $query)
 {
     Benchmark::measure('Sending Livestatus Query');
     $data = $this->doFetch((string) $query);
     Benchmark::measure('Got Livestatus Data');
     if ($query->hasColumns()) {
         $headers = $query->getColumnAliases();
     } else {
         $headers = array_shift($data);
     }
     $result = array();
     foreach ($data as $row) {
         $result_row =& $result[];
         $result_row = (object) array();
         foreach ($row as $key => $val) {
             $result_row->{$headers[$key]} = $val;
         }
     }
     if ($query->hasOrder()) {
         usort($result, array($query, 'compare'));
     }
     if ($query->hasLimit()) {
         $result = array_slice($result, $query->getOffset(), $query->getLimit());
     }
     Benchmark::measure('Data sorted, limits applied');
     return $result;
 }
Пример #13
0
 /**
  * Disconnect in case we are connected to a Livestatus socket
  *
  * @return $this
  */
 public function disconnect()
 {
     if (is_resource($this->connection) && get_resource_type($this->connection) === 'Socket') {
         Benchmark::measure('Disconnecting livestatus...');
         socket_close($this->connection);
         Benchmark::measure('...socket closed');
     }
     return $this;
 }
 protected function curlRequest($method, $url, $body = null, $raw = false)
 {
     $auth = sprintf('%s:%s', $this->user, $this->pass);
     $headers = array('Host: ' . $this->getPeerIdentity(), 'Connection: close');
     if (!$raw) {
         $headers[] = 'Accept: application/json';
     }
     if ($body !== null) {
         $body = json_encode($body);
         $headers[] = 'Content-Type: application/json';
     }
     $curl = $this->curl();
     $opts = array(CURLOPT_URL => $this->url($url), CURLOPT_HTTPHEADER => $headers, CURLOPT_USERPWD => $auth, CURLOPT_CUSTOMREQUEST => strtoupper($method), CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false);
     if ($body !== null) {
         $opts[CURLOPT_POSTFIELDS] = $body;
     }
     curl_setopt_array($curl, $opts);
     Benchmark::measure('Rest Api, sending ' . $url);
     $res = curl_exec($curl);
     if ($res === false) {
         throw new Exception('CURL ERROR: ' . curl_error($curl));
     }
     Benchmark::measure('Rest Api, got response');
     if ($raw) {
         return $res;
     } else {
         return RestApiResponse::fromJsonResult($res);
     }
 }
 protected function createFileForObjects($type, $objects)
 {
     Benchmark::measure(sprintf('Generating %d %s', count($objects), $type));
     if (empty($objects)) {
         return $this;
     }
     $masterZone = $this->getMasterZoneName();
     $globalZone = $this->getGlobalZoneName();
     $file = null;
     foreach ($objects as $object) {
         if ($object->isExternal()) {
             if ($type === 'zone') {
                 $this->zoneMap[$object->id] = $object->object_name;
             }
             continue;
         } elseif ($object->isTemplate()) {
             $filename = strtolower($type) . '_templates';
         } else {
             $filename = strtolower($type) . 's';
         }
         // Zones get special handling
         if ($type === 'zone') {
             $this->zoneMap[$object->id] = $object->object_name;
             // If the zone has a parent zone...
             if ($object->parent_id) {
                 // ...we render the zone object to the parent zone
                 $zone = $object->parent;
             } elseif ($object->is_global === 'y') {
                 // ...additional global zones are rendered to our global zone...
                 $zone = $globalZone;
             } else {
                 // ...and all the other zones are rendered to our master zone
                 $zone = $masterZone;
             }
             // Zone definitions for all other objects are respected...
         } elseif ($object->hasProperty('zone_id') && ($zone_id = $object->zone_id)) {
             $zone = $this->getZoneName($zone_id);
             // ...and if there is no zone defined, special rules take place
         } else {
             if ($this->typeWantsMasterZone($type)) {
                 $zone = $masterZone;
             } elseif ($this->typeWantsGlobalZone($type)) {
                 $zone = $globalZone;
             } else {
                 throw new ProgrammingError('I have no idea of how to deploy a "%s" object', $type);
             }
         }
         $filename = 'zones.d/' . $zone . '/' . $filename;
         $file = $this->configFile($filename);
         $file->addObject($object);
     }
     if ($file && $type === 'command') {
         $file->prepend("library \"methods\"\n\n");
     }
     return $this;
 }
Пример #16
0
 /**
  * Render the benchmark
  *
  * @return string Benchmark HTML
  */
 protected function renderBenchmark()
 {
     $this->_helper->viewRenderer->postDispatch();
     Benchmark::measure('Response ready');
     return Benchmark::renderToHtml();
 }
 /**
  * @return BusinessProcess
  */
 public function loadProcess($name)
 {
     Benchmark::measure('Loading business process ' . $name);
     $bp = new BusinessProcess();
     $bp->setName($name);
     $this->parseFile($name, $bp);
     $this->loadHeader($name, $bp);
     Benchmark::measure('Business process ' . $name . ' loaded');
     return $bp;
 }
 /**
  * Constructor
  */
 protected function __construct($configDir = null)
 {
     $this->libDir = realpath(__DIR__ . '/../..');
     if (!defined('ICINGA_LIBDIR')) {
         define('ICINGA_LIBDIR', $this->libDir);
     }
     if (defined('ICINGAWEB_APPDIR')) {
         $this->appDir = ICINGAWEB_APPDIR;
     } elseif (array_key_exists('ICINGAWEB_APPDIR', $_SERVER)) {
         $this->appDir = $_SERVER['ICINGAWEB_APPDIR'];
     } else {
         $this->appDir = realpath($this->libDir . '/../application');
     }
     if (!defined('ICINGAWEB_APPDIR')) {
         define('ICINGAWEB_APPDIR', $this->appDir);
     }
     if ($configDir === null) {
         if (array_key_exists('ICINGAWEB_CONFIGDIR', $_SERVER)) {
             $configDir = $_SERVER['ICINGAWEB_CONFIGDIR'];
         } else {
             $configDir = '/etc/icingaweb';
         }
     }
     $this->configDir = realpath($configDir);
     $this->setupAutoloader();
     $this->setupZendAutoloader();
     Benchmark::measure('Bootstrap, autoloader registered');
     Icinga::setApp($this);
     require_once dirname(__FILE__) . '/functions.php';
 }
 public function reallyRetrieveStatesFromBackend()
 {
     Benchmark::measure('Retrieving states for business process ' . $this->getName());
     $backend = $this->getBackend();
     // TODO: Split apart, create a dedicated function.
     //       Separate "parse-logic" from "retrieve-state-logic"
     //       Allow DB-based backend
     //       Use IcingaWeb2 Multi-Backend-Support
     $check_results = array();
     $hostFilter = array_keys($this->hosts);
     if ($this->state_type === self::HARD_STATE) {
         $hostStateColumn = 'host_hard_state';
         $hostStateChangeColumn = 'host_last_hard_state_change';
         $serviceStateColumn = 'service_hard_state';
         $serviceStateChangeColumn = 'service_last_hard_state_change';
     } else {
         $hostStateColumn = 'host_state';
         $hostStateChangeColumn = 'host_last_state_change';
         $serviceStateColumn = 'service_state';
         $serviceStateChangeColumn = 'service_last_state_change';
     }
     $filter = Filter::matchAny();
     foreach ($hostFilter as $host) {
         $filter->addFilter(Filter::where('host_name', $host));
     }
     if ($filter->isEmpty()) {
         return $this;
     }
     $hostStatus = $backend->select()->from('hostStatus', array('hostname' => 'host_name', 'last_state_change' => $hostStateChangeColumn, 'in_downtime' => 'host_in_downtime', 'ack' => 'host_acknowledged', 'state' => $hostStateColumn))->applyFilter($filter)->getQuery()->fetchAll();
     $serviceStatus = $backend->select()->from('serviceStatus', array('hostname' => 'host_name', 'service' => 'service_description', 'last_state_change' => $serviceStateChangeColumn, 'in_downtime' => 'service_in_downtime', 'ack' => 'service_acknowledged', 'state' => $serviceStateColumn))->applyFilter($filter)->getQuery()->fetchAll();
     foreach ($serviceStatus as $row) {
         $this->handleDbRow($row);
     }
     foreach ($hostStatus as $row) {
         $this->handleDbRow($row);
     }
     ksort($this->root_nodes);
     Benchmark::measure('Got states for business process ' . $this->getName());
     return $this;
 }