Skip to content

Instantly share code, notes, and snippets.

@Invis1ble
Created September 6, 2017 13:44
Show Gist options
  • Save Invis1ble/f6b62f8e88fb287aedf8addc1803b4b2 to your computer and use it in GitHub Desktop.
Save Invis1ble/f6b62f8e88fb287aedf8addc1803b4b2 to your computer and use it in GitHub Desktop.
Node.js HTTP service watchdog
#!/usr/bin/env php
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
set_time_limit(0);
$serviceHost = '127.0.0.1';
$servicePort = 1234;
$command = 'some-service start --port ' . $servicePort;
$serviceBinDirectory = '/usr/local/bin';
$timeout = 8;
$debug = false;
if ($debug) {
echo "Setting up environment... ";
}
putenv('PATH=' . getenv('PATH') . ':' . $serviceBinDirectory);
if ($debug) {
echo "OK.\n";
}
$expectedResponse = '{"error":"Not found"}';
function inspectCode(int $code, int $expected = 0) {
global $debug;
if ($expected !== $code) {
if ($debug) {
echo "Got exit code $code. Terminated.\n";
}
exit($code);
}
}
if ($debug) {
echo "Checking service... ";
}
$uri = $serviceHost . ':' . $servicePort;
$ch = curl_init($uri);
curl_setopt_array($ch, [
CURLOPT_HEADER => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);
curl_close($ch);
if ($expectedResponse === $response) {
if ($debug) {
echo "OK.\n";
}
exit(0);
}
if ($debug) {
echo "bad response.\n";
echo "Looking for a process... ";
}
exec('ps -ef | grep some-service ', $output, $code);
inspectCode($code);
if ($debug) {
echo "OK.\n";
}
$pid = null;
$process = null;
foreach ($output as $line) {
$pieces = preg_split('#\s+#', $line, 8);
if (false === $pieces || !isset($pieces[7])) {
if ($debug) {
echo "Can\'t parse line \"$line\". Terminated.\n";
}
exit(1);
}
$process = $pieces[7];
if (preg_match('#^node /(?:\pL+/)*some-service start#u', $process)) {
$pid = $pieces[1];
break;
}
}
if (null === $pid) {
if ($debug) {
echo "Process is not found.\n";
}
} else {
echo "Process \"$process\" [PID $pid] found.\n";
echo "Killing process... ";
exec('kill -9 ' . $pid, $output, $code);
inspectCode($code);
if ($debug) {
echo "OK.\n";
}
}
if ($debug) {
echo "Starting new process... ";
}
exec('nohup ' . $command . ' >> /dev/null 2>&1 &', $output, $code);
inspectCode($code);
if ($debug) {
echo "OK.\n";
echo "Done.\n";
}
exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment