public function __construct(SiteApplication $app)
 {
     $this->app = $app;
     set_time_limit(30000);
     ini_set('memory_limit', -1);
     proc_nice(19);
 }
Esempio n. 2
0
 /**
  * мастерский рабочий цикл
  */
 public function run()
 {
     try {
         static::log('starting master (PID ' . posix_getpid() . ')....');
         //задаем приоритет процесса в ОС
         proc_nice($this->priority);
         //включаем сборщик циклических зависимостей
         gc_enable();
         //выполняем функцию приложения до рабочего цикла
         call_user_func([$this->appl, 'baseOnRun']);
         //самый главный цикл
         while (TRUE) {
             if (TRUE === call_user_func([$this->appl, 'baseRun'])) {
                 //прекращаем цикл
                 break;
             }
             //ожидаем заданное время для получения сигнала операционной системы
             $this->sigwait();
             //если сигнал был получен, вызываем связанную с ним функцию
             pcntl_signal_dispatch();
         }
     } catch (\Exception $e) {
         $this->shutdown();
     }
 }
 public function run()
 {
     proc_nice(Daemon::$settings['masterpriority']);
     gc_enable();
     register_shutdown_function(array($this, 'onShutdown'));
     $this->collections = array('workers' => new threadCollection());
     Thread::setproctitle(Daemon::$runName . ': master process' . (Daemon::$settings['pidfile'] !== Daemon::$settings['defaultpidfile'] ? ' (' . Daemon::$settings['pidfile'] . ')' : ''));
     Daemon::$appResolver = (require Daemon::$settings['path']);
     Daemon::$appResolver->preloadPrivileged();
     $this->spawnWorkers(min(Daemon::$settings['startworkers'], Daemon::$settings['maxworkers']));
     $mpmLast = time();
     $autoReloadLast = time();
     while (TRUE) {
         pcntl_signal_dispatch();
         $this->sigwait(1, 0);
         clearstatcache();
         if (Daemon::$logpointerpath !== Daemon::parseStoragepath(Daemon::$settings['logstorage'])) {
             $this->sigusr1();
         }
         $c = 1;
         if (time() > $mpmLast + Daemon::$parsedSettings['mpmdelay']) {
             $mpmLast = time();
             ++$c;
             if ($c > 0xfffff) {
                 $c = 0;
             }
             if ($c % 10 == 0) {
                 $this->collections['workers']->removeTerminated(TRUE);
                 gc_collect_cycles();
             } else {
                 $this->collections['workers']->removeTerminated();
             }
             if (isset(Daemon::$settings['mpm']) && is_callable($c = Daemon::$settings['mpm'])) {
                 call_user_func($c);
             } else {
                 $state = Daemon::getStateOfWorkers($this);
                 if ($state) {
                     $n = max(min(Daemon::$settings['minspareworkers'] - $state['idle'], Daemon::$settings['maxworkers'] - $state['alive']), Daemon::$settings['minworkers'] - $state['alive']);
                     if ($n > 0) {
                         Daemon::log('Spawning ' . $n . ' worker(s).');
                         $this->spawnWorkers($n);
                     }
                     $n = min($state['idle'] - Daemon::$settings['maxspareworkers'], $state['alive'] - Daemon::$settings['minworkers']);
                     if ($n > 0) {
                         Daemon::log('Stopping ' . $n . ' worker(s).');
                         $this->stopWorkers($n);
                     }
                 }
             }
         }
     }
 }
Esempio n. 4
0
 /**
  * cron
  *
  * function called to create a cron
  *
  * @access	public
  * @param	string $app_name name of application to cron
  * @param	mixed $params null, or array of params for cron creation
  */
 function cron($app_name, $params = '')
 {
     // be very nice to other processes
     if (php_sapi_name() == 'cli') {
         proc_nice(19);
     }
     $this->_startTimer();
     $this->_app_name = $app_name;
     $this->_lock_file_name = '/web/temp/' . $app_name . '.lock';
     set_time_limit(0);
     $this->_stdin = fopen('php://stdin', 'r');
     $this->log_file = '/web/temp/' . $app_name . '.log';
     parse_str($params, $params);
     foreach ($params as $param => $value) {
         $this->{$param} = $value;
     }
     //end foreach
 }
