Example #1
0
 private function dispatch($args)
 {
     MvcConfiguration::set('ExecutionContext', 'shell');
     echo Console_Color::convert("\n%P%UWelcome to WP MVC Console!%n%n\n\n");
     $shell_name = 'help';
     if (!empty($args[1])) {
         $shell_name = $args[1];
     }
     $shell_title = MvcInflector::camelize($shell_name);
     $shell_name .= '_shell';
     $shell_class_name = MvcInflector::camelize($shell_name);
     $shell_path = 'shells/' . $shell_name . '.php';
     $shell_exists = $this->file_includer->include_first_app_file_or_core_file($shell_path);
     if (!$shell_exists) {
         echo 'Sorry, a shell named "' . $shell_name . '" couldn\'t be found in any of the MVC plugins.';
         echo "\n";
         echo 'Please make sure a shell class exists in "app/' . $shell_path . '", or execute "./wpmvc" to see a list of available shells.';
         echo "\n";
         die;
     }
     $args = array_slice($args, 2);
     if (empty($args[0])) {
         $args = array('main');
     }
     $shell = new $shell_class_name($args);
     $method = $args[0];
     $args = array_slice($args, 1);
     if ($shell_name != 'help_shell') {
         $shell->out(Console_Color::convert("\n%_[Running " . $shell_title . "::" . $method . "]%n"));
     }
     $shell->{$method}($args);
     if ($shell_name != 'help_shell') {
         $shell->out(Console_Color::convert("\n%_[Complete]%n"));
     }
 }
function dbQuery($sql, $parameters = array())
{
    global $fullSql, $debug;
    $fullSql = dbMakeQuery($sql, $parameters);
    if ($debug) {
        print Console_Color::convert("\nSQL[%y" . $fullSql . "%n] ");
        #echo("\nSQL[".$fullSql."] ");
    }
    /*
    if($this->logFile)
    	$time_start = microtime(true);
    */
    $result = mysql_query($fullSql);
    // sets $this->result
    /*
    if($this->logFile) {
    	$time_end = microtime(true);
    	fwrite($this->logFile, date('Y-m-d H:i:s') . "\n" . $fullSql . "\n" . number_format($time_end - $time_start, 8) . " seconds\n\n");
    }
    */
    if ($result === false && error_reporting() & 1) {
        // aye. this gets triggers on duplicate Contact insert
        //trigger_error('QDB - Error in query: ' . $fullSql . ' : ' . mysql_error(), E_USER_WARNING);
    }
    return $result;
}
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $selector = $input->getArgument('selector');
     $this->application->getController()->restart($selector, function ($message) {
         echo \Console_Color::convert(" %g>>%n ") . $message . "\n";
     });
 }
function print_message($text)
{
    if (isCli()) {
        print Console_Color::convert("%g" . $text . "%n\n", false);
    } else {
        echo '<div class="alert alert-success"><img src="/images/16/tick.png" align="absmiddle"> ' . $text . '</div>';
    }
}
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $selector = $input->getArgument('selector');
     echo "  Archive operation requires all selected containers to be stopped\n";
     echo "  Any running containers will be stopped before archiving\n";
     echo "  Archives will be created in current working directory\n";
     if (readline("Proceed[Y/n]?") != 'n') {
         $this->application->getController()->archive($selector, function ($message) {
             echo \Console_Color::convert(" %g>>%n ") . $message . "\n";
         });
     } else {
         echo "Aborted\n";
     }
 }
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $name = $input->getArgument('name');
     echo "  WARNING!\n";
     echo "  Selected archive must be created on system with same config and storage filesystem layout\n";
     echo "  Otherwise restore operation may damage your system!\n";
     if (readline("Proceed[Y/n]?") != 'n') {
         $this->application->getController()->restore($name, function ($message) {
             echo \Console_Color::convert(" %g>>%n ") . $message . "\n";
         });
     } else {
         echo "Aborted\n";
     }
 }
 /**
  * Send output to the console/terminal/screen
  * @param string $message The content of the message to send to the screen
  * @param array $options Options of the output, "eol" for a new line at the end of the message. "date" to show a timstamp of the message
  * @return void
  */
 function send($message, $options = array('eol' => TRUE, 'date' => TRUE))
 {
     //Check we want a new line
     if ($options['eol'] == TRUE) {
         $message .= PHP_EOL;
     }
     //Check we want a date prefixing the message
     if ($options['date'] == TRUE) {
         $message = '%K[' . date('d/M/Y H:i:s') . ']%n ' . $message;
     }
     //Color parse
     $message = Console_Color::convert($message . '%n');
     //Send to screen
     fwrite(STDOUT, $message);
 }
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if ($selector = $input->getArgument('selector')) {
         $containers = $this->application->getController()->selectContainers($selector);
     } else {
         $containers = $this->application->getController()->getContainers();
     }
     $namelength = Formatter::calculateNamelength($containers) + 1;
     $FORMAT = "%2s %{$namelength}s %6s %8s %12s %12s %12s %18s %10s %10s\n";
     printf($FORMAT, ' ', 'Name', 'Tasks', 'Rss', 'User time', 'System time', 'Uptime', 'IP', 'Upload', 'Download');
     foreach ($containers as $container) {
         $r = array('state' => '', 'name' => '', 'tasks' => 'n/a', 'rss' => 'n/a', 'usertime' => 'n/a', 'systemtime' => 'n/a', 'uptime' => 'n/a', 'ip' => 'n/a', 'upload' => 'n/a', 'download' => 'n/a');
         $r['name'] = $container->getName();
         $state = $container->getState();
         if ($state == 'RUNNING') {
             $r['state'] = \Console_Color::convert(' %g>>%n');
         } else {
             if ($state == 'STOPPED') {
                 $r['state'] = \Console_Color::convert(' %b--%n');
             }
         }
         if ($state == 'RUNNING') {
             $r['tasks'] = count($container->getTasks());
             $r['rss'] = Formatter::formatBytes($container->getRss());
             $r['uptime'] = Formatter::formatTime($container->getUptime());
             $times = $container->getCpuTimes();
             $r['systemtime'] = Formatter::formatTime($times['system']);
             $r['usertime'] = Formatter::formatTime($times['user']);
             $r['ip'] = $container->getIp();
             $traffic = $container->getTraffic();
             $r['upload'] = Formatter::formatBytes($traffic['upload']);
             $r['download'] = Formatter::formatBytes($traffic['download']);
         }
         vprintf($FORMAT, $r);
     }
 }
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if ($selector = $input->getArgument('selector')) {
         $containers = $this->application->getController()->selectContainers($selector);
     } else {
         $containers = $this->application->getController()->getContainers();
     }
     $namelength = Formatter::calculateNamelength($containers) + 1;
     $FORMAT = "%2s %{$namelength}s\n";
     printf($FORMAT, ' ', 'Name');
     foreach ($containers as $container) {
         $r = array('state' => '', 'name' => '');
         $r['name'] = $container->getName();
         $state = $container->getState();
         if ($state == 'RUNNING') {
             $r['state'] = \Console_Color::convert(' %g>>%n');
         } else {
             if ($state == 'STOPPED') {
                 $r['state'] = \Console_Color::convert(' %b--%n');
             }
         }
         vprintf($FORMAT, $r);
     }
 }
