-
Notifications
You must be signed in to change notification settings - Fork 257
/
watcher.py
914 lines (758 loc) · 31.8 KB
/
watcher.py
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
import copy
import errno
import os
import signal
import time
import sys
from random import randint
import site
import functools
from psutil import NoSuchProcess
from zmq.utils.jsonapi import jsonmod as json
from zmq.eventloop import ioloop
from circus.process import Process, DEAD_OR_ZOMBIE, UNEXISTING
from circus import logger
from circus import util
from circus.stream import get_pipe_redirector, get_stream
from circus.util import parse_env_dict, resolve_name
class Watcher(object):
"""
Class managing a list of processes for a given command.
Options:
- **name**: name given to the watcher. Used to uniquely identify it.
- **cmd**: the command to run. May contain *$WID*, which will be
replaced by **wid**.
- **args**: the arguments for the command to run. Can be a list or
a string. If **args** is a string, it's splitted using
:func:`shlex.split`. Defaults to None.
- **numprocesses**: Number of processes to run.
- **working_dir**: the working directory to run the command in. If
not provided, will default to the current working directory.
- **shell**: if *True*, will run the command in the shell
environment. *False* by default. **warning: this is a
security hazard**.
- **uid**: if given, is the user id or name the command should run
with. The current uid is the default.
- **gid**: if given, is the group id or name the command should run
with. The current gid is the default.
- **send_hup**: if True, a process reload will be done by sending
the SIGHUP signal. Defaults to False.
- **env**: a mapping containing the environment variables the command
will run with. Optional.
- **rlimits**: a mapping containing rlimit names and values that will
be set before the command runs.
- **stdout_stream**: a mapping that defines the stream for
the process stdout. Defaults to None.
Optional. When provided, *stdout_stream* is a mapping containing up to
three keys:
- **class**: the stream class. Defaults to
`circus.stream.FileStream`
- **filename**: the filename, if using a FileStream
- **max_bytes**: maximum file size, after which a new output file is
opened. defaults to 0 which means no maximum size.
- **backup_count**: how many backups to retain when rotating files
according to the max_bytes parameter. defaults to 0 which means
no backups are made.
This mapping will be used to create a stream callable of the specified
class.
Each entry received by the callable is a mapping containing:
- **pid** - the process pid
- **name** - the stream name (*stderr* or *stdout*)
- **data** - the data
- **stderr_stream**: a mapping that defines the stream for
the process stderr. Defaults to None.
Optional. When provided, *stderr_stream* is a mapping containing up to
three keys:
- **class**: the stream class. Defaults to `circus.stream.FileStream`
- **filename**: the filename, if using a FileStream
- **max_bytes**: maximum file size, after which a new output file is
opened. defaults to 0 which means no maximum size.
- **backup_count**: how many backups to retain when rotating files
according to the max_bytes parameter. defaults to 0 which means
no backups are made.
This mapping will be used to create a stream callable of the specified
class.
Each entry received by the callable is a mapping containing:
- **pid** - the process pid
- **name** - the stream name (*stderr* or *stdout*)
- **data** - the data
- **priority** -- integer that defines a priority for the watcher. When
the Arbiter do some operations on all watchers, it will sort them
with this field, from the bigger number to the smallest.
(default: 0)
- **singleton** -- If True, this watcher has a single process.
(default:False)
- **use_sockets** -- If True, the processes will inherit the file
descriptors, thus can reuse the sockets opened by circusd.
(default: False)
- **on_demand** -- If True, the processes will be started only
at the first connection to the socket
(default: False)
- **copy_env** -- If True, the environment in which circus is running
run will be reproduced for the workers. (default: False)
- **copy_path** -- If True, circusd *sys.path* is sent to the
process through *PYTHONPATH*. You must activate **copy_env** for
**copy_path** to work. (default: False)
- **max_age**: If set after around max_age seconds, the process is
replaced with a new one. (default: 0, Disabled)
- **max_age_variance**: The maximum number of seconds that can be added to
max_age. This extra value is to avoid restarting all processes at the
same time. A process will live between max_age and
max_age + max_age_variance seconds.
- **hooks**: callback functions for hooking into the watcher startup
and shutdown process. **hooks** is a dict where each key is the hook
name and each value is a 2-tuple with the name of the callable
or the callabled itself and a boolean flag indicating if an
exception occuring in the hook should not be ignored.
Possible values for the hook name: *before_start*, *after_start*,
*befor_spawn*, *before_stop*, *after_stop*.
- **options** -- extra options for the worker. All options
found in the configuration file for instance, are passed
in this mapping -- this can be used by plugins for watcher-specific
options.
- **respawn** -- If set to False, the processes handled by a watcher will
not be respawned automatically. (default: True)
- **virtualenv** -- The root directory of a virtualenv. If provided, the
watcher will load the environment for its execution. (default: None)
- **close_child_stdout**: If True, closes the stdout after the fork.
default: False.
- **close_child_stderr**: If True, closes the stderr after the fork.
default: False.
"""
def __init__(self, name, cmd, args=None, numprocesses=1, warmup_delay=0.,
working_dir=None, shell=False, uid=None, max_retry=5,
gid=None, send_hup=False, env=None, stopped=True,
graceful_timeout=30., prereload_fn=None,
rlimits=None, executable=None, stdout_stream=None,
stderr_stream=None, priority=0, loop=None,
singleton=False, use_sockets=False, copy_env=False,
copy_path=False, max_age=0, max_age_variance=30,
hooks=None, respawn=True, autostart=True, on_demand=False,
virtualenv=None, close_child_stdout=False,
close_child_stderr=False, **options):
self.name = name
self.use_sockets = use_sockets
self.on_demand = on_demand
self.res_name = name.lower().replace(" ", "_")
self.numprocesses = int(numprocesses)
self.warmup_delay = warmup_delay
self.cmd = cmd
self.args = args
self._process_counter = 0
self.stopped = stopped
self._stopping = False
self.graceful_timeout = float(graceful_timeout)
self.prereload_fn = prereload_fn
self.executable = None
self.priority = priority
self.stdout_stream_conf = copy.copy(stdout_stream)
self.stderr_stream_conf = copy.copy(stderr_stream)
self.stdout_stream = get_stream(self.stdout_stream_conf)
self.stderr_stream = get_stream(self.stderr_stream_conf)
self.stdout_redirector = self.stderr_redirector = None
self.max_retry = max_retry
self._options = options
self.singleton = singleton
self.copy_env = copy_env
self.copy_path = copy_path
self.virtualenv = virtualenv
self.max_age = int(max_age)
self.max_age_variance = int(max_age_variance)
self.ignore_hook_failure = ['before_stop', 'after_stop']
self.respawn = respawn
self.autostart = autostart
self.close_child_stdout = close_child_stdout
self.close_child_stderr = close_child_stderr
self.loop = loop or ioloop.IOLoop.instance()
if singleton and self.numprocesses not in (0, 1):
raise ValueError("Cannot have %d processes with a singleton "
" watcher" % self.numprocesses)
self.optnames = (("numprocesses", "warmup_delay", "working_dir",
"uid", "gid", "send_hup", "shell", "env",
"max_retry", "cmd", "args", "graceful_timeout",
"executable", "use_sockets", "priority", "copy_env",
"singleton", "stdout_stream_conf", "on_demand",
"stderr_stream_conf", "max_age", "max_age_variance",
"close_child_stdout", "close_child_stderr")
+ tuple(options.keys()))
if not working_dir:
# working dir hasn't been set
working_dir = util.get_working_dir()
self.working_dir = working_dir
self.processes = {}
self.shell = shell
self.uid = uid
self.gid = gid
if self.copy_env:
self.env = os.environ.copy()
if self.copy_path:
path = os.pathsep.join(sys.path)
self.env['PYTHONPATH'] = path
if env is not None:
self.env.update(env)
else:
if self.copy_path:
raise ValueError(('copy_env and copy_path must have the '
'same value'))
self.env = env
if self.virtualenv:
util.load_virtualenv(self)
# load directories in PYTHONPATH if provided
# so if a hook is there, it can be loaded
if self.env is not None and 'PYTHONPATH' in self.env:
for path in self.env['PYTHONPATH'].split(os.pathsep):
if path in sys.path:
continue
site.addsitedir(path)
self.rlimits = rlimits
self.send_hup = send_hup
self.sockets = self.evpub_socket = None
self.arbiter = None
self.hooks = {}
self._resolve_hooks(hooks)
def _reload_hook(self, key, hook, ignore_error):
hook_name = key.split('.')[-1]
self._resolve_hook(hook_name, hook, ignore_error)
def _reload_stream(self, key, val):
parts = key.split('.', 1)
if parts[0] == 'stdout':
self.stdout_stream_conf[parts[1]] = val
self.stdout_stream = get_stream(self.stdout_stream_conf)
else:
self.stderr_stream_conf[parts[1]] = val
self.stderr_stream = get_stream(self.stderr_stream_conf)
self._create_redirectors()
if self.stdout_redirector is not None:
self.stdout_redirector.start()
if self.stderr_redirector is not None:
self.stderr_redirector.start()
return 1
def _create_redirectors(self):
if self.stdout_stream:
if self.stdout_redirector is not None:
self.stdout_redirector.stop()
self.stdout_redirector = get_pipe_redirector(
self.stdout_stream, loop=self.loop)
else:
self.stdout_redirector = None
if self.stderr_stream:
if self.stderr_redirector is not None:
self.stderr_redirector.stop()
self.stderr_redirector = get_pipe_redirector(
self.stderr_stream, loop=self.loop)
else:
self.stderr_redirector = None
def _resolve_hook(self, name, callable_or_name, ignore_failure):
if callable(callable_or_name):
self.hooks[name] = callable_or_name
else:
# will raise ImportError on failure
self.hooks[name] = resolve_name(callable_or_name)
if ignore_failure:
self.ignore_hook_failure.append(name)
def _resolve_hooks(self, hooks):
"""Check the supplied hooks argument to make sure we can find
callables"""
if hooks is None:
return
for name, (callable_or_name, ignore_failure) in hooks.items():
self._resolve_hook(name, callable_or_name, ignore_failure)
@classmethod
def load_from_config(cls, config):
if 'env' in config:
config['env'] = parse_env_dict(config['env'])
cfg = config.copy()
w = cls(name=config.pop('name'), cmd=config.pop('cmd'), **config)
w._cfg = cfg
return w
@util.debuglog
def initialize(self, evpub_socket, sockets, arbiter):
self.evpub_socket = evpub_socket
self.sockets = sockets
self.arbiter = arbiter
def __len__(self):
return len(self.processes)
def notify_event(self, topic, msg):
"""Publish a message on the event publisher channel"""
json_msg = json.dumps(msg)
if isinstance(json_msg, unicode):
json_msg = json_msg.encode('utf8')
if isinstance(self.res_name, unicode):
name = self.res_name.encode('utf8')
else:
name = self.res_name
multipart_msg = ["watcher.%s.%s" % (name, topic), json.dumps(msg)]
if self.evpub_socket is not None and not self.evpub_socket.closed:
self.evpub_socket.send_multipart(multipart_msg)
@util.debuglog
def reap_process(self, pid, status=None):
"""ensure that the process is killed (and not a zombie)"""
process = self.processes.pop(pid)
if not status:
while True:
try:
_, status = os.waitpid(pid, os.WNOHANG)
except OSError as e:
if e.errno == errno.EAGAIN:
time.sleep(0.001)
continue
elif e.errno == errno.ECHILD:
# nothing to do here, we do not have any child
# process running
# but we still need to send the "reap" signal.
logger.debug('reaping already dead process %s [%s]',
pid, self.name)
self.notify_event(
"reap",
{"process_pid": pid, "time": time.time()})
return
else:
raise
# get return code
if os.WIFSIGNALED(status):
os.WTERMSIG(status)
# process exited using exit(2) system call; return the
# integer exit(2) system call has been called with
elif os.WIFEXITED(status):
os.WEXITSTATUS(status)
else:
# should never happen
raise RuntimeError("Unknown process exit status")
# if the process is dead or a zombie try to definitely stop it.
if process.status in (DEAD_OR_ZOMBIE, UNEXISTING):
process.stop()
logger.debug('reaping process %s [%s]', pid, self.name)
self.notify_event("reap", {"process_pid": pid, "time": time.time()})
@util.debuglog
def reap_processes(self):
"""Reap all the processes for this watcher.
"""
if self.stopped:
logger.debug('do not reap processes as the watcher is stopped')
return
# reap_process changes our dict, look through the copy of keys
for pid in self.processes.keys():
self.reap_process(pid)
@util.debuglog
def manage_processes(self):
"""Manage processes."""
if self.stopped:
return
# removing old processes
if self.max_age:
max_age = self.max_age + randint(0, self.max_age_variance)
for process in list(self.processes.itervalues()):
if process.age() <= max_age:
continue
logger.debug('%s: expired, respawning', self.name)
self.notify_event("expired", {"process_pid": process.pid,
"time": time.time()})
self.processes.pop(process.pid)
if process.status != DEAD_OR_ZOMBIE:
self.kill_process(process)
# adding fresh processes
if (self.respawn and len(self.processes) < self.numprocesses
and not self._stopping):
self.spawn_processes()
# removing extra processes
processes = self.processes.values()
processes.sort()
while len(processes) > self.numprocesses:
process = processes.pop(0)
if process.status == DEAD_OR_ZOMBIE:
self.processes.pop(process.pid)
else:
self.processes.pop(process.pid)
self.kill_process(process)
@util.debuglog
def reap_and_manage_processes(self):
"""Reap & manage processes."""
if self.stopped:
return
self.reap_processes()
self.manage_processes()
@util.debuglog
def spawn_processes(self):
"""Spawn processes.
"""
# when an on_demand process dies, do not restart it until
# the next event
if self.on_demand and not self.arbiter.socket_event:
self.stopped = True
return
for i in range(self.numprocesses - len(self.processes)):
self.spawn_process()
time.sleep(self.warmup_delay)
def _get_sockets_fds(self):
# XXX should be cached
if self.sockets is None:
return {}
fds = {}
for name, sock in self.sockets.items():
fds[name] = sock.fileno()
return fds
def spawn_process(self):
"""Spawn process.
"""
if self.stopped:
return
if not self.call_hook('before_spawn'):
self.stopped = True
return False
cmd = util.replace_gnu_args(self.cmd, sockets=self._get_sockets_fds(),
env=self.env)
self._process_counter += 1
nb_tries = 0
while nb_tries < self.max_retry or self.max_retry == -1:
process = None
pipe_stdout = self.stdout_redirector is not None
pipe_stderr = self.stderr_redirector is not None
try:
process = Process(self._process_counter, cmd,
args=self.args, working_dir=self.working_dir,
shell=self.shell, uid=self.uid, gid=self.gid,
env=self.env, rlimits=self.rlimits,
executable=self.executable,
use_fds=self.use_sockets, watcher=self,
pipe_stdout=pipe_stdout,
pipe_stderr=pipe_stderr,
close_child_stdout=self.close_child_stdout,
close_child_stderr=self.close_child_stderr)
# stream stderr/stdout if configured
if pipe_stdout and self.stdout_redirector is not None:
self.stdout_redirector.add_redirection('stdout',
process,
process.stdout)
if pipe_stderr and self.stderr_redirector is not None:
self.stderr_redirector.add_redirection('stderr',
process,
process.stderr)
self.processes[process.pid] = process
logger.debug('running %s process [pid %d]', self.name,
process.pid)
except OSError as e:
logger.warning('error in %r: %s', self.name, str(e))
if process is None:
nb_tries += 1
continue
else:
self.notify_event("spawn", {"process_pid": process.pid,
"time": time.time()})
time.sleep(self.warmup_delay)
return
self.stop()
def kill_process(self, process, sig=signal.SIGTERM):
"""Kill process.
"""
# remove redirections
if self.stdout_redirector is not None and process.stdout is not None:
self.stdout_redirector.remove_redirection(process.stdout)
if self.stderr_redirector is not None and process.stderr is not None:
self.stderr_redirector.remove_redirection(process.stderr)
logger.debug("%s: kill process %s", self.name, process.pid)
try:
# sending the same signal to all the children
for child_pid in process.children():
process.send_signal_child(child_pid, sig)
self.notify_event("kill", {"process_pid": child_pid,
"time": time.time()})
# now sending the signal to the process itself
self.send_signal(process.pid, sig)
self.notify_event("kill", {"process_pid": process.pid,
"time": time.time()})
except NoSuchProcess:
# already dead !
return
process.stop()
@util.debuglog
def kill_processes(self, sig):
"""Kill all the processes of this watcher.
"""
for process in self.get_active_processes():
try:
self.kill_process(process, sig)
except OSError as e:
if e.errno != errno.ESRCH:
raise
@util.debuglog
def send_signal(self, pid, signum):
if pid in self.processes:
process = self.processes[pid]
process.send_signal(signum)
else:
logger.debug('process %s does not exist' % pid)
def send_signal_processes(self, signum):
for pid in self.processes:
try:
self.send_signal(pid, signum)
except OSError as e:
if e.errno != errno.ESRCH:
raise
@util.debuglog
def send_signal_child(self, pid, child_id, signum):
"""Send signal to a child.
"""
process = self.processes[pid]
try:
process.send_signal_child(int(child_id), signum)
except OSError as e:
if e.errno != errno.ESRCH:
raise
@util.debuglog
def send_signal_children(self, pid, signum):
"""Send signal to all children.
"""
process = self.processes[int(pid)]
process.send_signal_children(signum)
@util.debuglog
def status(self):
if self.stopped:
return "stopped"
return "active"
@util.debuglog
def process_info(self, pid):
process = self.processes[int(pid)]
return process.info()
@util.debuglog
def info(self):
return dict([(proc.pid, proc.info())
for proc in self.processes.values()])
@util.debuglog
def stop(self, async=True, restarting=False):
"""Stop.
"""
logger.debug('stopping the %s watcher' % self.name)
logger.debug('gracefully stopping processes [%s] for %ss' % (
self.name, self.graceful_timeout))
# We ignore the hook result
self.call_hook('before_stop')
# sending a SIGTERM to all processes
for process in self.get_active_processes():
self.send_signal(process.pid, signal.SIGTERM)
self._stopping = True
# delayed SIGKILL if async is True
limit = time.time() + self.graceful_timeout
if async:
self.loop.add_callback(functools.partial(self._final_stop,
limit=limit,
restarting=restarting,
async=async))
else:
self._final_stop(limit=limit, restarting=restarting, async=async)
def _final_stop(self, limit=None, restarting=False, async=True):
# if we still got some active ones lets wait
actives = self.get_active_processes()
if actives and time.time() < limit and limit is not None:
if async:
# we're back in .2 seconds
callmeback = functools.partial(self._final_stop, limit,
restarting, async)
self.loop.add_timeout(time.time() + .2, callmeback)
return
else:
while time.time() < limit:
actives = self.get_active_processes()
if not actives:
break
time.sleep(.1)
# kill the remaining with SIGKILL
for process in actives:
self.kill_processes(signal.SIGTERM)
# stop redirectors
if self.stdout_redirector is not None:
self.stdout_redirector.stop()
self.stdout_redirector = None
if self.stderr_redirector is not None:
self.stderr_redirector.stop()
self.stderr_redirector = None
# notify about the stop
if self.evpub_socket is not None:
self.notify_event("stop", {"time": time.time()})
self.stopped = True
self._stopping = False
# We ignore the hook result
self.call_hook('after_stop')
logger.info('%s stopped', self.name)
if restarting:
logger.info('restarting %s', self.name)
self.loop.add_callback(self.start)
def get_active_processes(self):
"""return a list of pids of active processes (not already stopped)"""
return [p for p in self.processes.values()
if p.status not in (DEAD_OR_ZOMBIE, UNEXISTING)]
@property
def pids(self):
"""Returns a list of PIDs"""
return [process.pid for process in self.processes]
def call_hook(self, hook_name):
"""Call a hook function"""
kwargs = {'watcher': self, 'arbiter': self.arbiter,
'hook_name': hook_name}
if hook_name in self.hooks:
try:
result = self.hooks[hook_name](**kwargs)
error = None
self.notify_event("hook_success",
{"name": hook_name, "time": time.time()})
except Exception, error:
logger.exception('Hook %r failed' % hook_name)
result = hook_name in self.ignore_hook_failure
self.notify_event("hook_failure",
{"name": hook_name, "time": time.time(),
"error": str(error)})
return result
else:
return True
@util.debuglog
def start(self):
"""Start.
"""
if not self.stopped:
return
if self.on_demand and not self.arbiter.socket_event:
return
self.stopped = False
if not self.call_hook('before_start'):
logger.debug('Aborting startup')
self.stopped = True
return False
self._create_redirectors()
self.reap_processes()
self.spawn_processes()
if not self.call_hook('after_start'):
logger.debug('Aborting startup')
self.stop()
return False
if self.stdout_redirector is not None:
self.stdout_redirector.start()
if self.stderr_redirector is not None:
self.stderr_redirector.start()
logger.info('%s started' % self.name)
self.notify_event("start", {"time": time.time()})
return True
@util.debuglog
def restart(self, async=True):
"""Restart.
"""
self.notify_event("restart", {"time": time.time()})
if not async:
self.stop(async=False)
if self.start():
logger.info('%s restarted', self.name)
else:
logger.info('Failed to restart %s', self.name)
else:
self.stop(async=async, restarting=True)
@util.debuglog
def reload(self, graceful=True):
""" reload
"""
if self.prereload_fn is not None:
self.prereload_fn(self)
if not graceful:
return self.restart()
if self.send_hup:
for process in self.processes.values():
logger.info("SENDING HUP to %s" % process.pid)
process.send_signal(signal.SIGHUP)
else:
for i in range(self.numprocesses):
self.spawn_process()
self.manage_processes()
self.notify_event("reload", {"time": time.time()})
logger.info('%s reloaded', self.name)
def set_numprocesses(self, np):
if np < 0:
np = 0
if self.singleton and np > 1:
raise ValueError('Singleton watcher has a single process')
self.numprocesses = np
self.manage_processes()
return self.numprocesses
@util.debuglog
def incr(self, nb=1):
return self.set_numprocesses(self.numprocesses + nb)
@util.debuglog
def decr(self, nb=1):
return self.set_numprocesses(self.numprocesses - nb)
def set_opt(self, key, val):
"""Set a watcher option.
This function set the watcher options. unknown keys are ignored.
This function return an action number:
- 0: trigger the process management
- 1: trigger a graceful reload of the processes;
"""
action = 0
if key in self._options:
self._options[key] = val
action = -1 # XXX for now does not trigger a reload
elif key == "numprocesses":
val = int(val)
if val < 0:
val = 0
if self.singleton and val > 1:
raise ValueError('Singleton watcher has a single process')
self.numprocesses = val
elif key == "warmup_delay":
self.warmup_delay = float(val)
elif key == "working_dir":
self.working_dir = val
action = 1
elif key == "uid":
self.uid = util.to_uid(val)
action = 1
elif key == "gid":
self.gid = util.to_gid(val)
action = 1
elif key == "send_hup":
self.send_hup = val
elif key == "shell":
self.shell = val
action = 1
elif key == "env":
self.env = val
action = 1
elif key == "cmd":
self.cmd = val
action = 1
elif key == "graceful_timeout":
self.graceful_timeout = float(val)
action = -1
elif key == "max_age":
self.max_age = int(val)
action = 1
elif key == "max_age_variance":
self.max_age_variance = int(val)
action = 1
elif (key.startswith('stdout_stream') or
key.startswith('stderr_stream')):
action = self._reload_stream(key, val)
elif key.startswith('hook'):
val = val.split(',')
if len(val) == 2:
ignore_error = util.to_bool(val[1])
else:
ignore_error = False
hook = val[0]
self._reload_hook(key, hook, ignore_error)
action = 1
# send update event
self.notify_event("updated", {"time": time.time()})
return action
def do_action(self, num):
# trigger needed action
self.stopped = False
if num == 0:
self.manage_processes()
else:
# graceful restart
self.stop(async=False, restarting=True)
@util.debuglog
def options(self, *args):
options = []
for name in sorted(self.optnames):
if name in self._options:
options.append((name, self._options[name]))
else:
options.append((name, getattr(self, name)))
return options