Exemplo n.º 1
0
 /**
  * @param array $router
  * @param string $path
  * @return array
  */
 private function _dispatch_to_method($router, $path)
 {
     if (!isset($router[$path])) {
         return ['errno' => Da\Sys_Router::ERRNO_NOT_FOUND, 'data' => 'path [' . $path . '] not exists.'];
     }
     $rules = $router[$path];
     $count = count($rules);
     $http_method = 'get';
     if ($count > 2) {
         $http_method = $rules[2];
         if (strtolower($http_method) == 'post' && empty($_POST)) {
             return ['errno' => Da\Sys_Router::ERRNO_NOT_FOUND, 'data' => 'ONLY SUPPORT POST FOR URL:' . $path . ', but got empty Post vars.'];
         }
     }
     $method = array_slice($rules, 0, 2);
     if (!is_callable($method)) {
         return ['errno' => Da\Sys_Router::ERRNO_NOT_FOUND, 'data' => 'method ' . json_encode($method) . ' not exists'];
     }
     $this->_carry_current_url_path();
     $this->_current_url_info['url_path'] = self::current_url_path();
     $this->_current_url_info['rule'] = $rules;
     foreach ($this->_pre_route_hooks as $_hook) {
         if (is_callable($_hook)) {
             call_user_func($_hook);
         }
     }
     try {
         $result = call_user_func($method);
     } catch (Exception $ex) {
         \Lib_Log::error('Runtime error errno: [%d], msg: [%s]', [$ex->getCode(), $ex->getMessage()]);
         return ['errno' => Da\Sys_Router::ERRNO_SERVER_ERR, 'data' => 'something error!'];
     }
     return ['errno' => 200, 'data' => 'REUQEST OK!'];
 }
Exemplo n.º 2
0
 /**
  * @return array The return value should include 'errno' and 'data'
  */
 function dispatch()
 {
     $parse_url = $this->parse_url();
     if ($parse_url['errno'] != self::ERRNO_OK) {
         return $parse_url;
     }
     $url_piece = $parse_url['data'];
     $router = call_user_func($this->_router, $url_piece);
     if (isset($router['errno']) && $router['errno'] === self::ERRNO_OK) {
         return ['errno' => self::ERRNO_OK, 'data' => $router];
     } elseif (isset($router['errno'])) {
         switch ($router['errno']) {
             case self::ERRNO_FORBIDDEN:
                 \Lib_Log::info('forbidden page! url:[%s] case:[%s]', [json_encode($parse_url), json_encode($router)]);
                 return ['errno' => self::ERRNO_FORBIDDEN, 'data' => 'You cannot visit this page!'];
             case self::ERRNO_SERVER_ERR:
                 \Lib_Log::error('page err! url:[%s] case:[%s]', [json_encode($parse_url), json_encode($router)]);
                 return ['errno' => self::ERRNO_SERVER_ERR, 'data' => 'Something wrong!'];
             case self::ERRNO_NOT_FOUND:
             default:
                 \Lib_Log::notice('page not found! url:[%s] case:[%s]', [json_encode($parse_url), json_encode($router)]);
                 return ['errno' => self::ERRNO_NOT_FOUND, 'data' => 'PAGE NOT FOUND!'];
         }
     } else {
         \Lib_Log::notice('page not found! url:[%s] case:[%s]', [json_encode($parse_url), json_encode($router)]);
         return ['errno' => self::ERRNO_FORBIDDEN, 'data' => 'PAGE NOT FOUND!'];
     }
 }
Exemplo n.º 3
0
 /**
  * 获取实例的方法
  * @return array
  */
 public static function get_instance()
 {
     if (is_null(self::$_instance)) {
         $class = __CLASS__;
         self::$_instance = new $class();
     }
     return self::$_instance;
 }
Exemplo n.º 4
0
 /**
  * @param array
  * @return array
  */
 static function process_result($result)
 {
     if ($result['errno'] !== 0) {
         Lib_Log::error("Redis: get result failed! result: %s", json_encode($result));
         return Lib_Helper::get_err_struct(Const_Err_DataAccess::ERR_GET_CARD, 'get card failed! result:' . json_encode($result));
     }
     return Lib_Helper::get_return_struct($result['data']);
 }
Exemplo n.º 5
0
 /**
  * init the log manager
  */
 private function _init_log()
 {
     $config = Sys_Config::config('log/base');
     if ($config) {
         $this->_configure['path']['log'] = isset($config['path']) ? $config['path'] : 'logs';
         $config['path'] = self::log_path();
     } else {
         $config = [];
     }
     \Lib_Log::get_instance()->init($config);
 }