Example #10
0
 /**
  * Start containers
  * 
  * @param string $selector Containers selector
  * @param \Closure $console_callback Callback for console output
  */
 public function start($selector, $console_callback = null)
 {
     if ($console_callback == null) {
         $console_callback = function () {
         };
     }
     $containers = $this->selectContainers($selector);
     foreach ($containers as $key => $container) {
         if (!$container->isStopped()) {
             unset($containers[$key]);
         }
     }
     $threads = array();
     $threads_count = $this->config['general']['start_threads'];
     while (!empty($containers) || !empty($threads)) {
         if (count($threads) < $threads_count && !empty($containers)) {
             $container = array_shift($containers);
             $threads[$container->getName()] = array('timestamp' => time(), 'object' => $container);
             if ($this->getConfig('network', 'filtering') == 'on') {
                 $container->enableEbtables();
             }
             $container->start();
             $console_callback("Starting {$container->getName()}");
         }
         foreach ($threads as $name => $properties) {
             if (false !== strpos(file_get_contents($properties['object']->getLogPath()), 'ERROR')) {
                 $console_callback(\Console_Color::convert("%RError occured while starting {$name}. Check {$properties['object']->getLogPath()}%n"));
                 unset($threads[$name]);
                 continue;
             }
             if ($properties['object']->getState() == 'RUNNING') {
                 unset($threads[$name]);
                 $console_callback($name . ' started');
                 continue;
             }
             if ($properties['timestamp'] + $this->config['general']['start_timeout'] < time()) {
                 unset($threads[$name]);
                 $console_callback("Timeout reached while starting {$name}");
             }
         }
         if (!empty($threads)) {
             usleep(500000);
         }
     }
 }
Example #11
0
 /**
  * @param string $text
  * @return text
  */
 public static function yellow($text)
 {
     $oldErrorReportingLevel = error_reporting(error_reporting() & ~E_STRICT);
     $yellow = Console_Color::convert("%y{$text}%n");
     error_reporting($oldErrorReportingLevel);
     return $yellow;
 }
Example #12
0
 /**
  *	Private helper function that will color the content based
  *	on the setting on the current object. 
  *	The coloring is based on the existance of Console_Color or 
  *	the "display" flag in the settings.xml file.
  *
  *	@access private
  *	@return string The colored text
  */
 private function color($str, $type)
 {
     if (!$this->consoleColor || !$this->showColors) {
         return $str;
     }
     switch ($type) {
         case "func":
             return Console_Color::convert("%" . $this->color->func . $str . "%n");
             break;
         case "return":
             return Console_Color::convert("%" . $this->color->return . $str . "%n");
             break;
         case "type":
             return Console_Color::convert("%" . $this->color->type . $str . "%n");
             break;
         case "var":
             return Console_Color::convert("%" . $this->color->var . $str . "%n");
         default:
             return $str;
     }
 }
