-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.py
1545 lines (1334 loc) · 49.1 KB
/
process.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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
"""
The process module is the base for processes.
The process module cannot be ran on its own. The intended use for this
module is as a base for running and implementing processes. The
run_process() function is implemented in such a way that a command-line
process launcher could import this module and call the function. An
example script would be as such:
from stockpile.processing.process import run_process
if __name__ == "__main__":
exit(run_process())
Processes can be implemented two separate ways. The simplest way is as a
Configurable Process. A Configurable Process is simply a JSON file
describing the process under the "processing/processes/configs"
directory. The file's name must begin with an alphanumeric character and
any proceeding characters must be either alphanumeric or underscores. It
must be suffixed with the ".json" extension. The file must contain only
a dict (object). The dict must have the "title", "desc" and "cmd" keys
set. "title" is the title (str) of the process. "desc" is a description
(str) of the process. "cmd" is the command (str) to execute. An example
Process Config would be developed as such:
{{"#": "processing/processes/configs/myprocess.json",
"title": "My Process",
"desc": "This process runs my command.",
"cmd": "/path/to/my/command"
}}
A process can also be implemented in a more complicated way as a Process
Module. A Process Module is a folder (python package module) with an
"__init__.py" script under the "processing/processes/modules" directory.
The folder's name must begin with an alphanumeric character and any
proceeding characters must be either alphanumeric or underscores. The
script must define a class that subclasses the `Process` class and that
either is or is referenced by the `process` module attribute. This class
must set the `title`, `desc` and `worker` class attributes. `title` is
the title (str) of the process. `desc` is a description (str) of the
process. `worker` is an instance of the `Worker` class (or subclass
there of). An example Process Module would be developed as such:
#processing/processes/modules/myprocess/__init__.py
from stockpile.processing.process import Process, Worker
class MyProcess(Process):
title = "My Process"
desc = "This process runs my command."
worker = Worker('/path/to/my/command')
process = MyProcess
Process Modules and Configuration can be organized a hierarchical folder
structures under their respective directories: "processing/processes/
modules" for modules; and "processing/processes/configs" for configs.
All folders must being with an alphanumeric character and any proceeding
characters must be either alphanumeric or underscores. NOTE: Process
Modules take precedence over Process Configs; therefore, if a Process
Module and a Process Config both were to share the same effective name,
then the Process Module would be used.
E.g.,
Process Module:
file = "processing/processes/modules/myprocess/__init__.py"
name = "myprocess"
Process Config:
file = "processing/processes/configs/myprocess.json"
name = "myprocess"
The results of find_process() or get_process() would return results
pertaining to the Process Module named "myprocess" not the Process
Config.
Constants:
CLIENT_PORT (int)
- The default port that the Process Server listens for clients on:
`{client_port!r}`.
SERVER (str)
- The default name of the Process Server: {server!r}.
STDIN_FD (int)
- The FD used by STDIN: `{stdin!r}`.
STDOUT_FD (int)
- The FD used by STDOUT: `{stdout!r}`.
STDERR_FD (int)
- The FD used by STDERR: `{stderr!r}`.
STDLOG_FD (int)
- The FD used by a process to monitor log/status output from its
underlying worker: `{stdlog}`.
Path Prefixes:
PREFIX_LOCAL_RUN (str)
- The path to the local run-time data file directory: {local_run!r}.
PREFIX_LOCAL_VAR (str)
- The path to the local variable data file directory: {local_var!r}.
PREFIX_USR_RUN (str)
- The path to the run-time date file directory: {usr_run!r}
PREFIX_USR_VAR (str)
- The path to the variable data file directory: {usr_var!r}.
PREFIX_TMP (str)
- The path to the temporary data file directory: {tmp!r}.
Process Types:
MODULE (str)
- The process is defined by a Process Module: {module!r}.
CONFIG (str)
- The process is defined by a Process Config: {config!r}.
TODO:
- When the server root object raises a DeadReferenceError, stop trying
to update the server, try re-connecting and re-registering to the
server, and if the server cannot be connected to, then give up on the
server but continue running normally.
"""
__author__ = "Caleb"
__version__ = "0.8"
__status__ = "Development"
__project__ = "stockpile"
import atexit as _atexit
import errno as _errno
import imp as _imp
import inspect as _inspect
import json as _json
import os as _os
import re as _re
import shlex as _shlex
import signal as _signal
import sys as _sys
import time as _time
import traceback as _traceback
from twisted.internet import defer as _defer, error as _error, protocol as _protocol, reactor as _reactor
from twisted.spread import pb as _pb
import _daemon
CLIENT_PORT = 8087
SERVER = "processserver"
STDIN_FD = 0
STDOUT_FD = 1
STDERR_FD = 2
STDLOG_FD = 3
PREFIX_LOCAL_RUN = "/var/local/run"
PREFIX_LOCAL_VAR = "/var/local"
PREFIX_USR_RUN = "/var/run"
PREFIX_USR_VAR = "/var"
PREFIX_TMP = "/tmp"
MODULE = 'module'
CONFIG = 'config'
_dir = _os.path.dirname(_os.path.abspath(__file__))
_mod_dir = "%s/processes/modules" % _dir
_conf_dir = "%s/processes/configs" % _dir
__doc__ = __doc__.format(
dir=_dir,
client_port=CLIENT_PORT,
server=SERVER,
stdin=STDIN_FD,
stdout=STDOUT_FD,
stderr=STDERR_FD,
stdlog=STDLOG_FD,
local_run=PREFIX_LOCAL_RUN,
local_var=PREFIX_LOCAL_VAR,
usr_run=PREFIX_USR_RUN,
usr_var=PREFIX_USR_VAR,
tmp=PREFIX_TMP,
module=MODULE,
config=CONFIG
)
_connect_tmo = 1
_worker_check = 1.0
_worker_delay = 1.0
_proc_dir_perm = 0o755
_re_proc_basename = _re.compile(r'''
^ # Match beginning of string.
[\w][\w_]* # A word (alphanumeric followed by alphanumeric/underscore).
$ # Match until end of string.
''', _re.VERBOSE)
_re_proc_fullname = _re.compile(r'''
^ # Match beginning of string.
[\w][\w_]* # A word (alphanumeric followed by alphanumeric/underscore).
(?: # Optionally, followed by:
\. # a period
[\w][\w_]* # and another word
)* # any number of times.
$ # Match until end of string.
''', _re.VERBOSE)
_help = """
Usage: %prog [options] [<<< 'ARGS']
Arguments:
process The name of the process to run.
Worker Arguments:
To send arguments to the underlying process worker, arguments must be
piped or redirected into the standard input stream (stdin).
A bash here-doc/string can be used to send data into stdin:
i.e., %prog [options] <<< 'ARGS'
- E.g., %prog [options] <<< '-my args'
The output from a command can be piped into the stdin:
i.e., COMMAND | %prog [options]
- E.g., echo '-my args' | %prog [options]
The contents of a file can also be redirected to stdin:
i.e., %prog [options] [< FILE]
- E.g., %prog [options] < my_args.file
""".strip()
def _import_process_module(filepath, fullname):
"""
Returns the specified process module.
Arguments:
filepath (str)
- The file path to process module.
fullname (str)
- The fully qualified name of the process module:
i.e., {processing}.processes.modules.{process_name}
Returns:
(module) -- The process module.
"""
mod_dir, mod_name = _os.path.split(filepath)
fh, path, desc = _imp.find_module(mod_name, [mod_dir])
try:
_imp.acquire_lock()
try:
proc_mod = _imp.load_module(fullname, fh, path, desc)
finally:
_imp.release_lock()
finally:
if fh:
fh.close()
return proc_mod
def _read_process_config(filepath):
"""
Returns the specified process config.
Arguments:
filepath (str)
- The file path to process config.
Returns:
(dict) -- The process config.
"""
with open(filepath) as fh:
proc_conf = _json.load(fh)
return proc_conf
def check_process_basename(basename):
"""
Checks to see if the process basename is an alphanumeric/underscored
basename.
Arguments:
basename (str)
- A process basename.
Returns:
(bool)
- If the basename is valid, `True`; otherwise, `False`.
"""
if not isinstance(basename, basestring):
raise TypeError("Process basename:%r is not a string." % basename)
return bool(_re_proc_basename.match(basename))
def check_process_name(fullname):
"""
Checks to see if the process name is a string of alphanumeric/
underscored basenames separated by periods.
Arguments:
fullname (str)
- The name of the process.
Returns:
(bool)
- If the name is valid, `True`; otherwise, `False`.
"""
if not isinstance(fullname, basestring):
raise TypeError("Process name:%r is not a string." % fullname)
return bool(_re_proc_fullname.match(fullname))
def get_process(process_name):
"""
Returns the specified process.
Arguments:
process_name (str)
- The name of the process to get.
Returns:
(mixed)
- If the process is a module, the process class (Process); if the
process is a configuration, the process config (dict); otherwise,
an InvalidProcess exception is raised.
"""
proc_file, proc_type = find_process(process_name)
if proc_type == MODULE:
# Get modified time.
mtime = _os.stat(proc_file + "/__init__.py").st_mtime
# Import process module.
mod_full = "%s.modules.%s" % (__package__ + ".processes" if __package__ else 'processes', process_name)
proc_mod = _import_process_module(proc_file, mod_full)
# Get process class.
proc_cls = proc_mod.process
proc_cls.name = process_name
proc_cls.mtime = mtime
validate_process_class(process_name, proc_cls)
return proc_cls
elif proc_type == CONFIG:
# Get modified time.
mtime = _os.stat(proc_file).st_mtime
# Read process config.
proc_conf = _read_process_config(proc_file)
proc_conf['name'] = process_name
proc_conf['mtime'] = mtime
validate_process_config(process_name, proc_conf)
return proc_conf
raise LogicError("Process:%r type:%r is not %r." % (process_name, proc_type, ", ".join((MODULE, CONFIG))))
def find_process(process_name):
"""
Searches for the specified process and returns it's file path and
type.
Arguments:
process_name (str)
- The name of the process to find.
Returns:
(tuple)
- A 2-tuple containing: the process file (str), and process type
(str).
"""
if not isinstance(process_name, basestring):
raise TypeError("process_name:%r is not a string." % process_name)
elif not process_name:
raise ValueError("process_name:%r cannot be empty." % process_name)
validate_process_name(process_name)
proc_rel = _os.path.normpath(process_name.replace('.', '/'))
if proc_rel[0] == '.' or proc_rel[0] == '/':
raise LogicError("Process:%r relative path:%r cannot begin with a period or slash." % (process_name, proc_rel))
# Find process module.
mod_path = "%s/%s" % (_mod_dir, proc_rel)
if _os.path.isdir(mod_path):
files = _os.listdir(mod_path)
if "__init__.py" in files:
return mod_path, MODULE
# Find process config.
conf_path = "%s/%s.json" % (_conf_dir, proc_rel)
if _os.path.isfile(conf_path):
return conf_path, CONFIG
# Since the process could not be found, raise an exception.
raise InvalidProcess("Process %r does not exist." % process_name, process_name)
def list_processes():
"""
Returns the list of processes.
Returns:
(set) -- The list of processes.
"""
procs = []
# Scan process modules.
offset = len(_mod_dir) + 1
for path, dirs, files in _os.walk(_mod_dir):
# Skip any sub-directories that do not match the folder naming
# convention.
dirs[:] = [d for d in dirs if _re_proc_basename.match(d)]
# Check to see if this directory is a python package.
if "__init__.py" not in files:
continue
filename = path + "/__init__.py"
# Since this is a python package, check its script's size.
try:
size = _os.stat(filename).st_size
except Exception:
continue
if size > 2:
# Since the python package script is not empty (consider files
# with a single "\n" or a "\r\n" as empty; i.e., 1 or 2 bytes),
# trim the process modules directory path and proceeding slash off
# the process module path.
proc_name = path[offset:].replace('/', '.')
procs.append(proc_name)
# Scan process configs.
offset = len(_conf_dir) + 1
for path, dirs, files in _os.walk(_conf_dir):
# Skip any sub-directories that do not match the folder naming
# convention.
dirs[:] = [d for d in dirs if _re_proc_basename.match(d)]
# Check to see if any files match the config naming convention.
for filename in files:
base, ext = _os.path.splitext(filename)
if ext.lower() == ".json" and _re_proc_basename.match(base):
# Since we have a process config, add it to the list.
proc_name = path[offset:].replace('/', '.')
proc_name += '.' + base if proc_name else base
procs.append(proc_name)
# Returns processes (removing duplicates).
return set(procs)
def run_process(args=None):
"""
The default function for running a process from the command-line.
Optional Arguments:
args (list)
- The command line arguments to use (including the command-line
program name in the first index); default is `sys.argv`.
Returns:
(int) -- On success, `0`; otherwise, a non-zero integer.
"""
import optparse
if not args:
args = _sys.argv
# Parse options.
prog = _os.path.basename(args[0]) + " process"
parser = optparse.OptionParser(prog=prog, usage=_help)
parser.add_option('-s', '--server-name', dest='name', help="The name of the Process Server application; default is %r; mutually exclusive with '--server-socket' and '--no-server'." % SERVER, metavar="NAME")
parser.add_option('-f', '--server-socket', dest='socket', help="The Process Server socket file; default is %r then %r; mutually exclusive with '--server-name' and '--no-server'." % ("%s/{server_name}/processes.socket" % PREFIX_LOCAL_RUN, "%s/{server_name}/processes.socket" % PREFIX_USR_RUN), metavar="FILE")
parser.add_option('-n', '--no-server', dest='no_server', help="Run the process stand-alone without a Process Server; mutually exclusive with '--server-name', '--server-socket' and '--server-token'.", action='store_true')
parser.add_option('-t', '--server-token', dest='token', help="The server provided token to use when registering (this is used when the server starts the process); mutually exclusive with '--no-server'.", metavar="TOKEN")
parser.add_option('-r', '--run-path', dest='run', help="The run-time data file directory for the process; default is %r." % '.', metavar="PATH")
parser.add_option('-d', '--debug', dest='debug', help="Enable process debugging.", action='store_true')
parser.add_option('-i', '--inline', dest='inline', help="Run the process inline instead of daemonizing it (this is mainly useful for debugging processes).", action='store_true')
options, args = parser.parse_args(args[1:])
# Get arguments/options.
proc_name = args[0] if len(args) else None
if proc_name is None:
parser.print_help()
return 0
name = options.name
socket = options.socket
token = options.token
no_server = options.no_server
run = options.run
debug = options.debug
inline = options.inline
# Check arguments/options.
if no_server is not None:
if name is not None:
raise ValueError("no_server:%r is mutually exclusive with server_name:%r." % (no_server, name))
elif socket is not None:
raise ValueError("no_server:%r is mutually exclusive with server_socket:%r." % (no_server, socket))
elif token is not None:
raise ValueError("no_server:%r is mutually exclusive with server_token:%r." % (no_server, token))
elif name is not None and socket is not None:
raise ValueError("server_name:%r and server_token:%r are mutually exclusive." % (name, socket))
# Read stdin.
stdin = _sys.stdin.readline() if not _sys.stdin.isatty() else None
# Setup process keyword arguments.
proc_kw = {
'use_server': not no_server,
'server_name': name,
'server_socket': socket,
'server_token': token,
'args': stdin,
'path': run,
'debug': debug
}
# Get and instantiate process.
proc = get_process(proc_name)
if _inspect.isclass(proc) and issubclass(proc, Process):
proc = proc(**proc_kw)
elif isinstance(proc, dict):
proc = ConfigurableProcess(proc, **proc_kw)
else:
raise LogicError("get_process:%r returned a process:%r that is not a Process subclass or dict." % (get_process, proc))
# Run process.
daemon = _daemon.RunDaemon(lambda: proc.main())
return daemon.run() if inline else daemon.start()
def validate_process_class(process_name, process_class):
"""
Validates the process class (or instance).
Arguments:
process_name (str)
- The name of the process class.
process_class (mixed)
- The process class (class) or instance (Process) to validate.
"""
if not hasattr(process_class, 'name'):
raise AttributeError("%s.name is not set." % process_name)
elif not isinstance(process_class.name, basestring):
raise TypeError("%s.name is not a string." % (process_name, process_class.name))
elif not process_class.name:
raise ValueError("%s.name:%r cannot be an empty string." % (process_name, process_class.name))
elif not _re_proc_fullname.match(process_class.name):
raise ValueError("%s.name:%r is not a string of alphanumeric/underscored basenames separated by periods." % (process_name, process_class.name))
elif process_class.name != process_name:
raise ValueError("%s.name:%r does not match said process:%r." % (process_class.name, process_name))
if not hasattr(process_class, 'title'):
raise AttributeError("%s.title is not set." % process_name)
elif not isinstance(process_class.title, basestring):
raise TypeError("%s.title:%r is not a string." % (process_name, process_class.title))
elif not process_class.title:
raise ValueError("%s.title:%r cannot be an empty string." % (process_name, process_class.title))
if not hasattr(process_class, 'desc'):
raise AttributeError("%s.desc is not set." % process_name)
elif not isinstance(process_class.desc, basestring):
raise TypeError("%s.desc:%r is not a float." % (process_name, process_class.desc))
if not hasattr(process_class, 'mtime'):
raise AttributeError("%s.mtime is not set." % process_name)
elif not isinstance(process_class.mtime, float):
raise TypeError("%s.mtime:%r is not a float." % (process_name, process_class.mtime))
if not hasattr(process_class, 'worker'):
raise AttributeError("%s.worker is not set." % process_name)
elif not isinstance(process_class.worker, IWorker):
raise TypeError("%s.worker:%r is not a IWorker instance." % (process_name, process_class.worker))
def validate_process_config(process_name, process_config):
"""
Validates the process config.
Arguments:
process_name (str)
- The name of the process class.
process (dict)
- The process config.
"""
if 'name' not in process_config:
raise KeyError("%s[name] is not set." % process_name)
elif not isinstance(process_config['name'], basestring):
raise TypeError("%s[name] is not a string." % (process_name, process_config['name']))
elif not process_config['name']:
raise ValueError("%s[name]:%r cannot be an empty string." % (process_name, process_config['name']))
elif not _re_proc_fullname.match(process_config['name']):
raise ValueError("%s[name]:%r is not a string of alphanumeric/underscored basenames separated by periods." % (process_name, process_config['name']))
elif process_config['name'] != process_name:
raise ValueError("%s[name]:%r does not match said process:%r." % (process_config['name'], process_name))
if 'title' not in process_config:
raise KeyError("%s[title] is not set." % process_name)
elif not isinstance(process_config['title'], basestring):
raise TypeError("%s[title]:%r is not a string." % (process_name, process_config['title']))
elif not process_config['title']:
raise ValueError("%s[title]:%r cannot be an empty string." % (process_name, process_config['title']))
if 'desc' not in process_config:
raise KeyError("%s[desc] is not set." % process_name)
elif not isinstance(process_config['desc'], basestring):
raise TypeError("%s[desc]:%r is not a string." % (process_name, process_config['desc']))
if 'mtime' not in process_config:
raise KeyError("%s[mtime] is not set." % process_name)
elif not isinstance(process_config['mtime'], float):
raise TypeError("%s[mtime]:%r is not a float." % (process_name, process_config['mtime']))
if 'cmd' not in process_config:
raise KeyError("%s[cmd] is not set." % process_name)
elif not isinstance(process_config['cmd'], basestring):
raise TypeError("%s[cmd]:%r is not a string." % (process_name, process_config['cmd']))
elif not process_config['cmd']:
raise ValueError("%s[cmd]:%r cannot be an empty string." % (process_name, process_config['cmd']))
def validate_process_basename(basename):
"""
Validates a process basename by raising an exception if it is not an
alphanumeric/underscored basename.
Arguments:
basename (str)
- The basename of a process.
"""
if not isinstance(basename, basestring):
raise TypeError("Process basename:%r is not a string." % basename)
elif not _re_proc_basename.match(basename):
raise ValueError("Process basename:%r is not an alphanumeric/underscored basename." % basename)
def validate_process_name(fullname):
"""
Validates the specified process name by raising an exception if it is
not a list of alphanumeric/underscored basenames separated by periods.
Arguments:
fullname (str)
- The name of the process.
"""
if not isinstance(fullname, basestring):
raise TypeError("Process name:%r is not a string." % fullname)
elif not _re_proc_fullname.match(fullname):
raise ValueError("Process name:%r is not a string of alphanumeric/underscored basenames separated by periods." % fullname)
def validate_process_names(fullnames):
"""
Validates the specified process names by raising an exception if any
of them are not a string of alphanumeric/underscored basenames
separated by periods.
Arguments:
fullnames (list)
- The list of process names to validate.
"""
if not hasattr(fullnames, '__iter__'):
raise TypeError("Process names list:%r is not iterable." % fullnames)
bad = [repr(n) for n in fullnames if not isinstance(n, basestring)]
if bad:
raise TypeError("Process names list contains %i non-string name(s): %s." % (len(bad), ", ".join(bad)))
bad = [repr(n) for n in fullnames if not _re_proc_fullname.match(n)]
if bad:
raise TypeError("Process names list contains %i name(s) that are not strings of alphanumeric/underscored basenames separated by periods: %s." % (len(bad), ", ".join(bad)))
def color_worker_output(fd, output):
"""
Returns colored output for the worker.
Arguments:
fd (int) -- The file descriptor the output is from.
output (str) -- The output to color.
Returns:
(str) -- The colored output.
"""
if fd == 1:
return "\033[34m" + output + "\033[0m"
elif fd == 2:
return "\033[31m" + output + "\033[0m"
elif fd == 3:
return "\033[35m" + output + "\033[0m"
return "\033[36m" + output + "\033[0m"
class ProcessError(Exception):
"""
The Process Exception class is the base class that all process
exceptions will inherit from.
"""
class DebugError(ProcessError):
"""
The Debug Error exception is raised for debugging.
"""
class LogicError(ProcessError):
"""
The Logic Error exception is raised when a condition is met that
should be impossible if the logic is actually correct.
"""
class AlreadyRunning(ProcessError):
"""
The Already Running exception is raised when a process tries
registering but a process exists that is already running (starting or
registered).
"""
class InvalidProcess(ProcessError):
"""
The Invalid Process exception is raised when client tries accessing a
process that does not exist.
Instance Attributes:
args (tuple) -- The exception arguments.
message (str) -- The error message.
process_name (str) -- The name of the invalid process.
"""
def __init__(self, message, process_name):
"""
Initializes an InvalidProcess exception.
Arguments:
message (str) -- The error message.
process_name (str) -- The name of the invalid process.
"""
self.args = (message, process_name)
self.message = message
self.process_name = process_name
def __str__(self):
"""
Converts this exception into a string.
Returns:
(str) -- The exception message.
"""
return self.message
class InvalidProcessInstance(ProcessError):
"""
The Invalid Process Instance exception is raised when client tries
accessing a process instance that is not running.
Instance Attributes:
args (tuple) -- The exception arguments.
message (str) -- The error message.
process_id (str) -- The instance ID of the process.
"""
def __init__(self, message, process_id):
"""
Initializes an InvalidProcess exception.
Arguments:
message (str) -- The error message.
process_id (str) -- The instance ID of the process.
"""
self.args = (message, process_id)
self.message = message
self.process_id = process_id
def __str__(self):
"""
Converts this exception into a string.
Returns:
(str) -- The exception message.
"""
return self.message
class NotRegistered(ProcessError):
"""
The Not Registered exception is raised when a process tries
performaing an action on the server before its registering.
"""
class TerminateProcess(ProcessError):
"""
The Terminate Process exception is raised when the server wants to
terminate the process for being a naughty little school girl.
"""
class ProcessProtocol(_protocol.ProcessProtocol):
"""
The Process Protocol class handles the interaction between a Process
and a Worker instance.
Instance Attributes:
ready (callable)
- Called when the sub-process starts and is ready to received input
on stdin; called with arguments: the process protocol
(ProcessProtocol).
done (callable)
- Called when the sub-process is done executing and either was
killed by a signal or returned with an exit status; called with
arguments: the process protocol (ProcessProtocol) and the exit
status (int). If the sub-process was killed by a signal, the exit
status will be the additive inverse of the signal's integer value
(i.e., the signal's opposite or negative value).
recv (dict)
- Called when data is received from the sub-process; called with
arguments: the process protocol (ProcessProtocol), the file
descriptor (int) the data was received from, and the data received
(str).
"""
def __init__(self, ready=None, done=None, recv=None):
"""
Instantiates a Process Protocol instance.
Arguments:
ready (callable)
- Called when the sub-process starts and is ready to received
input on stdin; called with arguments: the process protocol
(ProcessProtocol).
done (callable)
- Called when the sub-process is done executing and either was
killed by a signal or returned with an exit status; called with
arguments: the process protocol (ProcessProtocol) and the exit
status (int). If the sub process was killed by a signal, the
exit status will be the additive inverse of the signal's integer
value (i.e., the signal's opposite or negative value).
recv (callable)
- Called when data is received from the sub-process; called with
arguments: the process protocol (ProcessProtocol), the file
descriptor (int) the data was received from, and the data
received (str).
"""
if ready is not None and not callable(ready):
raise TypeError("ready:%r is not callable." % ready)
if done is not None and not callable(done):
raise TypeError("done:%r is not callable." % done)
if recv is not None and not callable(recv):
raise TypeError("recv:%r is not callable." % recv)
self.ready = ready
self.done = done
self.recv = recv
def connectionMade(self):
"""
Called when a connection is made between the process and sub-process
(i.e., it's started).
This method is called once the sub-process is started. This is the
ideal place to write to the stdin pipe. Closing stdin is a common
way to indicate an EOF to the sub-process.
"""
if self.ready:
try:
self.ready(self)
except Exception:
_traceback.print_exc()
self.transport.closeStdin()
def childDataReceived(self, childFD, data):
"""
Called when output from the sub-process is received.
Arguments:
childFD (int) -- The file descriptor the data was received from.
data (str) -- The output data.
"""
if self.recv:
try:
self.recv(self, childFD, data)
except Exception:
_traceback.print_exc()
def processEnded(self, status):
"""
Called when process is finished.
Arguments:
status (twisted.python.failure.Failure)
- On success, the status will have a `twisted.internet.error.
ProcessDone` instance stored in its `value` attribute;
otherwise, the status will have a `twisted.internet.error.
ProcessTerminiated` instance (with an `exitCode` attribute)
stored in its `value` attribute.
"""
if self.done:
# Ignore the provided status and instead use the process transport
# exit status. The exit status is a 16-bit integer whose low byte
# is the signal that killed the process and whose high byte is the
# returned exit status.
# - See: http://docs.python.org/library/os.html#os.waitpid
status = self.transport.status
exit = status >> 8 if status > 0xFF else -(status & 0xFF)
try:
self.done(self, exit)
except Exception:
_traceback.print_exc()
class Process(_pb.Referenceable):
"""
The Process class manages inter-process communication between itself,
its worker and the Process Server, and its stateful and run-time
information.
Abstract Class Attributes:
name (str)
- The name of the process.
mtime (float)
- The time (UTC) that the process was last modified.
worker (IWorker)
- The worker to execute for this process.
Instance Attributes:
debug (bool)
- Whether process debugging is enabled or not.
exit (int)
- The exit code the process returns when it stops.
pid (int)
- The OS PID (not available until main() is run).
run_dir (str)
- The run-time data files directory path.
tmp_dir (str)
- The temporary data files directory path.
var_dir (str)
- The variable data files directory path.
log_dir (str)
- The log data files directory path.
pid_file (str)
- The PID file path.
exit_file (str)
- The file that the process's exit status is written to.
out_file (str)
- The file that the process's stdout (fd1) is written to.
err_file (str)
- The file that the process's stderr (fd2) is written to.
log_file (str)
- The file that the process's stdlod (fd3) is written to.
use_server (bool)
- Whether the process should connect to the Process Server or simply
run stand-alone.
server_error (bool)
- Whether there was an error connecting/registering with the server
or not.
server_factory (twisted.spread.pb.PBClientFactory)
- The process server PB factory.
server_id (int)
- If this process is registered, the process ID assigned by the
server; otherwise, `None`.
server_socket (str)
- The Process Server's UNIX socket file that processes connect to.
server (twisted.spread.pb.RemoteReference):
- The Process Server root reference.
worker_args (list)
- The process worker arguments.
worker_buffs (dict)
- The buffered output from the worker keyed by the output file
descriptors.
worker_check (float)
- The interval (seconds) at which the current worker is signaled for
its status.
worker_delay (float)
- The initial duration (seconds) at which the current worker will
not be signaled for its status.
worker_exit (int)
- The worker exit status when the worker is done executing;
otherwise, `None`.
worker_last (int)
- The time (seconds) that the worker last responded with its status.
worker_trans (twisted.internet.interfaces.IProcessTransport)
- The transport interface to the worker.
Temporary Instance Attributes:
_server_token (str)
- The server provided token to use when registering (this is used
when the server starts the process).
_spawn_args (list)
- The position arguments to use for spawning the sub-process
(worker).
_spawn_kw (dict)
- The keyword arguments to use for spawning the sub-process
(worker).
"""
def __init__(self, use_server=None, server_name=None, server_socket=None, server_token=None, args=None, path=None, debug=False):
"""
Initializes a process instance.
Optional Arguments:
use_server (bool)
- Whether the process should connect to the Process Server or
simply run stand-alone; default is `True`.
server_name (str)
- The name of the Process Server; default is {server_name!r}.
server_socket (str)
- The process server UNIX socket file; default is {local_socket!r}
then {usr_socket!r}.
server_token (str)
- The server provided token to use when registering (this is used
when the server starts the process); default is `None`.
args (mixed)
- The arguments (list or string) for this process. If args is a
string, the arguments will be parsed to a list using the shlex
module; default is `None`.
path (str)
- The run-time data file directory; default is ".".
debug (bool)
- Whether process debugging should be enabled or not; default is
`False`.
""".format(
server_name=SERVER,
local_socket=("%s/%s/processes.socket" % (PREFIX_LOCAL_RUN, "{server_name}")),
usr_socket=("%s/%s/processes.socket" % (PREFIX_USR_RUN, "{server_name}"))
)
# Validate self.
validate_process_class(getattr(self, 'name', "%s.%s" % (self.__class__.__module__, self.__class__.__name__)), self)