Exemplo n.º 6
0
 /**
  * @return array
  */
 static function module_info()
 {
     $modules_info = new Model_ModulesInfo();
     $module_info = $modules_info->get_module_by_indentify(self::indentify());
     if ($module_info['errno'] !== Const_Err_Base::ERR_OK) {
         Lib_Log::error(__METHOD__ . ' faild! cause: ' . json_encode($module_info['data']));
         self::$module_id = self::MODULE_UNREG_ID;
         return Lib_Helper::get_err_struct(Const_Err_Db::ERR_GET_DATA_FAIL, '获取模块失败', __FILE__, __LINE__);
     }
     $module_info = $module_info['data'];
     if (empty($module_info)) {
         self::$module_id = self::MODULE_UNREG_ID;
         return Lib_Helper::get_err_struct(Const_Err_DataAccess::ERR_MODULE_UNREG, '模块未注册', __FILE__, __LINE__);
     }
     self::$module_id = $module_info['_id'];
     return ['errno' => Const_Err_Base::ERR_OK, 'data' => $module_info];
 }
Exemplo n.º 7
0
 /**
  * @param int $id
  * @return $this|null
  */
 function set_current_ap($id)
 {
     if (isset($this->_ap_list[$id])) {
         $this->_current_ap_id = $id;
         $this->_current_ap = $this->_ap_list[$id];
     } else {
         $ap_info = Module_AccessPoint_Ap::get_ap($id);
         if ($ap_info['errno'] !== Const_Err_Base::ERR_OK) {
             Lib_Log::notice('Get ap faild! Result: %s', Lib_Helper::format_err_struct($ap_info));
             $this->_current_ap_id = null;
             $this->_current_ap = null;
             return null;
         }
         $ap_info = $ap_info['data'];
         $this->set_current_ap_info($id, $ap_info);
     }
     return $this;
 }
Exemplo n.º 8
0
 /**
  * @param string $hook_type
  * @param string $hook_name
  * @return null|array
  */
 function get_hook($hook_type, $hook_name)
 {
     if (!$this->hook_exists($hook_type, $hook_name)) {
         return null;
     }
     $hook = $this->_hooks[$hook_type][$hook_name];
     if (!isset($hook[1])) {
         Lib_Log::notice("Hook: [%s.%s] [%s] not has run_once flag", [strval($hook_type), $hook_name, var_export($hook[1], true)]);
         unset($this->_hooks[$hook_type][$hook_name]);
         return null;
     }
     if (!is_callable($hook[0])) {
         Lib_Log::notice("Hook: [%s.%s] [%s] not callable", [strval($hook_type), $hook_name, json_encode($hook[0])]);
         unset($this->_hooks[$hook_type][$hook_name]);
         return null;
     }
     return $hook;
 }
Exemplo n.º 9
0
 /**
  * 信号处理函数
  * @param number $signo
  * @param number $pid
  * @param number $status
  * @return boolean
  */
 public function childSignalHandler($signo, $pid = null, $status = null)
 {
     //If no pid is provided, that means we're getting the signal from the system.  Let's figure out
     //which child process ended
     if (!$pid) {
         $pid = pcntl_waitpid(-1, $status, WNOHANG);
     }
     //Make sure we get all of the exited children
     while ($pid > 0) {
         if ($pid && isset($this->currentJobs[$pid])) {
             $exitCode = pcntl_wexitstatus($status);
             if ($exitCode != 0) {
                 Lib_Log::info("{$pid} exited with status " . $exitCode);
             }
             unset($this->currentJobs[$pid]);
         } else {
             if ($pid) {
                 //Oh no, our job has finished before this parent process could even note that it had been launched!
                 //Let's make note of it and handle it when the parent process is ready for it
                 Lib_Log::info("..... Adding {$pid} to the signal queue .....");
                 $this->signalQueue[$pid] = $status;
             }
         }
         $pid = pcntl_waitpid(-1, $status, WNOHANG);
     }
     return true;
 }