Example #13
0
 public function testAllTestgroupsNoReload()
 {
     echo "<b>SparqlDbTests</b><br/>\n";
     //prepare
     $parser = new SparqlParser();
     $strLastDataFile = null;
     foreach ($_SESSION['sparqlTestGroups'] as $arGroup) {
         if (isset($arGroup['deact'])) {
             continue;
         }
         //echo count($_SESSION[$arGroup['tests']]) . " tests\n";
         foreach ($_SESSION[$arGroup['tests']] as $name) {
             if (isset($name['type']) && ($name['type'] == 'syntax-negative' || $name['type'] == 'syntax-positive')) {
                 //skip syntax tests; they are run in SparqlParserTests
                 continue;
             }
             $checkfunc = $arGroup['checkfunc'];
             $fileData = null;
             $fileResult = null;
             $fileQuery = null;
             if (is_array($name)) {
                 if (isset($name['data'])) {
                     if (!file_exists(SPARQL_TESTFILES . $name['data'])) {
                         $fileData = 'data/' . $name['data'];
                     } else {
                         $fileData = $name['data'];
                     }
                 }
                 if (!file_exists(SPARQL_TESTFILES . $name['query'])) {
                     $fileQuery = 'query/' . $name['query'] . '.rq';
                 } else {
                     $fileQuery = $name['query'];
                 }
                 if (isset($name['result'])) {
                     if (!file_exists(SPARQL_TESTFILES . $name['result'])) {
                         $fileResult = 'result/' . $name['result'] . '.res';
                     } else {
                         $fileResult = $name['result'];
                     }
                 }
                 if (isset($name['title'])) {
                     $title = $name['title'];
                 } else {
                     $title = $name['query'];
                 }
             } else {
                 $fileData = 'data/' . $name . '.n3';
                 $fileQuery = 'query/' . $name . '.rq';
                 $fileResult = 'result/' . $name . '.res';
                 $title = $name;
             }
             if (in_array($title, $_SESSION['testSparqlDbTestsIgnores'])) {
                 if (isset($GLOBALS['debugTests'])) {
                     echo Console_Color::convert('%y');
                     echo '  ignoring ' . $title . "\n";
                     echo Console_Color::convert('%n');
                 }
                 continue;
             }
             //echo '  ' . $title . "\n";
             $_SESSION['test'] = $title . ' test';
             $e = null;
             if (isset($name['earl:name'])) {
                 //fix some weird issue with simpletest
                 $earlname = $name['earl:name'];
                 $this->signal('earl:name', $earlname);
             }
             if ($fileData != null && $fileData != $strLastDataFile) {
                 //re-use database if not changed
                 list($database, $dbModel) = $this->prepareDatabase();
                 //import statements into database
                 $dbModel->load(SPARQL_TESTFILES . $fileData, 'n3');
                 $strLastDataFile = $fileData;
             }
             $qs = file_get_contents(SPARQL_TESTFILES . $fileQuery);
             if ($fileResult !== null) {
                 $res = file_get_contents(SPARQL_TESTFILES . $fileResult);
                 if (substr($fileResult, -4) == '.srx') {
                     //Sparql XML result
                     $resParser = new SparqlResultParser();
                     $result = $resParser->parse($res);
                 } else {
                     if (substr($fileResult, -4) == '.rdf') {
                         //same format as .ttl, but serialized as xml
                         //rdf xml sorted
                         $resModel = new MemModel();
                         $resModel->load(SPARQL_TESTFILES . $fileResult, 'rdf');
                         $result = SparqlTestHelper::convertModelToResultArray($resModel);
                         unset($resModel);
                         $checkfunc = 'resultCheckSort';
                     } else {
                         if (substr($fileResult, -4) == '.res') {
                             //our own php code
                             unset($result);
                             eval($res);
                         } else {
                             if (substr($fileResult, -4) == '.ttl') {
                                 //N3
                                 $resModel = new MemModel();
                                 $resModel->load(SPARQL_TESTFILES . $fileResult, 'n3');
                                 $result = SparqlTestHelper::convertModelToResultArray($resModel);
                                 unset($resModel);
                             } else {
                                 throw new Exception('Unknown result format in ' . $fileResult);
                             }
                         }
                     }
                 }
             }
             try {
                 $q = $parser->parse($qs);
             } catch (Exception $e) {
                 //normal query failed to be parsed
                 $this->assertTrue(false, 'Query failed to be parsed');
                 if (!isset($GLOBALS['debugTests'])) {
                     //echo '  ' . $title . "\n";
                 } else {
                     echo Console_Color::convert('%RTest failed: ' . $title . "%n\n");
                     if (isset($e)) {
                         echo $e->getMessage() . "\n";
                         //var_dump($e);
                     }
                     echo $strQuery . "\n";
                     die;
                 }
             }
             try {
                 $t = $dbModel->sparqlQuery($qs);
                 if ($t instanceof MemModel) {
                     $bOk = $t->equals($result);
                 } else {
                     $bOk = SparqlTestHelper::$checkfunc($t, $result);
                 }
                 $this->assertTrue($bOk);
             } catch (Exception $e) {
                 $bOk = false;
                 $t = null;
                 //an exception is an error
                 if (isset($GLOBALS['debugTests'])) {
                     var_dump($e->getMessage());
                 }
                 $this->assertTrue(false);
             }
             if (!$bOk) {
                 if (!isset($GLOBALS['debugTests'])) {
                     //echo '  ' . $title . "\n";
                 } else {
                     echo Console_Color::convert('%RTest failed: ' . $title . "%n\n");
                     if ($e != null) {
                         echo get_class($e) . ': ' . $e->getMessage() . "\n";
                     }
                     echo ' Data: ' . $fileData . "\n";
                     echo 'Query string: ' . $qs . "\n";
                     echo "Expected:\n";
                     echo Console_Color::convert('%p');
                     var_dump($result);
                     echo Console_Color::convert('%n');
                     echo "Result:\n";
                     echo Console_Color::convert('%r');
                     var_dump($t);
                     echo Console_Color::convert('%n');
                     //var_dump($q);
                     die;
                 }
             }
             /**/
         }
         //            echo $arGroup['title'] . " done\n";
     }
 }
 /**
  *   Runs a parser test
  */
 protected function runQueryParseTest($strQuery, $parser, $strType, $title)
 {
     $bException = false;
     try {
         $parser->parse($strQuery);
     } catch (Exception $e) {
         $bException = true;
     }
     if ($strType == 'syntax-negative') {
         $this->assertTrue($bException, 'Query should fail to be parsed.');
         $bOk = $bException == true;
     } else {
         if ($strType == 'syntax-positive') {
             $this->assertFalse($bException, 'Query should get parsed.');
             $bOk = $bException == false;
         }
     }
     if (!$bOk) {
         if (isset($GLOBALS['debugTests']) && $GLOBALS['debugTests']) {
             echo Console_Color::convert('%RTest failed: ' . $title . "%n\n");
             if (isset($e)) {
                 echo $e->getMessage() . "\n";
                 //var_dump($e);
             }
             echo $strQuery . "\n";
             die;
         }
     }
 }
