[php] daemon manager

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
class ManagerDaemon
{
private $pid = null;
private $dev_pid = null;
// Когда установится в TRUE, демон завершит работу
protected $stop_server = false;
protected $trace;
// объект по работе с очередями
protected $qIpc = null;
protected $pidFile = '/tmp/daemon.pid';
public static function i()
{
if (empty(self::$_instance)) {
self::$_instance = new ManagerDaemon();
}
return self::$_instance;
}
function __construct()
{
// логирование
$this->trace = new DebugInfo();
if(!empty(Globals::i()->config["m_daemon_log"]))
$this->trace->pathLog = LOG_DIR . "/" .Globals::i()->config["m_daemon_log"];
else
$this->trace->pathLog = LOG_DIR . "/daemonManager.log";
// если есть pid-файл, то скорее всего запущен ещё один процесс
$this->pid = getmypid();
$pidOld = false;
if (file_exists($this->pidFile)) {
$pidOld = file_get_contents($this->pidFile);
}
if ($pidOld != false && file_exists("/proc/" . $pidOld)) {
trigger_error(
"ERR: manager_daemon has running (double parent proc "
. $this->pid . ")", E_USER_ERROR
);
exit();
}
if (file_put_contents($this->pidFile, $this->pid) === false) {
trigger_error("ERR: PID file don't writable", E_USER_ERROR);
}
$this->qIpc = new IPC();
pcntl_signal(SIGTERM, array($this, "childSignalHandler"));
pcntl_signal(SIGCHLD, array($this, "childSignalHandler"));
}
function __destruct()
{
unlink($this->pidFile);
unset($this->trace);
unset($this->qIpc);
}
public function childSignalHandler($signo, $pid = null, $status = null)
{
switch ($signo) {
case SIGTERM:
// При получении сигнала завершения работы устанавливаем флаг
$this->stop_server = true;
break;
case SIGCHLD:
break;
default:
// все остальные сигналы
}
}
protected function run_proc($path)
{
$output = trim(shell_exec($path));
if (!$output) {
return false;
}
if (strpos($output, "\n")) {
$output = explode("\n", $output);
$output = end($output);
}
return intval(substr($output, -strspn(strrev($output), "0123456789")));
}
/**
* Отправка команд дочернему процессу осуществляется
* через функции семафоры.
*/
public function works()
{
$schedule = new Schedule();
$DBH = DB::i();
while (!$this->stop_server) {
$this->schedule_on = Globals::getOption("schedule_on");
// проверка дочернего процесса
$this->devicesCtl();
// контроль ресурса очереди сообщений
$this->qIpc->msg_que_ctl();
$event = $DBH->fetch("SELECT * FROM `events` ORDER BY `start_time` DESC LIMIT 1");
if (!$event)
{
$this->createEvent();
continue;
}
$this->eventId = $event['event_id'];
$closeBetsInterval = Globals::i()->config['close_bets_interval'];
$closeEventsInterval = Globals::i()->config['close_event_interval'];
if (intval($event['finish_time']) == 0 || $event['external_finish'] == 1)
{
$this->just_started = false;
//handling current event
$startTime = strtotime($event['start_time']);
$diff = $startTime - time();
$this->trace->clog("Handling event #" . $this->eventId . " : $diff seconds left");
switch (true)
{
case $diff <= -1 * $closeEventsInterval: //event should be finished by now
$this->closeEvent();
$this->csleep(1);
break;
case $diff <= 0: //event running
$this->csleep($closeEventsInterval + $diff);
break;
case $diff <= $closeBetsInterval: //closing bets
$this->trace->clog("Started video capturing: " .
Globals::startCapture($event['event_id'])
);
$this->closeBets();
$diff = $startTime - time();
if ($diff <= 0)
$this->trace->clog("Event #" . $this->eventId . " already ///");
else
$this->csleep($diff);
break;
default:
$this->csleep($diff - $closeBetsInterval);
}
}
else //no new events
{
if ($this->eventId != $this->lastEventId)
{
$this->trace->clog('Event ' . $this->eventId . ' finished; Stopping capture');
Globals::stopCapture($this->eventId);
$this->lastEventId = $this->eventId;
$this->qIpc->msg_send("CMD for daemon");
}
if ($this->just_started)
{
$last_change = strtotime(DB::i()->fetch("SELECT `when` FROM `rats_lane_assignment` ORDER BY `when` DESC LIMIT 1"));
$last_race = strtotime($event['start_time']);
if ($schedule->getSessionStartTimestamp() != $schedule->getSessionStartTimestamp($last_race - 1) && $last_change < $last_race)
{
if (!$this->idle)
$this->trace->clog("Last race started at " . $event['start_time'] . " which is older than current session start: " . date('c', $schedule->getSessionStartTimestamp()) . " while team outdated at " . date('c', $last_change) . " : forcing team change!");
Globals::setOption("team_change", $last_race + 1);
}
}
else
{
if (!$schedule->getRacesTillBreak() && !Globals::getOption("team_change")) //reboot arduino during break
{
$this->trace->clog("Going on a break");
Globals::setOption("team_change", time());
$this->csleep(10);
$this->trace->clog("Importing bets...");
MathImport::importBets();
if ($schedule->getNextEventTime() - time() > 900) //large breaks
{
foreach (MathHelper::getMathModelsList() as $model_id)
{
$mObject = MathModelFactory::i()->create($model_id);
if (is_object($mObject) && method_exists($mObject, "update"))
{
$this->trace->clog("Updating model $model_id to event ".$this->eventId."...");
$mObject->update($this->eventId);
}
}
}
}
}
if (!$this->schedule_on)
{
if (!$this->idle)
$this->trace->clog("[IDLE]Event creation disabled");
$this->idle = true;
$this->csleep(20);
}
else
{
$this->createEvent();
$this->csleep(5);
}
}
}
$this->qIpc->msg_remove();
}
private function devicesCtl()
{
if ($this->dev_pid && !file_exists("/proc/" . $this->dev_pid)) {
$this->trace->clog("Dev daemon is dead, restarting...\n");
$this->dev_pid = null;
}
if ($this->dev_pid == null) {
$this->dev_pid = $this->run_proc(
BIN_DIR . '/AManager/dev_daemon.sh'
);
if ($this->dev_pid > 0) {
$this->trace->clog(
"Start dev daemon, PID is " . $this->dev_pid
);
} else {
$this->trace->clog("Error start dev daemon $this->dev_pid");
}
}
}
/**
* @param $secs - значение в секундах
*/
protected function csleep($secs)
{
$start = microtime(true);
if (!$this->idle)
$this->trace->clog("Sleeping for $secs seconds...");
if ($secs < 0)
return true;
$slstep = pow(10, 3); // step
do {
usleep($slstep);
}
while((microtime(true) - $start)<$secs);
}
}
$child_pid = pcntl_fork();
if ($child_pid) {
exit;
}
if (empty(Globals::i()->config["m_daemon_log"])) {
$logFile = LOG_DIR . "/daemonManager.log";
} else {
$logFile = LOG_DIR . "/" .Globals::i()->config["m_daemon_log"];
}
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
$STDIN = fopen('/dev/null', 'r');
$STDOUT = fopen($logFile, 'ab');
$STDERR = fopen($logFile, 'ab');
ManagerDaemon::i()->run();