Exemplo n.º 10
0
 /**
  * @param string
  * @param null|string
  * @return array|bool
  * @throws \Exception
  */
 public function get_config($str, $path = null)
 {
     $path_array = explode('/', $str);
     if (!isset($path_array[0])) {
         return false;
     }
     $file = '';
     $filepath = '';
     $section = array_pop($path_array);
     empty($path_array) || ($file = array_pop($path_array));
     empty($path_array) || ($filepath = implode($path_array));
     empty($path) && ($path = $this->get_config_path());
     if (!empty($filepath)) {
         $path .= '/' . $filepath;
     }
     if (empty($file)) {
         $file = $section;
         $section = null;
     }
     if (is_file($path . '/' . $file . '.ini')) {
     } elseif (!empty($file) && is_dir($path . '/' . $file)) {
         $path = $path . '/' . $file;
         $file = $section;
         $section = null;
     } else {
         return false;
     }
     $run_mode = Sys_App::app()->get_run_mode();
     $run_mode == DA_RUN_MODE_PRO && $this->check_run_mode_suffix(false);
     $run_mode_abbr = self::run_mode_abbr($run_mode);
     $run_mode_conf_file = empty($run_mode_abbr) ? $file : $file . '.' . $run_mode_abbr;
     if ($this->_check_run_mode_suffix && is_file($path . '/' . $run_mode_conf_file . '.ini')) {
         $file = $run_mode_conf_file;
         \Lib_Log::debug("use run mode config file: [%s]", $file);
     }
     $file .= '.ini';
     $config = $this->get_config_from_file($file, $section, $path);
     return $config;
 }
Exemplo n.º 11
0
 /**
  * @param int $ap_id
  * @param int $mode
  * @param array $options
  * @param string $php_script
  * @return array
  */
 static function exec_task_by_cli($ap_id, $mode = Module_FlowManager_Main::RUN_MODE_CALLBACK, $options = ['meta' => true], $php_script = 'tools/access_point.php')
 {
     $script = self::get_run_ap_script($ap_id, $mode, $options, $php_script);
     $result = 0;
     $output = null;
     exec($script, $output, $result);
     if ($result != 0) {
         Lib_Log::notice("run ap script failed. case: %s", $output);
         return Lib_Helper::get_err_struct($result, '执行失败');
     }
     return Lib_Helper::get_return_struct('运行成功');
 }
Exemplo n.º 12
0
 /**
  * @param int $task_id
  * @param int $mid
  * @param array $data
  * @return bool|int
  */
 private function _write_meta_file($task_id, $mid, $data)
 {
     // 检查meta选项,如果有则生成meta文件
     if (isset($this->options[Module_FlowManager_Main::EXPORT_META_FILE]) && $this->options[Module_FlowManager_Main::EXPORT_META_FILE] == Module_FlowManager_Main::META_FILE_CREATE) {
         Lib_Log::debug("%s use meta file, task: %d, mid %d", [__CLASS__, $task_id, $mid]);
         $meta_file = self::meta_file_path($task_id, $mid);
         if ($meta_file) {
             return file_put_contents($meta_file, json_encode($data));
         }
     }
     return false;
 }
Exemplo n.º 13
0
 /**
  * @param int $id
  * @param string $value
  * @return array
  */
 private static function _format_field_value($id, $value)
 {
     if (!is_array($value)) {
         Lib_Log::debug('filed values is not array, values: %s', json_encode($value));
         return [];
     }
     foreach ($value as $_k => $_v) {
         if (is_array($_v) && isset($_v[Const_Interface::FIELD_ATTR_RELATION])) {
             $new_value = [];
             if (!is_array($_v[Const_Interface::FIELD_ATTR_RELATION])) {
                 Lib_Log::error('Fields error, please check relaction fields :' . json_encode($_v) . ' in an array');
                 continue;
             }
             foreach ($_v[Const_Interface::FIELD_ATTR_RELATION] as $__value) {
                 $new_value[] = [Const_Interface::FIELD_ATTR_KEY => $__value, Const_Interface::FIELD_ATTR_MODULE => $id];
             }
             $value[$_k][Const_Interface::FIELD_ATTR_RELATION] = $new_value;
         }
     }
     return $value;
 }
Exemplo n.º 14
0
 /**
  * @param $action
  * @param $args
  * @return array|mixed|null
  */
 protected function _do_action($action, $args)
 {
     $result = null;
     $falid_things = function ($result) use($action, $args) {
         Lib_Log::warn('REDIS-ACTION: ' . strtoupper($action) . ' FAILD, args: ' . json_encode($args) . ', result: ' . json_encode($result));
         $this->_reconnect();
     };
     foreach (range(1, self::RETRY_COUNT) as $_count) {
         try {
             if (!$this->_redis || !$this->_is_connecting()) {
                 $this->_create_connection();
             }
             if (!$this->_redis || !$this->_is_connecting()) {
                 $result = ['errno' => 1, 'data' => 'redis is not connected'];
             } else {
                 $result = call_user_func_array([$this->_redis, $action], $args);
                 $result = ['errno' => 0, 'data' => $result];
                 break;
             }
         } catch (RedisException $ex) {
             try {
                 $falid_things([$ex->getCode(), $ex->getMessage(), 'retry count: ' . $_count]);
             } catch (RedisException $ex) {
                 Lib_Log::warn("Redis reconnect failed, err: %s", json_encode($ex));
             }
             $result = ['errno' => $ex->getCode(), 'data' => $ex->getMessage()];
         }
     }
     return $result;
 }