Example #15
0
 /**
  * 強調文字表示
  *
  * @param string $str   文字列
  * @param string $color 色
  *
  * @return string
  * @internal CLIとHTMLで表示を変えています
  */
 public function printStrong($str, $color = 'b')
 {
     if ($this->_config['cli']) {
         return Console_Color::convert("%{$color}{$str}%n");
     } else {
         return '<strong>' . $str . '</strong>';
     }
 }
Example #16
0
 /**
  * Show documentation for a shell.
  * Usage:
  * wpmvc Help Shell <shell_name> [command_name]
  * wpmvc Help Shell Generate
  * wpmvc Help Shell Generate Scaffold
  * @param mixed $args
  * @return null 
  */
 public function shell($args)
 {
     list($name, $method) = $args;
     if (empty($name)) {
         $this->out('No shell given');
         return;
     }
     try {
         $shell = $this->get_shell_meta($name);
     } catch (Exception $ex) {
         $this->out('Error:');
         $this->out($ex->getMessage());
         return;
     }
     $this->nl();
     $this->out(Console_Color::convert('%UShells > %n%U%9' . $shell->title . '%n'));
     $this->nl();
     $this->out($shell->doc);
     $this->nl(2);
     $this->out('Commands:');
     $table = new Console_Table(CONSOLE_TABLE_ALIGN_LEFT, ' ', 1, null, true);
     if ($method == 'default') {
         $method = '(default)';
     }
     if (!empty($method) && !empty($shell->methods[$method])) {
         $table->addRow(array(Console_Color::convert('%9' . $method . '%n'), $shell->methods[$method]));
     } else {
         foreach ($shell->methods as $method => $doc) {
             $table->addRow(array(Console_Color::convert('%9' . $method . '%n'), $doc));
             $table->addSeparator();
         }
     }
     $this->out($table->getTable());
 }
Example #17
0
function print_message($text)
{
    if (isCli()) {
        print Console_Color::convert("%g" . $text . "%n\n", false);
    } else {
        echo '
    <div class="alert alert-info">
      <button type="button" class="close" data-dismiss="alert">&times;</button>
      ' . $text . '
    </div>';
    }
}
 /**
  * Returns the character length of a string.
  *
  * @param string $str A multibyte or singlebyte string.
  *
  * @return integer  The string length.
  */
 function _strlen($str)
 {
     static $mbstring;
     // Strip ANSI color codes if requested.
     if ($this->_ansiColor) {
         $str = Console_Color::strip($str);
     }
     // Cache expensive function_exists() calls.
     if (!isset($mbstring)) {
         $mbstring = function_exists('mb_strwidth');
     }
     if ($mbstring) {
         return mb_strwidth($str, $this->_charset);
     }
     return strlen($str);
 }
