3 final class PhutilDaemonHandle
extends Phobject
{
5 const EVENT_DID_LAUNCH
= 'daemon.didLaunch';
6 const EVENT_DID_LOG
= 'daemon.didLogMessage';
7 const EVENT_DID_HEARTBEAT
= 'daemon.didHeartbeat';
8 const EVENT_WILL_GRACEFUL
= 'daemon.willGraceful';
9 const EVENT_WILL_EXIT
= 'daemon.willExit';
22 private $stdoutBuffer;
23 private $shouldRestart = true;
24 private $shouldShutdown;
25 private $hibernating = false;
26 private $shouldSendExitEvent = false;
28 private function __construct() {
32 public static function newFromConfig(array $config) {
33 PhutilTypeSpec
::checkMap(
37 'argv' => 'optional list<string>',
38 'load' => 'optional list<string>',
39 'log' => 'optional string|null',
40 'down' => 'optional int',
43 $config = $config +
array(
51 $daemon->properties
= $config;
52 $daemon->daemonID
= $daemon->generateDaemonID();
57 public function setDaemonPool(PhutilDaemonPool
$daemon_pool) {
58 $this->pool
= $daemon_pool;
62 public function getDaemonPool() {
66 public function getBusyEpoch() {
67 return $this->busyEpoch
;
70 public function getDaemonClass() {
71 return $this->getProperty('class');
74 private function getProperty($key) {
75 return idx($this->properties
, $key);
78 public function setCommandLineArguments(array $arguments) {
79 $this->argv
= $arguments;
83 public function getCommandLineArguments() {
87 public function getDaemonArguments() {
88 return $this->getProperty('argv');
91 public function didLaunch() {
92 $this->restartAt
= time();
93 $this->shouldSendExitEvent
= true;
96 self
::EVENT_DID_LAUNCH
,
98 'argv' => $this->getCommandLineArguments(),
99 'explicitArgv' => $this->getDaemonArguments(),
105 public function isRunning() {
106 return (bool)$this->getFuture();
109 public function isHibernating() {
111 !$this->isRunning() &&
116 public function wakeFromHibernation() {
117 if (!$this->isHibernating()) {
124 'Process is being awakened from hibernation.'));
126 $this->restartAt
= time();
132 public function isDone() {
133 return (!$this->shouldRestart
&& !$this->isRunning());
136 public function update() {
137 if (!$this->isRunning()) {
138 if (!$this->shouldRestart
) {
141 if (!$this->restartAt ||
(time() < $this->restartAt
)) {
144 if ($this->shouldShutdown
) {
147 $this->startDaemonProcess();
150 $future = $this->getFuture();
154 if ($future->canResolve()) {
155 $this->future
= null;
157 $result = $future->resolve();
158 } catch (Exception
$ex) {
160 } catch (Throwable
$ex) {
165 list($stdout, $stderr) = $future->read();
166 $future->discardBuffers();
168 if (strlen($stdout)) {
169 $this->didReadStdout($stdout);
172 $stderr = trim($stderr);
173 if (strlen($stderr)) {
174 foreach (phutil_split_lines($stderr, false) as $line) {
175 $this->logMessage('STDE', $line);
179 if ($result !== null ||
$caught !== null) {
183 'Process failed with exception: %s',
184 $caught->getMessage());
185 $this->logMessage('FAIL', $message);
187 list($err) = $result;
190 $this->logMessage('FAIL', pht('Process exited with error %s.', $err));
192 $this->logMessage('DONE', pht('Process exited normally.'));
196 if ($this->shouldShutdown
) {
197 $this->restartAt
= null;
199 $this->scheduleRestart();
203 $this->updateHeartbeatEvent();
204 $this->updateHangDetection();
207 private function updateHeartbeatEvent() {
208 if ($this->heartbeat
> time()) {
212 $this->heartbeat
= time() +
$this->getHeartbeatEventFrequency();
213 $this->dispatchEvent(self
::EVENT_DID_HEARTBEAT
);
216 private function updateHangDetection() {
217 if (!$this->isRunning()) {
221 if (time() > $this->deadline
) {
222 $this->logMessage('HANG', pht('Hang detected. Restarting process.'));
223 $this->annihilateProcessGroup();
224 $this->scheduleRestart();
228 private function scheduleRestart() {
229 // Wait a minimum of a few sceconds before restarting, but we may wait
230 // longer if the daemon has initiated hibernation.
231 $default_restart = time() + self
::getWaitBeforeRestart();
232 if ($default_restart >= $this->restartAt
) {
233 $this->restartAt
= $default_restart;
239 'Waiting %s second(s) to restart process.',
240 new PhutilNumber($this->restartAt
- time())));
244 * Generate a unique ID for this daemon.
246 * @return string A unique daemon ID.
248 private function generateDaemonID() {
249 return substr(getmypid().':'.Filesystem
::readRandomCharacters(12), 0, 12);
252 public function getDaemonID() {
253 return $this->daemonID
;
256 private function getFuture() {
257 return $this->future
;
260 private function getPID() {
261 $future = $this->getFuture();
267 if (!$future->hasPID()) {
271 return $future->getPID();
274 private function getCaptureBufferSize() {
278 private function getRequiredHeartbeatFrequency() {
282 public static function getWaitBeforeRestart() {
286 public static function getHeartbeatEventFrequency() {
290 private function getKillDelay() {
294 private function getDaemonCWD() {
295 $root = dirname(phutil_get_library_root('phabricator'));
296 return $root.'/scripts/daemon/exec/';
299 private function newExecFuture() {
300 $class = $this->getDaemonClass();
301 $argv = $this->getCommandLineArguments();
302 $buffer_size = $this->getCaptureBufferSize();
304 // NOTE: PHP implements proc_open() by running 'sh -c'. On most systems this
305 // is bash, but on Ubuntu it's dash. When you proc_open() using bash, you
306 // get one new process (the command you ran). When you proc_open() using
307 // dash, you get two new processes: the command you ran and a parent
308 // "dash -c" (or "sh -c") process. This means that the child process's PID
309 // is actually the 'dash' PID, not the command's PID. To avoid this, use
310 // 'exec' to replace the shell process with the real process; without this,
311 // the child will call posix_getppid(), be given the pid of the 'sh -c'
312 // process, and send it SIGUSR1 to keepalive which will terminate it
313 // immediately. We also won't be able to do process group management because
314 // the shell process won't properly posix_setsid() so the pgid of the child
315 // won't be meaningful.
317 $config = $this->properties
;
318 unset($config['class']);
319 $config = phutil_json_encode($config);
321 return id(new ExecFuture('exec ./exec_daemon.php %s %Ls', $class, $argv))
322 ->setCWD($this->getDaemonCWD())
323 ->setStdoutSizeLimit($buffer_size)
324 ->setStderrSizeLimit($buffer_size)
329 * Dispatch an event to event listeners.
331 * @param string Event type.
332 * @param dict Event parameters.
335 private function dispatchEvent($type, array $params = array()) {
337 'id' => $this->getDaemonID(),
338 'daemonClass' => $this->getDaemonClass(),
339 'childPID' => $this->getPID(),
342 $event = new PhutilEvent($type, $data);
345 PhutilEventEngine
::dispatchEvent($event);
346 } catch (Exception
$ex) {
351 private function annihilateProcessGroup() {
352 $pid = $this->getPID();
354 $pgid = posix_getpgid($pid);
356 posix_kill(-$pgid, SIGTERM
);
357 sleep($this->getKillDelay());
358 posix_kill(-$pgid, SIGKILL
);
363 private function startDaemonProcess() {
364 $this->logMessage('INIT', pht('Starting process.'));
366 $this->deadline
= time() +
$this->getRequiredHeartbeatFrequency();
367 $this->heartbeat
= time() + self
::getHeartbeatEventFrequency();
368 $this->stdoutBuffer
= '';
369 $this->hibernating
= false;
371 $future = $this->newExecFuture();
372 $this->future
= $future;
374 $pool = $this->getDaemonPool();
375 $overseer = $pool->getOverseer();
376 $overseer->addFutureToPool($future);
379 private function didReadStdout($data) {
380 $this->stdoutBuffer
.= $data;
382 $pos = strpos($this->stdoutBuffer
, "\n");
383 if ($pos === false) {
386 $message = substr($this->stdoutBuffer
, 0, $pos);
387 $this->stdoutBuffer
= substr($this->stdoutBuffer
, $pos +
1);
390 $structure = phutil_json_decode($message);
391 } catch (PhutilJSONParserException
$ex) {
392 $structure = array();
395 switch (idx($structure, 0)) {
396 case PhutilDaemon
::MESSAGETYPE_STDOUT
:
397 $this->logMessage('STDO', idx($structure, 1));
399 case PhutilDaemon
::MESSAGETYPE_HEARTBEAT
:
400 $this->deadline
= time() +
$this->getRequiredHeartbeatFrequency();
402 case PhutilDaemon
::MESSAGETYPE_BUSY
:
403 if (!$this->busyEpoch
) {
404 $this->busyEpoch
= time();
407 case PhutilDaemon
::MESSAGETYPE_IDLE
:
408 $this->busyEpoch
= null;
410 case PhutilDaemon
::MESSAGETYPE_DOWN
:
411 // The daemon is exiting because it doesn't have enough work and it
412 // is trying to scale the pool down. We should not restart it.
413 $this->shouldRestart
= false;
414 $this->shouldShutdown
= true;
416 case PhutilDaemon
::MESSAGETYPE_HIBERNATE
:
417 $config = idx($structure, 1);
418 $duration = (int)idx($config, 'duration', 0);
419 $this->restartAt
= time() +
$duration;
420 $this->hibernating
= true;
421 $this->busyEpoch
= null;
425 'Process is preparing to hibernate for %s second(s).',
426 new PhutilNumber($duration)));
429 // If we can't parse this or it isn't a message we understand, just
430 // emit the raw message.
431 $this->logMessage('STDO', pht('<Malformed> %s', $message));
437 public function didReceiveNotifySignal($signo) {
438 $pid = $this->getPID();
440 posix_kill($pid, $signo);
444 public function didReceiveReloadSignal($signo) {
445 $signame = phutil_get_signal_name($signo);
448 'Reloading in response to signal %d (%s).',
453 'Reloading in response to signal %d.',
457 $this->logMessage('RELO', $sigmsg, $signo);
459 // This signal means "stop the current process gracefully, then launch
460 // a new identical process once it exits". This can be used to update
461 // daemons after code changes (the new processes will run the new code)
462 // without aborting any running tasks.
464 // We SIGINT the daemon but don't set the shutdown flag, so it will
465 // naturally be restarted after it exits, as though it had exited after an
466 // unhandled exception.
468 $pid = $this->getPID();
470 posix_kill($pid, SIGINT
);
474 public function didReceiveGracefulSignal($signo) {
475 $this->shouldShutdown
= true;
476 $this->shouldRestart
= false;
478 $signame = phutil_get_signal_name($signo);
481 'Graceful shutdown in response to signal %d (%s).',
486 'Graceful shutdown in response to signal %d.',
490 $this->logMessage('DONE', $sigmsg, $signo);
492 $pid = $this->getPID();
494 posix_kill($pid, SIGINT
);
498 public function didReceiveTerminateSignal($signo) {
499 $this->shouldShutdown
= true;
500 $this->shouldRestart
= false;
502 $signame = phutil_get_signal_name($signo);
505 'Shutting down in response to signal %s (%s).',
509 $sigmsg = pht('Shutting down in response to signal %s.', $signo);
512 $this->logMessage('EXIT', $sigmsg, $signo);
513 $this->annihilateProcessGroup();
516 private function logMessage($type, $message, $context = null) {
517 $this->getDaemonPool()->logMessage($type, $message, $context);
519 $this->dispatchEvent(
523 'message' => $message,
524 'context' => $context,
528 public function didExit() {
529 if ($this->shouldSendExitEvent
) {
530 $this->dispatchEvent(self
::EVENT_WILL_EXIT
);
531 $this->shouldSendExitEvent
= false;