Exemplo n.º 15
0
 /**
  * @param int $mid
  * @param array $stuff_mids
  * @param array $id_map
  * @return callable
  */
 static function after_run_module_record_hook($mid, $stuff_mids, $id_map)
 {
     if ($stuff_mids === null) {
         $stuff_mids = [];
     }
     if (!isset($id_map[$mid][1])) {
         Lib_Log::warn("%s gen record id and order failed!", __METHOD__);
     }
     return function ($task_id, $module_id, $class, $result) use($mid, $stuff_mids, $id_map) {
         $record_id = $id_map[$mid][0];
         $model_module_record = new Model_TaskRunModuleRecord();
         // log for record
         Lib_Log::debug('record after hook task_id: [%d], module_id: [%d], record_id: [%d]', [$task_id, $module_id, $record_id]);
         // end log
         $stat = [];
         $end_time = time();
         $counts = Module_ControlCentre_Counter::get_all_counts();
         if (!isset($result['errno']) || $result['errno'] !== Const_Err_Base::ERR_OK) {
             $record = ['status' => Module_ModuleManager_Main::RUN_MODULE_STATUS_FAILED, 'result' => $result, 'end_time' => $end_time];
             if (isset($result[Const_DataAccess::MREK_STATUS])) {
                 $record['status'] = $result[Const_DataAccess::MREK_STATUS];
             }
         } else {
             $record = ['status' => Module_ModuleManager_Main::RUN_MODULE_STATUS_FINISH, 'end_time' => $end_time];
             $data = $result['data'];
             if (method_exists($class, 'format_record_msg')) {
                 $stat = call_user_func([$class, 'format_record_msg'], $data);
             }
             if (!empty($stat)) {
                 $record['result'] = ['errno' => Const_Err_Base::ERR_OK, 'msg' => $stat];
                 $record['stat'] = $stat;
             }
         }
         if ($counts['errno'] != Const_Err_Base::ERR_OK) {
             $stuff_mids = [];
         } else {
             $counts = $counts['data'];
             $_tmp_stat = Module_ControlCentre_Counter::formated_counts($mid, $counts);
             if (is_array($_tmp_stat) && !empty($_tmp_stat)) {
                 $record['stat'] = isset($record['stat']) ? array_merge($_tmp_stat, $record['stat']) : $_tmp_stat;
             }
             unset($_tmp_stat);
         }
         $model_module_record->update_record($record_id, $record);
         foreach ($stuff_mids as $_mid) {
             $stat = [];
             $record_id = $id_map[$_mid][0];
             $_tmp_stat = Module_ControlCentre_Counter::formated_counts($_mid, $counts);
             is_array($_tmp_stat) && ($stat = array_merge($_tmp_stat, $stat));
             unset($_tmp_stat);
             $record = ['status' => Module_ModuleManager_Main::RUN_MODULE_STATUS_CALLED, 'end_time' => $end_time];
             if (!empty($stat)) {
                 $record['stat'] = $stat;
             }
             $model_module_record->update_record($record_id, $record);
         }
     };
 }
Exemplo n.º 16
0
 /**
  * (non-PHPdoc)
  *
  * @see TyDB_Abstract::_connect()
  */
 protected function _connect($isReader = true)
 {
     // 		$config = $isReader ? $this->_reader : $this->_writer;
     $config = $this->_writer;
     try {
         if (empty($this->pdo)) {
             $this->pdo = new \PDO("mysql:host={$config['host']};dbname={$config['dbname']};port={$config['port']};charset={$config['charset']}", $config['user'], $config['password'], array(\PDO::ATTR_PERSISTENT => true, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_TIMEOUT => 2, \PDO::ATTR_EMULATE_PREPARES => true));
         }
     } catch (\PDOException $e) {
         $msg = $e->getMessage();
         Lib_Log::write('system_sql', 'connect', $msg);
     }
 }
Exemplo n.º 17
0
<?php

if (!defined('DA_INIT')) {
    // 防止重复初始化
    define("DA_INIT", 1);
    // 版本检查
    if (PHP_VERSION_ID < 50400) {
        exit("Need PHP-5.4.0 or upper." . PHP_EOL);
    }
    ini_set('memory_limit', '30G');
    define('DA_PATH_INIT_FILE', dirname(__FILE__));
    define('DA_PATH_HOME', dirname(DA_PATH_INIT_FILE));
    define('DA_PATH_SYS', DA_PATH_INIT_FILE . '/sys');
    // functions
    require_once DA_PATH_SYS . '/function.php';
    // start app
    require_once DA_PATH_SYS . '/app.php';
    Da\Sys_App::app(DA_PATH_HOME . '/conf/app.ini')->bootstrap();
    file_exists(DA_PATH_INIT_FILE . '/extra.php') && (require_once DA_PATH_INIT_FILE . '/extra.php');
    Lib_Log::DEBUG('Framework(v' . DA_VERSION . ') init ok');
}
// end of if DA_LIB_INIT
Exemplo n.º 18
0
<?php