Example #19
0
 /**
  * Runs tests based on the given TestSuite object.
  *
  * @param TestSuite $suite
  */
 public function run($suite)
 {
     $reporter = new MultipleReporter();
     $reporter->attachReporter($this->decorateReporter(new TextReporter()));
     if ($this->config->logsResultsInJUnitXML) {
         if (!$this->config->logsResultsInJUnitXMLInRealtime) {
             $xmlWriter = new Stagehand_TestRunner_JUnitXMLWriter_JUnitXMLDOMWriter(array($this, 'writeJUnitXMLToFile'));
         } else {
             $xmlWriter = $this->junitXMLStreamWriter(array($this, 'writeJUnitXMLToFile'));
         }
         $junitXMLReporter = new $this->junitXMLReporterClass($this->config);
         $junitXMLReporter->setXMLWriter($xmlWriter);
         $junitXMLReporter->setTestSuite($suite);
         $junitXMLReporter->setConfig($this->config);
         $reporter->attachReporter($this->decorateReporter($junitXMLReporter));
     }
     ob_start();
     $suite->run($reporter);
     $output = ob_get_contents();
     ob_end_clean();
     if ($this->config->logsResultsInJUnitXML) {
         if (is_resource($this->junitXMLFileHandle)) {
             fclose($this->junitXMLFileHandle);
         }
     }
     if ($this->config->usesGrowl) {
         if (preg_match('/^(OK.+)/ms', $output, $matches)) {
             $this->notification->name = 'Green';
             $this->notification->description = $matches[1];
         } elseif (preg_match('/^(FAILURES.+)/ms', $output, $matches)) {
             $this->notification->name = 'Red';
             $this->notification->description = $matches[1];
         }
     }
     if ($this->config->colors) {
         print Console_Color::convert(preg_replace(array('/^(OK.+)/ms', '/^(FAILURES!!!.+)/ms', '/^(\\d+\\)\\s)(.+at \\[.+\\]$\\s+in .+)$/m', '/^(Exception \\d+!)/m', '/^(Unexpected exception of type \\[.+\\] with message \\[.+\\] in \\[.+\\]$\\s+in .+)$/m'), array('%g$1%n', '%r$1%n', "\$1%r\$2%n", '%p$1%n', '%p$1%n'), Console_Color::escape($output)));
     } else {
         print $output;
     }
 }
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $options = $input->getOptions();
     $ask = function ($what, $default = null, $values = array()) {
         while (true) {
             $q = "\n" . $what;
             if ($default !== null) {
                 $q .= " [{$default}]: ";
             } else {
                 $q .= ": ";
             }
             $v = readline($q);
             if (!empty($values)) {
                 if (in_array($v, $values)) {
                     return $v;
                 }
             } else {
                 if ($v !== '') {
                     return $v;
                 }
             }
             if ($default !== null) {
                 return $default;
             }
         }
     };
     foreach ($options as $key => &$value) {
         if (!$value) {
             switch ($key) {
                 case 'ip':
                     $ip = $this->application->getController()->findFreeIp();
                     if (!$ip) {
                         throw new \Exception('No free ip left');
                     }
                     $options[$key] = $ask('IP', $ip);
                     break;
                 case 'template':
                     $default = $this->application->getController()->getConfig('general', 'default_template');
                     $templates = $this->application->getController()->getTemplates();
                     $templates_rev = array_flip($templates);
                     $what = "Select template\n";
                     foreach ($templates as $key => $value) {
                         $what .= " {$key}) {$value}\n";
                     }
                     $what .= 'Template';
                     $default_idx = isset($templates_rev[$default]) ? $templates_rev[$default] : null;
                     $i = (int) $ask($what, $default_idx, $templates_rev);
                     $options[$key] = $templates[$i];
                     break;
                 case 'name':
                     $options[$key] = $ask('Name');
                     break;
                 default:
                     break;
             }
         }
     }
     $this->application->getController()->create($options, function ($message) {
         echo \Console_Color::convert(" %g>>%n ") . $message . "\n";
     });
 }
Example #21
0
 public function ansi_console_colors($content)
 {
     return Console_Color::convert($content);
 }