Esempio n. 5
0
 /**
  * @method run
  * @desc Runtime of Child process.
  * @return void
  */
 public function run()
 {
     try {
         static::log('starting child (PID ' . posix_getpid() . ')....', Logger::L_TRACE);
         proc_nice($this->priority);
         gc_enable();
         $this->start_time = microtime(true);
         call_user_func([$this->appl, 'baseOnRun']);
         while (TRUE) {
             if (TRUE === call_user_func([$this->appl, 'baseRun']) || $this->isItTimeToDie()) {
                 break;
             }
             //ожидаем заданное время для получения сигнала операционной системы
             $this->sigwait(Config::get('Daemon.child_sigwait'));
             //если сигнал был получен, вызываем связанную с ним функцию
             pcntl_signal_dispatch();
         }
     } catch (\Exception $e) {
         $this->shutdown();
     }
 }
Esempio n. 6
0
<?php

midcom::get('auth')->require_admin_user();
// If we import some other database than Geonames this is the place to tune
// Also, the Geonames dump format may change. See http://download.geonames.org/export/dump/readme.txt
// The current state of this, incl. comments reflects the Geonames format as of 2008-12-15
$fields_map = array('geonameid' => 0, 'name' => 1, 'asciiname' => 2, 'alternatenames' => 3, 'latitude' => 4, 'longitude' => 5, 'featureclass' => 6, 'featurecode' => 7, 'country' => 8, 'cc2' => 9, 'admin1 code' => 10, 'admin2 code' => 11, 'admin3 code' => 12, 'admin4 code' => 13, 'population' => 14, 'elevation' => 15, 'gtopo30' => 16, 'timezone' => 17, 'modification date' => 18);
if (array_key_exists('cities_file_path', $_POST) && file_exists($_POST['cities_file_path'])) {
    $features = explode(',', $_POST['featurecodes_to_import']);
    midcom::get()->disable_limits();
    // this is a potentially very time and resource intensive operation, so let's play nicely:
    if (is_callable('proc_nice')) {
        proc_nice(10);
    }
    while (@ob_end_flush()) {
    }
    $imported_cities = array();
    // Read CSV file
    $cities_created = 0;
    $row = 0;
    $handle = fopen($_POST['cities_file_path'], 'r');
    while ($data = fgetcsv($handle, 1000, "\t")) {
        $row++;
        //if ($row > 1000) { break; }
        if (!isset($data[$fields_map['featurecode']]) || !in_array($data[$fields_map['featurecode']], $features)) {
            continue;
        }
        if ($data[$fields_map['population']] < $_POST['population_to_import']) {
            continue;
        }
        if (strlen($data[$fields_map['country']]) > 2) {
Esempio n. 7
0
 /**
  * Call proc_nice with passed value if available on this platform.
  *
  * @param int Priorty adjustment to be made.
  * @return boolean True if successful.
  *
  * @see options['adjustPriority']
  * @see http://us3.php.net/manual/en/function.proc-nice.php
  **/
 public function adjustPriority($adjBy)
 {
     if (!function_exists('proc_nice')) {
         return;
     }
     return proc_nice($adjBy);
 }
Esempio n. 8
0
 public function nice($increment)
 {
     if (is_resource($this->_process)) {
         return proc_nice($this->_process, $increment);
     }
     return false;
 }
 /**
  * Setup settings on start.
  * @return void
  */
 public function prepareSystemEnv()
 {
     register_shutdown_function(array($this, 'onShutdown'));
     proc_nice(Daemon::$config->masterpriority->value);
     $this->setproctitle(Daemon::$runName . ': master process' . (Daemon::$config->pidfile->value !== Daemon::$config->pidfile->defaultValue ? ' (' . Daemon::$config->pidfile->value . ')' : ''));
 }
Esempio n. 10
0
fclose($pipes[0]);
fpassthru($pipes[1]);
VS(proc_close($process), 0);
$descriptorspec = array(array("pipe", "r"), array("pipe", "w"), array("file", $errout, "a"));
$process = proc_open('cat', $descriptorspec, $pipes);
VERIFY($process != false);
VERIFY(proc_terminate($process));
// still need to close it, not to leave a zombie behind
proc_close($process);
$process = proc_open('cat', $descriptorspec, $pipes);
VERIFY($process != false);
$ret = proc_get_status($process);
VS($ret['command'], 'cat');
VERIFY($ret['pid'] > 0);
VERIFY($ret['running']);
VERIFY(!$ret['signaled']);
VS($ret['exitcode'], -1);
VS($ret['termsig'], 0);
VS($ret['stopsig'], 0);
proc_close($process);
VERIFY(proc_nice(0));
VS(escapeshellarg("\""), "'\"'");
VS(escapeshellcmd("perl \""), "perl \\\"");
$nullbyte = "echo abc\ncommand";
VS(passthru($nullbyte), null);
VS(system($nullbyte), "");
VS(exec($nullbyte, $nullbyteout), "");
VS($nullbyteout, null);
VS(shell_exec($nullbyte), null);
$process = proc_open($nullbyte, array(), $pipes);
VS($process, false);
Esempio n. 11
0
 function _proc_nice_shutdown_function()
 {
     // Restore priority
     proc_nice(0);
 }
Esempio n. 12
0
//
//STOP FAKE REGISTER GLOBALS
$fake_register_globals = false;
//
require_once dirname(__FILE__) . "/../../interface/globals.php";
require_once dirname(__FILE__) . "/../reminders.php";
//To improve performance and not freeze the session when running this
// report, turn off session writing. Note that php session variables
// can not be modified after the line below. So, if need to do any php
// session work in the future, then will need to remove this line.
session_write_close();
//Remove time limit, since script can take many minutes
set_time_limit(0);
// Set the "nice" level of the process for these reports. When the "nice" level
// is increased, these cpu intensive reports will have less affect on the performance
// of other server activities, albeit it may negatively impact the performance
// of this report (note this is only applicable for linux).
if (!empty($GLOBALS['pat_rem_clin_nice'])) {
    proc_nice($GLOBALS['pat_rem_clin_nice']);
}
//  Start a report, which will be stored in the report_results sql table..
if (!empty($_POST['execute_report_id']) && !empty($_POST['process_type']) && ($_POST['process_type'] == "process" || $_POST['process_type'] == "process_send")) {
    if ($_POST['process_type'] == "process_send") {
        update_reminders_batch_method('', '', $_POST['execute_report_id'], TRUE);
    } else {
        // $_POST['process_type'] == "process"
        update_reminders_batch_method('', '', $_POST['execute_report_id']);
    }
} else {
    echo "ERROR";
}
Esempio n. 13
0
 /**
  * Setup settings on start.
  * @return void
  */
 protected function prepareSystemEnv()
 {
     register_shutdown_function(function () {
         if ($this->pid != posix_getpid()) {
             return;
         }
         if ($this->shutdown === true) {
             return;
         }
         $this->log('Unexcepted shutdown.');
         $this->shutdown(SIGTERM);
     });
     posix_setsid();
     proc_nice(Daemon::$config->masterpriority->value);
     if (!Daemon::$config->verbosetty->value) {
         fclose(STDIN);
         fclose(STDOUT);
         fclose(STDERR);
     }
     $this->setTitle(Daemon::$runName . ': master process' . (Daemon::$config->pidfile->value !== Daemon::$config->pidfile->defaultValue ? ' (' . Daemon::$config->pidfile->value . ')' : ''));
 }
Esempio n. 14
0
 private function work()
 {
     $this->getLogger()->debug("Child {$this->myPid} about to start work");
     if ($this->nice) {
         $this->getLogger()->debug("Child being reniced to {$this->nice}");
         proc_nice($this->nice);
     }
     while ($this->shouldWork) {
         pcntl_signal_dispatch();
         $_SERVER['REQUEST_TIME'] = time();
         $_SERVER['REQUEST_TIME_FLOAT'] = microtime(true);
         if ($this->doWork()) {
             $this->roundsComplete++;
         }
         // If runCount is 0, go indefinitely. Otherwise stop after runCount
         if ($this->runCount && $this->roundsComplete >= $this->runCount) {
             $this->stopWorking();
         }
     }
     $this->getLogger()->info("Child has stopped working and will exit");
     exit;
 }
Esempio n. 15
0
 /**
  * At process level increases the niceness of a heavy "thread" making its priority lower. Multiple calls of the method will accumulate and increase the effect.
  * @see \GPhpThread::makeNicer() A method with the opposite effect is GPhpThread::makeNicer().
  * @return bool Returns true on success or false in case of error or lack of privileges.
  */
 protected function makeUnfriendlier()
 {
     // {{{ decreases the priority
     if ($this->amIParent()) {
         return false;
     }
     return proc_nice(1);
 }
Esempio n. 16
0
 /**
  * Change parent process priority according to EXTENDER_NICENESS
  *
  */
 public final function adjustNiceness()
 {
     if (defined("EXTENDER_PARENT_NICENESS")) {
         $niceness = proc_nice(EXTENDER_PARENT_NICENESS);
         if ($niceness == false) {
             $this->logger->warning("Unable to set parent process niceness to " . EXTENDER_PARENT_NICENESS);
         }
     }
 }
Esempio n. 17
0
<?php

echo "*** Test by calling method or function with incorrect numbers of arguments ***\n";
$priority = 1;
$extra_arg = 1;
var_dump(proc_nice($priority, $extra_arg));
var_dump(proc_nice());
Esempio n. 18
0
<?php

function getNice($id)
{
    $res = shell_exec('ps -p ' . $id . ' -o "pid,nice"');
    preg_match('/^\\s*\\w+\\s+\\w+\\s*(\\d+)\\s+(\\d+)/m', $res, $matches);
    if (count($matches) > 2) {
        return $matches[2];
    } else {
        return -1;
    }
}
$delta = 10;
$pid = getmypid();
$niceBefore = getNice($pid);
proc_nice($delta);
$niceAfter = getNice($pid);
var_dump($niceBefore == $niceAfter - $delta);
Esempio n. 19
0
<?php

chdir('..');
$MIN_DAYS = 2;
require_once 'common.inc';
require_once 'archive.inc';
ignore_user_abort(true);
set_time_limit(3300);
// only allow it to run for 55 minutes
if (function_exists('proc_nice')) {
    proc_nice(19);
}
// bail if we are already running
$lock = Lock("Archive", false, 3600);
if (!isset($lock)) {
    echo "Archive process is already running\n";
    exit(0);
}
if (array_key_exists('archive_days', $settings)) {
    $MIN_DAYS = $settings['archive_days'];
}
$MIN_DAYS = max($MIN_DAYS, 0.1);
$archive_dir = null;
if (array_key_exists('archive_dir', $settings)) {
    $archive_dir = $settings['archive_dir'];
}
$kept = 0;
$archiveCount = 0;
$deleted = 0;
$log = fopen('./cli/archive.log', 'w');
// check the old tests first
Esempio n. 20
0
<?php

echo "*** Test substituting argument 1 with array values ***\n";
$index_array = array(1, 2, 3);
$assoc_array = array(1 => 'one', 2 => 'two');
$variation_array = array('empty array' => array(), 'int indexed array' => $index_array, 'associative array' => $assoc_array, 'nested arrays' => array('foo', $index_array, $assoc_array));
foreach ($variation_array as $var) {
    var_dump(proc_nice($var));
}
Esempio n. 21
0
//
require_once dirname(__FILE__) . "/../../interface/globals.php";
require_once dirname(__FILE__) . "/../clinical_rules.php";
//To improve performance and not freeze the session when running this
// report, turn off session writing. Note that php session variables
// can not be modified after the line below. So, if need to do any php
// session work in the future, then will need to remove this line.
session_write_close();
//Remove time limit, since script can take many minutes
set_time_limit(0);
// Set the "nice" level of the process for these reports. When the "nice" level
// is increased, these cpu intensive reports will have less affect on the performance
// of other server activities, albeit it may negatively impact the performance
// of this report (note this is only applicable for linux).
if (!empty($GLOBALS['cdr_report_nice'])) {
    proc_nice($GLOBALS['cdr_report_nice']);
}
//  Start a report, which will be stored in the report_results sql table..
if (!empty($_POST['execute_report_id'])) {
    $target_date = !empty($_POST['date_target']) ? $_POST['date_target'] : date('Y-m-d H:i:s');
    $rule_filter = !empty($_POST['type']) ? $_POST['type'] : "";
    $plan_filter = !empty($_POST['plan']) ? $_POST['plan'] : "";
    $organize_method = empty($plan_filter) ? "default" : "plans";
    $provider = $_POST['provider'];
    $pat_prov_rel = empty($_POST['pat_prov_rel']) ? "primary" : $_POST['pat_prov_rel'];
    // Process a new report and collect results
    $options = array();
    $array_date = array();
    if ($rule_filter == "amc" || $rule_filter == "amc_2011" || $rule_filter == "amc_2014") {
        // For AMC:
        //   need to make $target_date an array with two elements ('dateBegin' and 'dateTarget')
Esempio n. 22
0
 public function import($xml)
 {
     $originalMaxExecutionTime = ini_get('max_execution_time');
     ini_set('max_execution_time', 120);
     proc_nice(1);
     $tagLocalIds = array();
     $listLocalIds = array();
     $newTagIds = array();
     $newListIds = array();
     $newTaskIds = array();
     $newNoteIds = array();
     $tags = $xml->plancake_tasks->tags->tag;
     foreach ($tags as $tag) {
         $isNewTag = false;
         $tagId = (int) $tag->id > 0 ? $tag->id : null;
         $tagLocalId = (int) $tag->localId;
         $tagName = (string) $tag->name;
         $tagSortOrder = (int) $tag->sortOrder;
         $tagObj = null;
         if ($tagId && !in_array($tagId, $newTagIds)) {
             $tagObj = PcUsersContextsPeer::retrieveByPK($tagId);
         }
         if ($tagObj) {
             if ($tagObj->getUserId() != $this->user->getId()) {
                 die("Hacking attempt.");
             }
         } else {
             // tags are unique by name, thus
             // we check whether the tag is already in the instance
             // we are importing the dump to.
             $c = new Criteria();
             $c->add(PcUsersContextsPeer::CONTEXT, $tagName);
             $tagObj = PcUsersContextsPeer::doSelectOne($c);
             if (!is_object($tagObj)) {
                 $tagObj = new PcUsersContexts();
                 $isNewTag = true;
             }
         }
         $tagObj->setUserId($this->user->getId())->setContext($tagName)->setSortOrder($tagSortOrder)->save();
         $tagLocalIds[$tagLocalId] = $tagObj->getId();
         if ($isNewTag) {
             $newTagIds[] = $tagObj->getId();
         }
     }
     $lists = $xml->plancake_tasks->lists->list;
     foreach ($lists as $list) {
         $isNewList = false;
         $listId = (int) $list->id > 0 ? $list->id : null;
         $listLocalId = (int) $list->localId;
         $listName = (string) $list->name;
         $listSortOrder = (int) $list->sortOrder;
         $listIsInbox = (int) $list->isInbox == 1 ? true : false;
         $listIsTodo = (int) $list->isTodo == 1 ? true : false;
         $listIsHeader = (int) $list->isHeader == 1 ? true : false;
         $listObj = null;
         if ($listId && !in_array($listId, $newListIds)) {
             $listObj = PcListPeer::retrieveByPK($listId);
         }
         if ($listObj) {
             if ($listObj->getCreatorId() != $this->user->getId()) {
                 die("Hacking attempt.");
             }
         } else {
             if ($listIsInbox) {
                 $listObj = $this->user->getInbox();
             } else {
                 if ($listIsTodo) {
                     $listObj = $this->user->getTodo();
                 } else {
                     $listObj = new PcList();
                     $isNewList = true;
                 }
             }
         }
         $listObj->setCreatorId($this->user->getId())->setTitle($listName)->setSortOrder($listSortOrder)->setIsInbox($listIsInbox)->setIsTodo($listIsTodo)->setIsHeader($listIsHeader)->save();
         $listLocalIds[$listLocalId] = $listObj->getId();
         if ($isNewList) {
             $newListIds[] = $listObj->getId();
         }
     }
     $tasks = $xml->plancake_tasks->tasks->task;
     foreach ($tasks as $task) {
         $isNewTask = false;
         $taskId = (int) $task->id > 0 ? $task->id : 0;
         $taskListLocalId = (int) $task->listLocalId;
         $taskDescription = (string) $task->description;
         $taskSortOrder = (int) $task->sortOrder;
         $taskDueDate = (string) $task->dueDate;
         $taskDueTime = strlen($task->dueTime) > 0 ? (int) $task->dueTime : '';
         $taskRepetitionId = (int) $task->repetitionId;
         $taskRepetitionParam = (int) $task->repetitionParam;
         $taskIsStarred = (int) $task->isStarred == 1 ? true : false;
         $taskIsCompleted = (int) $task->isCompleted == 1 ? true : false;
         $taskIsHeader = (int) $task->isHeader == 1 ? true : false;
         $taskIsFromSystem = (int) $task->isFromSystem == 1 ? true : false;
         $taskTagLocalIds = (string) $task->tagLocalIds;
         $taskNote = (string) $task->note;
         $taskListId = $listLocalIds[$taskListLocalId];
         $taskTagIdsArray = array();
         $taskTagLocalIdsArray = PcUtils::explodeWithEmptyInputDetection(',', $taskTagLocalIds);
         foreach ($taskTagLocalIdsArray as $id) {
             $taskTagIdsArray[] = $tagLocalIds[$id];
         }
         $taskTagIds = '';
         if (count($taskTagIdsArray)) {
             $taskTagIds = implode(',', $taskTagIdsArray);
         }
         $taskFromDb = null;
         if ($taskId && !in_array($taskId, $newTaskIds)) {
             $taskFromDb = PcTaskPeer::retrieveByPK($taskId);
         }
         if (!is_object($taskFromDb)) {
             // if the task doesn't exist (even if the dump contains a taskId)
             // we want to add it.
             $taskId = 0;
             $isNewTask = true;
         }
         $newTask = PcTaskPeer::createOrEdit($taskDescription, $taskListId, $taskId, $taskTagIds, $taskIsHeader, $taskNote, $taskDueDate, $taskDueTime, $taskIsStarred, $taskRepetitionId, $taskRepetitionParam, 0, '', 'd-m-Y', false);
         if ($taskIsCompleted) {
             $newTask->setIsCompleted(1);
             $newTask->setCompletedAt($task->completedAt);
             $newTask->save();
         }
         if ($isNewTask) {
             $newTaskIds[] = $newTask->getId();
         }
         if (!$taskId) {
             $newTask->deleteDirtyEntry();
         }
     }
     $notes = $xml->plancake_notes->notes->note;
     foreach ($notes as $note) {
         $isNewNote = false;
         $noteId = (int) $note->id > 0 ? $note->id : null;
         $noteTitle = (string) $note->title;
         $noteContent = (string) $note->content;
         $noteObj = null;
         if ($noteId && !in_array($noteId, $newNoteIds)) {
             $noteObj = PcNotePeer::retrieveByPK($noteId);
         }
         if ($noteObj) {
             if ($noteObj->getCreatorId() != $this->user->getId()) {
                 die("Hacking attempt.");
             }
         } else {
             $noteObj = new PcNote();
             $isNewNote = true;
         }
         $noteObj->setCreatorId($this->user->getId())->setTitle($noteTitle)->setContent($noteContent)->save();
         if ($isNewNote) {
             $newNoteIds[] = $noteObj->getId();
         }
     }
     ini_set('max_execution_time', $originalMaxExecutionTime);
 }
Esempio n. 23
0
 /**
  * Set "nice" value for the process
  *
  * @param  [type] $nice Nice level 0 .. 20
  * @return null
  */
 function nice($nice)
 {
     if (function_exists('proc_nice')) {
         proc_nice($this->process, $nice);
     }
 }
Esempio n. 24
0
 public function init()
 {
     $this->_lock = new Core_Lock($this->_options, self::$out);
     try {
         if (!isset($this->_options['engine'])) {
             throw new Core_StopException("You have to configure `engine`.", "init");
         }
         //internally return isLocked();
         if ($this->_lock->lock()) {
             self::$out->logNotice(">>>>SHOULD WAIT");
             $this->_lock->wait();
         }
         // configure output
         $this->_configureOutput();
         // engine.nice
         if (!self::isWindows() && false !== $this->_options['engine']['nice']) {
             self::$out->logNotice("changing process priority, nice=" . $this->_options['engine']['nice']);
             proc_nice($this->_options['engine']['nice']);
         }
         // configure compare driver
         $this->_configureCompare();
         // configure local driver
         $this->_configureLocalStorage();
         // configure remote driver
         $this->_configureRemoteStorage();
     } catch (Core_StopException $e) {
         // start text
         self::$out->welcome();
         // error message
         $this->_stopAt = $e;
         self::$out->logError($e->getMessage());
         // help instructions
         self::$out->showHelp($this->_appHelpMessage);
         return false;
     } catch (Exception $e) {
         $myE = new Core_StopException("", "engine init", null, Core_StopException::RETCODE_FOREIGN_EXCEPTION);
         $myE->setException($e);
         $this->_stopAt = $myE;
         throw $e;
     }
     return true;
 }
 public function run()
 {
     proc_nice(Daemon::$settings['workerpriority']);
     Daemon::$worker = $this;
     $this->microsleep = Daemon::$settings['microsleep'];
     $this->autoReloadLast = time();
     $this->reloadDelay = Daemon::$parsedSettings['mpmdelay'] + 2;
     $this->setStatus(4);
     Thread::setproctitle(Daemon::$runName . ': worker process' . (Daemon::$settings['pidfile'] !== Daemon::$settings['defaultpidfile'] ? ' (' . Daemon::$settings['pidfile'] . ')' : ''));
     register_shutdown_function(array($this, 'shutdown'));
     if (Daemon::$settings['autogc'] > 0) {
         gc_enable();
     } else {
         gc_disable();
     }
     if (isset(Daemon::$settings['group'])) {
         $sg = posix_getgrnam(Daemon::$settings['group']);
     }
     if (isset(Daemon::$settings['user'])) {
         $su = posix_getpwnam(Daemon::$settings['user']);
     }
     if (Daemon::$settings['chroot'] !== '/') {
         if (posix_getuid() != 0) {
             Daemon::log('You must have the root privileges to change root.');
             exit(0);
         } elseif (!chroot(Daemon::$settings['chroot'])) {
             Daemon::log('Couldn\'t change root to \'' . Daemon::$settings['chroot'] . '\'.');
             exit(0);
         }
     }
     if (isset(Daemon::$settings['group'])) {
         if ($sg === FALSE) {
             Daemon::log('Couldn\'t change group to \'' . Daemon::$settings['group'] . '\'. You must replace config-variable \'group\' with existing group.');
             exit(0);
         } elseif ($sg['gid'] != posix_getgid() && !posix_setgid($sg['gid'])) {
             Daemon::log('Couldn\'t change group to \'' . Daemon::$settings['group'] . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno));
             exit(0);
         }
     }
     if (isset(Daemon::$settings['user'])) {
         if ($su === FALSE) {
             Daemon::log('Couldn\'t change user to \'' . Daemon::$settings['user'] . '\', user not found. You must replace config-variable \'user\' with existing username.');
             exit(0);
         } elseif ($su['uid'] != posix_getuid() && !posix_setuid($su['uid'])) {
             Daemon::log('Couldn\'t change user to \'' . Daemon::$settings['user'] . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno));
             exit(0);
         }
     }
     if (Daemon::$settings['cwd'] !== '.') {
         if (!@chdir(Daemon::$settings['cwd'])) {
             Daemon::log('WORKER ' . $this->pid . '] Couldn\'t change directory to \'' . Daemon::$settings['cwd'] . '.');
         }
     }
     $this->setStatus(6);
     $this->eventBase = event_base_new();
     Daemon::$appResolver->preload();
     foreach (Daemon::$appInstances as $app) {
         foreach ($app as $appInstance) {
             if (!$appInstance->ready) {
                 $this->ready = TRUE;
                 $appInstance->onReady();
             }
         }
     }
     $this->setStatus(1);
     $ev = event_new();
     event_set($ev, STDIN, EV_TIMEOUT, function () {
     }, array());
     event_base_set($ev, $this->eventBase);
     $this->timeoutEvent = $ev;
     while (TRUE) {
         pcntl_signal_dispatch();
         if (($s = $this->checkState()) !== TRUE) {
             $this->closeSockets();
             if (sizeof($this->queue) === 0) {
                 return $s;
             }
         }
         event_add($this->timeoutEvent, $this->microsleep);
         event_base_loop($this->eventBase, EVLOOP_ONCE);
         do {
             for ($i = 0, $s = sizeof($this->eventsToAdd); $i < $s; ++$i) {
                 event_add($this->eventsToAdd[$i]);
                 unset($this->eventsToAdd[$i]);
             }
             $this->readPool();
             $processed = $this->runQueue();
         } while ($processed || $this->readPoolState || $this->eventsToAdd);
     }
 }
Esempio n. 26
0
 /**
  * Setup settings on start.
  * @return void
  */
 protected function prepareSystemEnv()
 {
     proc_nice(Daemon::$config->workerpriority->value);
     register_shutdown_function(function () {
         $this->shutdown(true);
     });
     $this->setTitle(Daemon::$runName . ': worker process' . (Daemon::$config->pidfile->value !== Daemon::$config->defaultpidfile->value ? ' (' . Daemon::$config->pidfile->value . ')' : ''));
     if (isset(Daemon::$config->group->value)) {
         $sg = posix_getgrnam(Daemon::$config->group->value);
     }
     if (isset(Daemon::$config->user->value)) {
         $su = posix_getpwnam(Daemon::$config->user->value);
     }
     $flushCache = false;
     if (Daemon::$config->chroot->value !== '/') {
         if (posix_getuid() != 0) {
             Daemon::log('You must have the root privileges to change root.');
             exit(0);
         } elseif (!chroot(Daemon::$config->chroot->value)) {
             Daemon::log('Couldn\'t change root to \'' . Daemon::$config->chroot->value . '\'.');
             exit(0);
         }
         $flushCache = true;
     }
     if (isset(Daemon::$config->group->value)) {
         if ($sg === FALSE) {
             Daemon::log('Couldn\'t change group to \'' . Daemon::$config->group->value . '\'. You must replace config-variable \'group\' with existing group.');
             exit(0);
         } elseif ($sg['gid'] != posix_getgid() && !posix_setgid($sg['gid'])) {
             Daemon::log('Couldn\'t change group to \'' . Daemon::$config->group->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno));
             exit(0);
         }
         $flushCache = true;
     }
     if (isset(Daemon::$config->user->value)) {
         if ($su === FALSE) {
             Daemon::log('Couldn\'t change user to \'' . Daemon::$config->user->value . '\', user not found. You must replace config-variable \'user\' with existing username.');
             exit(0);
         } elseif ($su['uid'] != posix_getuid() && !posix_setuid($su['uid'])) {
             Daemon::log('Couldn\'t change user to \'' . Daemon::$config->user->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno));
             exit(0);
         }
         $flushCache = true;
     }
     if ($flushCache) {
         clearstatcache(true);
     }
     if (Daemon::$config->cwd->value !== '.') {
         if (!@chdir(Daemon::$config->cwd->value)) {
             Daemon::log('Couldn\'t change directory to \'' . Daemon::$config->cwd->value . '.');
         }
         clearstatcache(true);
     }
 }
function archive_stream_zip_directory($root, $archive = 'archive.zip')
{
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    date_default_timezone_set('UTC');
    if (!class_exists('RecursiveIteratorIterator') || !function_exists('gzdeflate')) {
        return 1;
    }
    if (!file_exists($root)) {
        return 2;
    }
    if (function_exists('proc_nice')) {
        proc_nice(19);
    }
    $files = array();
    $added = array();
    $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root), RecursiveIteratorIterator::SELF_FIRST);
    $zip = new ArchiveStream_Zip($archive);
    foreach ($objects as $name => $object) {
        // http://php.net/manual/en/splfileinfo.getbasename.php
        $basename = $object->getBasename();
        if ('.' === $basename || '..' === $basename || $object->isDir()) {
            continue;
        }
        $zip->add_file_from_path(ltrim($name, '/'), $name);
        //DBG echo $name.'<br>';
        $added[] = $name;
    }
    $zip->finish();
    if (function_exists('proc_nice')) {
        proc_nice(0);
    }
    return $added;
}