if (!defined('DA_UT_PATH')) {
    define('DA_UT_PATH', dirname(__FILE__));
    define('DA_UT_DATA_PATH', DA_UT_PATH . '/data');
    // 版本检查
    if (PHP_VERSION_ID < 50400) {
        exit("Need PHP-5.4.0 or upper." . PHP_EOL);
    }
    ini_set('memory_limit', '10240M');
    //require_once 'PHPUnit/Autoload.php';
    // start app
    defined('DA_PATH_HOME') || define('DA_PATH_HOME', dirname(dirname(DA_UT_PATH)));
    // functions
    if (DA_PATH_HOME) {
        $app = DA_PATH_HOME . '/app/sys/app.php';
        $conf = DA_PATH_HOME . '/conf/unit.ini';
        require_once $app;
        require_once DA_PATH_HOME . '/app/sys/function.php';
        Da\Sys_App::app($conf)->bootstrap();
        Lib_Log::DEBUG('Unit test init ok');
    } else {
        throw new Exception('UT: wrong path.');
    }
    require_once DA_UT_PATH . '/helper.php';
}
// end of if DA_UT_INIT
 /**
  * @brief 
  * 定时器,用来检测是否有子进程超时
  * 同时增加超时控制
  * @see 
  * @note 
  * @author duxin01
  * @date 2014/04/17 13:32:38
  **/
 public function childAlarmHandler($signo)
 {
     foreach ($this->currentJobs as $pid => $startTime) {
         if (time() - $startTime < $this->childTimeout) {
             continue;
         }
         Lib_Log::warn("child timeout, kill -9 {$pid}");
         $this->pushFaildData($pid);
         posix_kill($pid, SIGKILL);
         // clear pid of current jobs
         unset($this->currentJobs[$pid]);
     }
     pcntl_alarm($this->childTimeout);
     //重新设置闹钟
     return true;
 }
Exemplo n.º 20
0
<?php

session_start();
require_once dirname(dirname(__FILE__)) . '/app/init.php';
Module_HttpRequest_Router::get_instance()->register_pre_router_hook(['Module_Account_Manager', 'check_perm']);
Module_View_Main::view()->set_template_dir(Da\Sys_App::template_path());
$router = [Module_HttpRequest_Router::get_instance(), 'route'];
if (Da\Sys_Router::get_instance()->register_router($router)) {
    MT::lang(MT::LANG_ZH_CN);
    $dispatch = Da\Sys_Router::get_instance()->dispatch();
    if ($dispatch['errno'] != Da\Sys_Router::ERRNO_OK) {
        echo $dispatch['data'];
        exit;
    }
} else {
    Lib_Log::error('Route rules ' . json_encode($rules) . ' is not callable!');
}
Exemplo n.º 21
0
 /**
  * @param int $module_id
  * @return array
  */
 static function functional_module_class_name($module_id)
 {
     $module = self::get_instance()->get_module_info_by_id($module_id);
     if (empty($module)) {
         return Lib_Helper::get_err_struct(Const_Err_DataAccess::ERR_MODULE_NOT_EXISTS, '模块[' . $module_id . ']不存在');
     }
     if (!isset($module[Const_Module::META_TYPE])) {
         Lib_Log::error('errno:' . Const_Err_DataAccess::ERR_MODULE_INCORRECT_INFO . ' module not has meta type, module_id: ' . $module_id);
         return Lib_Helper::get_err_struct(Const_Err_DataAccess::ERR_MODULE_INCORRECT_INFO, ' module not has meta type, module_id: ' . $module_id);
     }
     if (strcmp($module[Const_Module::META_TYPE], Const_Module::TYPE_FUNCTIONAL) !== 0) {
         Lib_Log::error('errno:' . Const_Err_DataAccess::ERR_MODULE_WRONG_TYPE . ' module is not functional module, module_id: ' . $module_id);
         return Lib_Helper::get_err_struct(Const_Err_DataAccess::ERR_MODULE_WRONG_TYPE, ' module not has meta type, module_id: ' . $module_id);
     }
     $class_name = $module[Model_ModulesInfo::FIELD_MODULE_CLASS];
     if (!class_exists($class_name)) {
         Lib_Log::error("errno: %d, err: module class %s not exists!", [Const_Err_DataAccess::ERR_MODULE_CLASS_NOT_EXISTS, $class_name]);
         return Lib_Helper::get_err_struct(Const_Err_DataAccess::ERR_MODULE_CLASS_NOT_EXISTS, 'Module class ' . $class_name . ' not exists!');
     }
     return Lib_Helper::get_return_struct($class_name);
 }