Example #22
0
function poll_sensor($device, $class, $unit)
{
    global $config, $agent_sensors, $ipmi_sensors;
    $sql = "SELECT *, `sensors`.`sensor_id` AS `sensor_id`";
    $sql .= " FROM  `sensors`";
    $sql .= " LEFT JOIN  `sensors-state` ON  `sensors`.sensor_id =  `sensors-state`.sensor_id";
    $sql .= " WHERE `sensor_class` = ? AND `device_id` = ?";
    foreach (dbFetchRows($sql, array($class, $device['device_id'])) as $sensor) {
        echo "Checking (" . $sensor['poller_type'] . ") {$class} " . $sensor['sensor_descr'] . " ";
        if ($sensor['poller_type'] == "snmp") {
            #      if ($class == "temperature" && $device['os'] == "papouch")
            if ($class == "temperature") {
                for ($i = 0; $i < 5; $i++) {
                    if ($debug) {
                        echo "Attempt {$i} ";
                    }
                    $sensor_value = preg_replace("/[^0-9.]/", "", snmp_get($device, $sensor['sensor_oid'], "-OUqnv", "SNMPv2-MIB"));
                    if (is_numeric($sensor_value) && $sensor_value != 9999) {
                        break;
                    }
                    # TME sometimes sends 999.9 when it is right in the middle of an update;
                    sleep(1);
                    # Give the TME some time to reset
                }
            } else {
                $sensor_value = trim(str_replace("\"", "", snmp_get($device, $sensor['sensor_oid'], "-OUqnv", "SNMPv2-MIB")));
            }
        } else {
            if ($sensor['poller_type'] == "agent") {
                if (isset($agent_sensors)) {
                    $sensor_value = $agent_sensors[$class][$sensor['sensor_type']][$sensor['sensor_index']]['current'];
                    # FIXME pass unit?
                } else {
                    echo "no agent data!\n";
                    continue;
                }
            } else {
                if ($sensor['poller_type'] == "ipmi") {
                    if (isset($ipmi_sensors)) {
                        $sensor_value = $ipmi_sensors[$class][$sensor['sensor_type']][$sensor['sensor_index']]['current'];
                        $unit = $ipmi_sensors[$class][$sensor['sensor_type']][$sensor['sensor_index']]['unit'];
                    } else {
                        echo "no IPMI data!\n";
                        continue;
                    }
                } else {
                    echo "unknown poller type!\n";
                    continue;
                }
            }
        }
        if ($sensor_value == -32768) {
            echo "Invalid (-32768) ";
            $sensor_value = 0;
        }
        if ($sensor['sensor_divisor']) {
            $sensor_value = $sensor_value / $sensor['sensor_divisor'];
        }
        if ($sensor['sensor_multiplier']) {
            $sensor_value = $sensor_value * $sensor['sensor_multiplier'];
        }
        $rrd_file = get_sensor_rrd($device, $sensor);
        if (!is_file($rrd_file)) {
            rrdtool_create($rrd_file, "--step 300 \\\n      DS:sensor:GAUGE:600:-20000:U " . $config['rrd_rra']);
            //DS:sensor:GAUGE:600:-20000:20000 ".$config['rrd_rra']);
        }
        echo "{$sensor_value} {$unit} ";
        // FIXME also warn when crossing WARN level!!
        if ($sensor['sensor_ignore'] != "1") {
            if ($sensor['sensor_limit_low'] != "" && $sensor['sensor_value'] >= $sensor['sensor_limit_low'] && $sensor_value < $sensor['sensor_limit_low']) {
                $msg = ucfirst($class) . " Alarm: " . $device['hostname'] . " " . $sensor['sensor_descr'] . " is under threshold: " . $sensor_value . "{$unit} (< " . $sensor['sensor_limit_low'] . "{$unit})";
                notify($device, ucfirst($class) . " Alarm: " . $device['hostname'] . " " . $sensor['sensor_descr'], $msg);
                print Console_Color::convert("[%rAlerting for " . $device['hostname'] . " " . $sensor['sensor_descr'] . "%n\n");
                log_event(ucfirst($class) . ' ' . $sensor['sensor_descr'] . " under threshold: " . $sensor_value . " {$unit} (< " . $sensor['sensor_limit_low'] . " {$unit})", $device, $class, $sensor['sensor_id']);
            } else {
                if ($sensor['sensor_limit'] != "" && $sensor['sensor_value'] <= $sensor['sensor_limit'] && $sensor_value > $sensor['sensor_limit']) {
                    $msg = ucfirst($class) . " Alarm: " . $device['hostname'] . " " . $sensor['sensor_descr'] . " is over threshold: " . $sensor_value . "{$unit} (> " . $sensor['sensor_limit'] . "{$unit})";
                    notify($device, ucfirst($class) . " Alarm: " . $device['hostname'] . " " . $sensor['sensor_descr'], $msg);
                    print Console_Color::convert("[%rAlerting for " . $device['hostname'] . " " . $sensor['sensor_descr'] . "%n\n");
                    log_event(ucfirst($class) . ' ' . $sensor['sensor_descr'] . " above threshold: " . $sensor_value . " {$unit} (> " . $sensor['sensor_limit'] . " {$unit})", $device, $class, $sensor['sensor_id']);
                }
            }
        } else {
            print Console_Color::convert("[%ySensor Ignored%n]");
        }
        echo "\n";
        // Update RRD
        rrdtool_update($rrd_file, "N:{$sensor_value}");
        // Update SQL State
        if (is_numeric($sensor['sensor_polled'])) {
            dbUpdate(array('sensor_value' => $sensor_value, 'sensor_polled' => time()), 'sensors-state', '`sensor_id` = ?', array($sensor['sensor_id']));
        } else {
            dbInsert(array('sensor_id' => $sensor['sensor_id'], 'sensor_value' => $sensor_value, 'sensor_polled' => time()), 'sensors-state');
        }
    }
}
Example #23
0
 public function write_target_files()
 {
     $this->out("\n" . 'Scan Complete. Preparing to write to target...');
     $this->out('Changing directory to ' . $this->cfg->get('TargetDir') . "/\n");
     chdir($this->cfg->get('TargetDir'));
     $pattern = preg_quote('#' . $this->get_file_sep('-0-') . '#i');
     $pattern = str_replace('-0-', '(.*)', $pattern);
     $files = preg_split($pattern, $this->buf, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
     $alias =& $files;
     foreach ($alias as $file) {
         $file = $this->get_path($file);
         $dirname = dirname($file);
         if ($dirname != '.' && !is_dir($dirname)) {
             $this->out('Creating folder ' . $this->cfg->get('TargetDir') . '/' . $dirname);
             mkdir($dirname);
         }
         $data = current($alias);
         next($alias);
         #            $this->out('Writing obfuscated code to ' . $this->cfg->get('TargetDir') . '/' . $file);
         file_put_contents($file, $data);
     }
     require_once 'Console/Color.php';
     $this->out('');
     $this->out(count($this->tree_hier) . ' file(s) obfuscated with no errors.');
     $this->out(round($this->buf_get_len() / 1024) . ' KB of output written to ' . Console_Color::convert('%9' . $this->cfg->get('TargetDir') . '%n') . '/');
     $this->out('Please execute scripts to ensure they work as intended.');
 }
        $tbl->setHeaders(array('Port name', 'Status', 'IPv4 Address', 'Speed In', 'Speed Out', 'Packets In', 'Packets Out', 'Speed', 'Duplex', 'Type', 'MAC Address', 'MTU'));
        foreach (dbFetchRows("SELECT * FROM `ports` WHERE `device_id` = ?", array($options['d'])) as $port) {
            if ($port['ifOperStatus'] == 'up') {
                $port['in_rate'] = $port['ifInOctets_rate'] * 8;
                $port['out_rate'] = $port['ifOutOctets_rate'] * 8;
                $in_perc = @round($port['in_rate'] / $port['ifSpeed'] * 100);
                $out_perc = @round($port['in_rate'] / $port['ifSpeed'] * 100);
            }
            if ($port['ifSpeed']) {
                $port_speed = humanspeed($port['ifSpeed']);
            }
            if ($port[ifDuplex] != "unknown") {
                $port_duplex = $port['ifDuplex'];
            }
            if ($port['ifPhysAddress'] && $port['ifPhysAddress'] != "") {
                $port_mac = formatMac($port['ifPhysAddress']);
            }
            if ($port['ifMtu'] && $port['ifMtu'] != "") {
                $port_mtu = $port['ifMtu'];
            }
            $tbl->addRow(array($port['ifDescr'], $port['ifOperStatus'], '', formatRates($port['in_rate']), formatRates($port['out_rate']), format_bi($port['ifInUcastPkts_rate']) . 'pps', format_bi($port['ifOutUcastPkts_rate']) . 'pps', $port_speed, $port_duplex, '', $port_mac, $port_mtu));
        }
        echo $tbl->getTable();
    } else {
        echo $options['list'];
        echo "Usage of console-ui.php:\n\n  -l      What log type we want to see:\n            eventlog = Event log messages\n            syslog = Syslog messages\n\n  -d      Specify the device id to filter results\n\n  --list   What to list\n            devices = list devices and device id's\n\n  --device-stats      Lists the port statistics for a given device\n\n  Examples:\n           #1 php console-ui.php -l eventlog -d 1\n           #2 php console-ui.php --list=devices\n\n";
        exit;
    }
    echo Console_Color::convert("%rLast update at " . date("Y-m-d h:i:s") . "%n\n\n");
    sleep(5);
}
            // parse all remaining args
            if (is_numeric($arg)) {
                $port = $arg;
            } elseif (preg_match('/(' . implode("|", $config['snmp']['transports']) . ')/i', $arg)) {
                $transport = $arg;
            } elseif (preg_match('/^(v1|v2c)$/i', $arg)) {
                $snmpver = $arg;
            }
        }
        if ($community) {
            $config['snmp']['community'] = array($community);
        }
        $device_id = addHost($host, $snmpver, $port, $transport);
    }
    if ($snmpver) {
        $snmpversions[] = $snmpver;
    } else {
        $snmpversions = array('v2c', 'v3', 'v1');
    }
    while (!$device_id && count($snmpversions)) {
        $snmpver = array_shift($snmpversions);
        $device_id = addHost($host, $snmpver, $port, $transport);
    }
    if ($device_id) {
        $device = device_by_id_cache($device_id);
        echo "Added device " . $device['hostname'] . " (" . $device_id . ")\n";
        exit;
    }
}
print Console_Color::convert("\n" . $config['project_name_version'] . " Add Host Tool\n\nUsage (SNMPv1/2c): ./addhost.php <%Whostname%n> [community] [v1|v2c] [port] [" . implode("|", $config['snmp']['transports']) . "]\nUsage (SNMPv3)   :  Config Defaults : ./addhost.php <%Whostname%n> any v3 [user] [port] [" . implode("|", $config['snmp']['transports']) . "]\n                   No Auth, No Priv : ./addhost.php <%Whostname%n> nanp v3 [user] [port] [" . implode("|", $config['snmp']['transports']) . "]\n                      Auth, No Priv : ./addhost.php <%Whostname%n> anp v3 <user> <password> [md5|sha] [port] [" . implode("|", $config['snmp']['transports']) . "]\n                      Auth,    Priv : ./addhost.php <%Whostname%n> ap v3 <user> <password> <enckey> [md5|sha] [aes|dsa] [port] [" . implode("|", $config['snmp']['transports']) . "]\n%rRemember to run discovery for the host afterwards.%n\n\n");
Example #26
0
<?php