Exemplo n.º 22
0
			}
		}
		
		public  function writeLog($message)
		{
			$ip =  isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
			$debug = debug_backtrace(true);
			$string = date('Y-m-d H:i:s')."\t";
			$string .= $ip."\t";
			$string .=$debug[0]['file']."\t";
			$string .= "\tline" . $debug[0]['line']."\t";
			$string .= json_encode($message)."\r\n";
			if(!fwrite($this->fileHander, $string)){
				die('the log file can not be written!');
			}
		}
		
		public function __destruct()
		{
			if($this->fileHander!=null){
				fclose($this->fileHander);
			}
		}
		
	}
	
	$log = new Lib_Log();
	$log->writeLog('the error debug!');
	echo "</pre>";
	
?>
Exemplo n.º 23
0
 /**
  * @param $callback
  * @return null|array
  * @throws Exception
  */
 protected function _doAction($callback)
 {
     Lib_Log::debug(__METHOD__ . ': do action begin!');
     if (empty($this->_currentDbName) || empty($this->_currentTableName)) {
         throw new Exception(__METHOD__ . 'empty param ! DB:' . var_export($this->_currentDbName, true) . ' Table: ' . var_export($this->_currentTableName, true), self::ERRNO_EMPTY_PARAMS);
     }
     Lib_Log::debug(__METHOD__ . ': data check finish!');
     $doAct = function () use($callback) {
         $dbName = $this->_currentDbName;
         $tableName = $this->_currentTableName;
         if (empty($this->_conn->{$dbName})) {
             $this->ReConnect();
         }
         $collection = $this->_conn->{$dbName}->{$tableName};
         $ret = $callback($collection);
         return $ret;
     };
     Lib_Log::debug(__METHOD__ . ': create function finish!');
     $retryCount = self::RETRY_COUNT - 1;
     $ret = null;
     do {
         Lib_Log::debug(__METHOD__ . ': begin do action! retry count is: %d', $retryCount);
         try {
             $ret = $doAct();
             $retryCount = -1;
         } catch (Exception $e) {
             if ($retryCount < 0) {
                 throw new Exception($e->getMessage(), $e->getCode());
             } else {
                 Lib_Log::warn("MONGO Retry,retry time: %d, Exception code: %s, msg: %s", array(self::RETRY_COUNT - $retryCount, strval($e->getCode()), $e->getMessage()));
             }
         }
     } while (is_null($ret) && $retryCount-- >= 0);
     return $ret;
 }
Exemplo n.º 24
0
 static function task_list_action()
 {
     $task_id = Lib_Request::get_int('task_id');
     $ap_name = Lib_Request::get_var('ap_name');
     $ap_name = trim($ap_name);
     $src_id = Lib_Request::get_var('sub_src');
     $src_id = trim($src_id);
     $status = Lib_Request::get_int('status');
     $time_begin = Lib_Request::get_var('time_begin');
     $time_begin = trim($time_begin);
     $time_end = Lib_Request::get_var('time_end');
     $time_end = trim($time_end);
     $cond = [];
     $search_vars = [];
     $ap_cond = [];
     if (!empty($task_id)) {
         $cond = ['_id' => $task_id];
         $search_vars = ['task_id' => $task_id];
     } else {
         if (strpos($src_id, ',')) {
             $src_ids = explode(',', $src_id);
             $int_src_ids = [];
             foreach ($src_ids as $k => $v) {
                 $int_src_ids[] = intval($v);
             }
             $cond['src_id'] = ['$in' => array_merge($src_ids, $int_src_ids)];
         } elseif (!empty($src_id)) {
             $cond['src_id'] = ['$in' => [$src_id, intval($src_id)]];
         }
         if (!empty($status)) {
             $cond['status'] = $status;
             $search_vars['status'] = $status;
         }
         if (!empty($time_begin) || !empty($time_end)) {
             $time_cond = [];
             if (!empty($time_begin)) {
                 $time_begin = strtotime($time_begin);
                 $time_cond['$gt'] = $time_begin;
             }
             if (!empty($time_end)) {
                 $time_end = strtotime($time_end);
                 $time_cond['$lte'] = $time_end;
             }
             if ($time_begin >= $time_end) {
                 unset($time_cond['$lte']);
             }
             if (!empty($time_cond)) {
                 $cond['create_time'] = $time_cond;
             }
         }
     }
     if (!Module_Account_User::has_perms([Module_Account_Perm::PERM_AP_ADMIN])) {
         $ap_cond['interface_people'] = new MongoRegex("/" . Module_Account_User::get_current_user() . "/");
     }
     if (!empty($ap_name)) {
         $ap_cond = ['ap_name' => new MongoRegex("/" . $ap_name . "/")];
     }
     if (!empty($ap_cond)) {
         $search_vars['ap_name'] = $ap_name;
         $ap_ids = [];
         $int_ap_ids = [];
         $model = new Model_AccessPoint();
         $ap_infos = $model->get_all($ap_cond);
         if ($ap_infos['errno'] == Const_Err_Base::ERR_OK) {
             foreach ($ap_infos['data'] as $k => $ap) {
                 $ap_ids[] = $ap['ap_id'];
                 $int_ap_ids[] = intval($ap['ap_id']);
             }
         }
         $cond['ap_id'] = ['$in' => array_merge($ap_ids, $int_ap_ids)];
     }
     $model_task = new Model_Task();
     $total_num = $model_task->get_tasks_count($cond);
     $current_page = Lib_Request::get_int('page');
     //当前页码,必须
     $total_size = isset($total_num['data']) ? intval($total_num['data']) : 0;
     //总记录数,必须
     $page_size = 15;
     //每页条数,必须
     $skip = ($current_page - 1) * $page_size;
     //跳过记录,必须
     $skip = $skip < 0 ? 0 : $skip;
     $mode = 2;
     //页码模式,决定页码个数,默认1
     $tasks = $model_task->get_all($cond, $page_size, $skip);
     if ($tasks['errno'] !== Const_Err_Base::ERR_OK) {
         Lib_Log::error(Lib_Helper::format_err_struct($tasks));
         $tasks = [];
         Lib_Request::flash('未获取到任务信息');
     }
     $tasks = $tasks['data'];
     $ap_infos = [];
     $ap_model = new Model_AccessPoint();
     foreach ($tasks as $_k => $_t) {
         $ap_info = $ap_model->get_ap_by_id($_t['ap_id']);
         $ap_info['ap_id'] = $_t['ap_id'];
         if ($ap_info['errno'] !== Const_Err_Base::ERR_OK) {
             Lib_Log::error(Lib_Helper::format_err_struct($ap_info));
             Lib_Request::flash('获取接入点信息失败');
             Module_HttpRequest_Router::redirect_to('/');
         }
         $ap_info = $ap_info[Const_DataAccess::MREK_DATA];
         $ap_infos[$_t['ap_id']] = $ap_info;
     }
     $source_model = new Model_Source();
     $all_sources = $source_model->get_all();
     $sources = $all_sources[Const_DataAccess::MREK_DATA];
     $all_src_type = [];
     foreach ($all_sources['data'] as $k => $v) {
         if (!in_array($v['src_type'], $all_src_type)) {
             $all_src_type[] = $v['src_type'];
         }
     }
     asort($all_src_type);
     $task_status_list = Module_ControlCentre_Main::$task_status_list;
     $pages = Module_View_Template::get_pages_html($current_page, $total_size, $page_size, $mode);
     Module_Page_Main::render('control_centre/task_list', ['ap_info' => $ap_infos, 'tasks' => $tasks, 'sources' => $sources, 'pages' => $pages, 'all_src_type' => $all_src_type, 'status_list' => $task_status_list, 'search_vars' => $search_vars]);
 }
Exemplo n.º 25
0
 /**
  * @param int $task_id
  * @param int $module_id
  * @param array $data
  * @param array $options
  * @return array
  */
 function run_module($task_id, $module_id, $data, $options)
 {
     $class = $this->get_module_class($module_id);
     Lib_Log::debug("%s begin run module [%d]\ttask_id:[%d]\toptions:%s", [__METHOD__, $module_id, $task_id, json_encode($options)]);
     $class->set_options($options);
     $this->run_hooks(self::get_run_module_hook_type(self::HOOK_TYPE_BEFORE_RUN_MODULE_PREFIX, $module_id), [$task_id, $module_id, $class, $data]);
     $this->run_hooks(self::HOOK_TYPE_BEFORE_RUN, [$task_id, $module_id, $class, $data]);
     try {
         $result = $class->run($task_id, $data);
     } catch (Exception $ex) {
         $code = $ex->getCode();
         $msg = $ex->getMessage();
         Lib_Log::error("Got a Exception, code [%d], message [%s]", [$code, $msg]);
         $result = Lib_Helper::get_err_struct($code, $msg);
     }
     $this->run_hooks(self::get_run_module_hook_type(self::HOOK_TYPE_AFTER_RUN_MODULE_PREFIX, $module_id), [$task_id, $module_id, $class, $result]);
     $this->run_hooks(self::HOOK_TYPE_AFTER_RUN, [$task_id, $module_id, $class, $result]);
     return $result;
 }