/**
 * @version     $Id$
 * @package     Koowa_Tests
 * @copyright   Copyright (C) 2007 - 2008 Joomlatools. All rights reserved.
 * @license     GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
 * @link        http://www.koowa.org
 */
echo Console_Color::convert(PHP_EOL . '%YKoowa Unit Testing' . PHP_EOL . '------------------%n' . PHP_EOL);
Example #27
0
 /**
  * Returns the character length of a string.
  *
  * @param string $str A multibyte or singlebyte string.
  *
  * @return integer  The string length.
  */
 function _strlen($str)
 {
     static $mbstring, $utf8;
     // Strip ANSI color codes if requested.
     if ($this->_ansiColor) {
         include_once 'Console/Color.php';
         $str = Console_Color::strip($str);
     }
     // Cache expensive function_exists() calls.
     if (!isset($mbstring)) {
         $mbstring = function_exists('mb_strlen');
     }
     if (!isset($utf8)) {
         $utf8 = function_exists('utf8_decode');
     }
     if ($utf8 && ($this->_charset == strtolower('utf-8') || $this->_charset == strtolower('utf8'))) {
         return strlen(utf8_decode($str));
     }
     if ($mbstring) {
         return mb_strlen($str, $this->_charset);
     }
     return strlen($str);
 }
 /**
  * @param boolean $specs
  */
 public function output($specs = false)
 {
     $output = preg_replace(array('/(\\x0d|\\x0a|\\x0d\\x0a){3,}/', '/^(  -)(.+)/m'), array("\n\n", '$1 $2'), $this->toString($specs));
     if ($this->color) {
         $failuresCount = $this->_result->countFailures();
         $deliberateFailuresCount = $this->_result->countDeliberateFailures();
         $errorsCount = $this->_result->countErrors();
         $exceptionsCount = $this->_result->countExceptions();
         $pendingsCount = $this->_result->countPending();
         if ($failuresCount + $deliberateFailuresCount + $errorsCount + $exceptionsCount + $pendingsCount == 0) {
             $colorLabel = 'green';
         } elseif ($pendingsCount && $failuresCount + $deliberateFailuresCount + $errorsCount + $exceptionsCount == 0) {
             $colorLabel = 'yellow';
         } else {
             $colorLabel = 'red';
         }
         $oldErrorReportingLevel = error_reporting(error_reporting() & ~E_STRICT);
         $output = preg_replace(array('/^(\\d+ examples?.*)/m', '/^(  -)(.+)( \\(ERROR|EXCEPTION\\))/m', '/^(  -)(.+)( \\(FAIL\\))/m', '/^(  -)(.+)( \\(DELIBERATEFAIL\\))/m', '/^(  -)(.+)( \\(PENDING\\))/m', '/^(  -)(.+)/m', '/(\\d+\\)\\s+)(.+ (?:ERROR|EXCEPTION)\\s+.+)/', '/(\\d+\\)\\s+)(.+ FAILED\\s+.+)/', '/(\\d+\\)\\s+)(.+ PENDING\\s+.+)/', '/^((?:Errors|Exceptions):)/m', '/^(Failures:)/m', '/^(Pending:)/m'), array(Stagehand_TestRunner_Coloring::$colorLabel('$1'), Stagehand_TestRunner_Coloring::magenta('$1$2$3'), Stagehand_TestRunner_Coloring::red('$1$2$3'), Stagehand_TestRunner_Coloring::red('$1$2$3'), Stagehand_TestRunner_Coloring::yellow('$1$2$3'), Stagehand_TestRunner_Coloring::green('$1$2$3'), '$1' . Stagehand_TestRunner_Coloring::magenta('$2'), '$1' . Stagehand_TestRunner_Coloring::red('$2'), '$1' . Stagehand_TestRunner_Coloring::yellow('$2'), Stagehand_TestRunner_Coloring::magenta('$1'), Stagehand_TestRunner_Coloring::red('$1'), Stagehand_TestRunner_Coloring::yellow('$1')), Console_Color::escape($output));
         error_reporting($oldErrorReportingLevel);
     }
     print $output;
 }