Exemplo n.º 26
0
 public function __destruct()
 {
     $_ENV['tongji']['cost'] = time() - $_ENV['tongji']['cost'];
     Lib_Log::tongji($_ENV['tongji']);
 }
Exemplo n.º 27
0
 /**
  * @param array
  * @param string
  * @param string
  * @param string
  * @param string
  * @param string
  * @param string
  * @param int
  * @param string
  * @return array
  */
 function save_fail_data($db, $task_id, $ap_id, $ts, $uid, $content, $module, $errno, $errmsg)
 {
     $data = [];
     $data['_id'] = $task_id . '_' . $uid;
     $data['task_id'] = $task_id;
     $data['uid'] = $uid;
     $data['ap_id'] = $ap_id;
     $data['ts'] = $ts;
     $data['content'] = $content;
     $data['module'] = $module;
     $data['errno'] = $errno;
     $data['errmsg'] = $errmsg;
     $this->get_db()->set_db_name('fail_data');
     $this->get_db()->set_table_name('t_fail_data');
     $ret = $this->get_db()->save($data);
     if (0 != $ret['errno']) {
         Lib_Log::error(__METHOD__ . ' Fail to save fail data.');
     }
     return $ret;
 }
Exemplo n.º 28
0
 /**
  * @param $callback
  * @param array $args
  */
 function fork_count_processor($callback, $args)
 {
     $this->_counter_pid = pcntl_fork();
     if ($this->_counter_pid < 0) {
         Lib_Log::warn("%s fork failed! result: %s", [__METHOD__, var_export($this->_counter_pid, true)]);
         $this->_counter_pid = null;
     } elseif ($this->_counter_pid == 0) {
         call_user_func_array($callback, $args);
         exit;
     }
 }
Exemplo n.º 29
0
 /**
  * 获取并发curl结果
  * 为防止假死,设置循环最大执行时间,为0为不设最大执行时间
  * @param int $max_timeout
  * @return array
  */
 public function multiGet($max_timeout = 0)
 {
     $active = null;
     $t1 = time();
     do {
         $mrc = curl_multi_exec($this->mh, $active);
     } while ($mrc == CURLM_CALL_MULTI_PERFORM);
     while ($active && $mrc == CURLM_OK) {
         if ($max_timeout > 0 && time() - $t1 > $max_timeout) {
             Lib_Log::warn("exec time out,exit loop");
             break;
         }
         //PHP_VERSION_ID < 50214 ? usleep(5000) : curl_multi_select($this->mh, 0.2);
         if (curl_multi_select($this->mh, 0.2) != -1) {
             do {
                 $mrc = curl_multi_exec($this->mh, $active);
             } while ($mrc == CURLM_CALL_MULTI_PERFORM);
         }
     }
     $stat = array();
     $data = array();
     foreach ($this->handles as $key => $ch) {
         $d = array();
         $d['errno'] = curl_errno($ch);
         if ($d['errno'] != CURLE_OK) {
             $d['error'] = curl_error($ch);
             continue;
         } else {
             $d['total_time'] = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
             $d['code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
             $d['data'] = curl_multi_getcontent($ch);
         }
         $data[$key] = $d;
         curl_multi_remove_handle($this->mh, $ch);
         curl_close($ch);
     }
     $this->handles = array();
     return array('errno' => 0, 'data' => $data);
 }
Exemplo n.º 30
0
 /**
  * @param array $cond
  * @return array
  */
 public function get_tables($cond = [])
 {
     switch ($this->_driver) {
         case self::DB_DRIVER_MONGO:
         default:
             Lib_Log::debug(__METHOD__ . ': Use mongo driver, cond: %s', [json_encode($cond)]);
             try {
                 $result = $this->_db->GetTables($cond);
                 if (is_null($result)) {
                     $result = Lib_Helper::get_err_struct(Const_Err_Db::ERR_MONGO_COLLECTIONS_FAIL, '获取数据集失败', __FILE__, __LINE__);
                 } else {
                     $result = Lib_Helper::get_return_struct($result);
                 }
             } catch (Exception $ex) {
                 Lib_Log::error(__METHOD__ . " get faild! cond: %s, code: %d, messsage: %s", [json_encode($cond), $ex->getCode(), $ex->getMessage()]);
                 $result = Lib_Helper::get_err_struct(Const_Err_Db::ERR_MONGO_COLLECTIONS_FAIL, '获取数据集失败', __FILE__, __LINE__);
             }
     }
     return $result;
 }