Example #29
0
 /**
  * Converts colorcodes in the format %y (for yellow) into ansi-control
  * codes. The conversion table is: ('bold' meaning 'light' on some
  * terminals). It's almost the same conversion table irssi uses.
  * <pre> 
  *                  text      text            background
  *      ------------------------------------------------
  *      %k %K %0    black     dark grey       black
  *      %r %R %1    red       bold red        red
  *      %g %G %2    green     bold green      green
  *      %y %Y %3    yellow    bold yellow     yellow
  *      %b %B %4    blue      bold blue       blue
  *      %m %M %5    magenta   bold magenta    magenta
  *      %p %P       magenta (think: purple)
  *      %c %C %6    cyan      bold cyan       cyan
  *      %w %W %7    white     bold white      white
  *
  *      %F     Blinking, Flashing
  *      %U     Underline
  *      %8     Reverse
  *      %_,%9  Bold
  *
  *      %n     Resets the color
  *      %%     A single %
  * </pre>
  * First param is the string to convert, second is an optional flag if
  * colors should be used. It defaults to true, if set to false, the
  * colorcodes will just be removed (And %% will be transformed into %)
  *
  * @param string $string  String to convert
  * @param bool   $colored Should the string be colored?
  *
  * @access public
  * @return string
  */
 function convert($string, $colored = true)
 {
     static $conversions = array('%y' => array('color' => 'yellow'), '%g' => array('color' => 'green'), '%b' => array('color' => 'blue'), '%r' => array('color' => 'red'), '%p' => array('color' => 'purple'), '%m' => array('color' => 'purple'), '%c' => array('color' => 'cyan'), '%w' => array('color' => 'grey'), '%k' => array('color' => 'black'), '%n' => array('color' => 'reset'), '%Y' => array('color' => 'yellow', 'style' => 'light'), '%G' => array('color' => 'green', 'style' => 'light'), '%B' => array('color' => 'blue', 'style' => 'light'), '%R' => array('color' => 'red', 'style' => 'light'), '%P' => array('color' => 'purple', 'style' => 'light'), '%M' => array('color' => 'purple', 'style' => 'light'), '%C' => array('color' => 'cyan', 'style' => 'light'), '%W' => array('color' => 'grey', 'style' => 'light'), '%K' => array('color' => 'black', 'style' => 'light'), '%N' => array('color' => 'reset', 'style' => 'light'), '%3' => array('background' => 'yellow'), '%2' => array('background' => 'green'), '%4' => array('background' => 'blue'), '%1' => array('background' => 'red'), '%5' => array('background' => 'purple'), '%6' => array('background' => 'cyan'), '%7' => array('background' => 'grey'), '%0' => array('background' => 'black'), '%F' => array('style' => 'blink'), '%U' => array('style' => 'underline'), '%8' => array('style' => 'inverse'), '%9' => array('style' => 'bold'), '%_' => array('style' => 'bold'));
     if ($colored) {
         $string = str_replace('%%', '% ', $string);
         foreach ($conversions as $key => $value) {
             $string = str_replace($key, Console_Color::color($value), $string);
         }
         $string = str_replace('% ', '%', $string);
     } else {
         $string = preg_replace('/%((%)|.)/', '$2', $string);
     }
     return $string;
 }
/**
 * Generates an rrd database at $filename using $options
 *
 * @param string filename
 * @param string options
 */
function rrdtool_create($filename, $options)
{
    global $config, $debug;
    if ($config['norrd']) {
        print Console_Color::convert("[%gRRD Disabled%n] ", false);
    } else {
        $command = $config['rrdtool'] . " create {$filename} {$options}";
    }
    if ($debug) {
        print Console_Color::convert("RRD[%g" . $command . "%n] ");
    }
    return shell_exec($command);
}