-
Notifications
You must be signed in to change notification settings - Fork 2
/
gxpd.py
executable file
·2387 lines (2195 loc) · 87.1 KB
/
gxpd.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
# Copyright (c) 2005-2009 by Kenjiro Taura. All rights reserved.
#
# THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
# EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
#
# Permission is hereby granted to use or copy this program
# for any purpose, provided the above notices are retained on all
# copies. Permission to modify the code and to distribute modified
# code is granted, provided the above notices are retained, and
# a notice that the code was modified is included with the above
# copyright notice.
#
# $Header: /cvsroot/gxp/gxp3/gxpd.py,v 1.25 2013/10/25 12:00:53 ttaauu Exp $
# $Name: $
#
#
# TODO:
# mw ... requires clients to write newlines. otherwise the msg
# does not get through. this stems from the follwing.
# action_create_proc_or_peer ->
# set_pipe_atomicity -> set_expected, where pipe is set
# to have line atomicity.
enable_connection_upgrade = 0
import errno,fcntl,os,random,re,select,signal,socket
import stat,string,sys,time,types
# import profile,pstats
import ioman,gxpm,opt,ifconfig,this_file
dbg=0
# see ChangeLog entry of 2007-12-25
fix_2007_12_25 = 1
# -------------------------------------------------------------------
#
# -------------------------------------------------------------------
# ioman.process_base
# | |
# | +-- ioman.child_process
# | |
# | +-- ioman.pipe_process
# | +-- ioman.sockpair_process
# | |
# +---- gxp_peer |
# | | |
# | +--------------+----- child_peer
# |
# +---- parent_peer
# +---- client_peer
#
class gxp_peer_base(ioman.process_base):
"""
The gxp_peer_base class represents another gxp process
this process connects to. It may be a child gxp process
invoked by this process (it may in fact be an rsh-like
process that remotely forks gxp), a parent gxp process
that invoked this process (it may in fact be an rsh-like
process that locally forked this process), or a command
interpreter or any external process that sends gxp commands
to this process.
"""
STATE_IN_PROGRESS = 0
STATE_LIVE = 1
def __init__(self, name, init_state, critical):
ioman.process_base.__init__(self)
# when state is in progress, it is a child process
# that is not ready to accept commands. i.e. `explore'
# is in progress
self.state = init_state
self.peer_name = name
self.critical = critical
self.wch = None # set by subclass
def write_channel(self):
return self.wch
def set_write_channel(self, ch):
self.wch = ch
class parent_peer(gxp_peer_base):
"""
represent process that spawns me
"""
def __init__(self, name, no_stdin):
gxp_peer_base.__init__(self, name,
gxp_peer_base.STATE_LIVE, 1)
# self.wch = None
# now no_stdin is always zero
assert no_stdin == 0
if no_stdin == 0:
pch0 = ioman.primitive_channel_fd(0, 1)
ch0 = ioman.rchannel_process(pch0, self, None)
ch0.set_expected([("M",)])
pch1 = ioman.primitive_channel_fd(1, 1)
pch2 = ioman.primitive_channel_fd(2, 1)
ch1 = ioman.wchannel_process(pch1, self, None)
ch2 = ioman.wchannel_process(pch2, self, None)
self.set_write_channel(ch1)
self.task = None
def clear_critical(self):
self.critical = 0
def discard(self):
# one day I tried to terminate inst_local.py once it has done
# the job and connection is successfully upgraded.
# need more investigations to make it work
if 0:
for ch in self.r_channels_rev.keys():
ch.discard()
for ch in self.w_channels_rev.keys():
ch.discard()
if 0:
pid = os.fork()
if pid > 0:
os._exit(0)
def is_garbage(self):
return 0
class connect_peer(gxp_peer_base):
"""
represent process that connects to me
"""
def __init__(self, name, so):
gxp_peer_base.__init__(self, name, # peer_name == ""
gxp_peer_base.STATE_LIVE, 0)
pch = ioman.primitive_channel_socket(so, 0)
ch_r = ioman.rchannel_process(pch, self, None)
ch_r.set_expected([("M",)])
ch_w = ioman.wchannel_process(pch, self, None)
self.set_write_channel(ch_w)
self.task = None
def set_critical(self):
self.critical = 1
def discard(self):
pass
def is_garbage(self):
return 0
class child_peer(ioman.child_process,gxp_peer_base):
"""
represent a gxp process that is invoked by me.
It is typically a result of `explore' commands.
"""
upgrading_status_init = 0
upgrading_status_in_progress = 1
upgrading_status_succeeded = 2
upgrading_status_failed = 3
def __init__(self, cmd, pipe_desc, env, cwd, rlimits):
gxp_peer_base.__init__(self, "", # peer_name = ""
gxp_peer_base.STATE_IN_PROGRESS, 0)
ioman.child_process.__init__(self, cmd, pipe_desc, env, cwd, rlimits)
self.target_label = None
self.hostname = None
self.task = None
self.rid = None
self.upgrading_channel_w = None
self.upgrading_channel_r = None
self.upgrading_status = child_peer.upgrading_status_init
class child_task_process(ioman.child_process):
"""
This class represents a non-gxp child process. That is,
processes invoked as a result of `e' commands etc.
"""
def __init__(self, cmd, pipe_desc, env, cwd, rlimits):
ioman.child_process.__init__(self, cmd, pipe_desc, env, cwd, rlimits)
self.task = None
self.rid = None
# -------------------------------------------------------------------
#
# -------------------------------------------------------------------
class task_tree_node:
"""
This class represents a node of a task tree.
a task is conceptually a set of distributed processes.
it is typically the result of executing an 'e' command.
They form a tree along the tree of gxp processes.
The tree is used to route msgs/commands from the command
interpreter to processes, to route msgs from processes to
the command interpreter, and to signal events (termination, etc.)
to the command interpreter.
Though it is called a tree, a single task node may in general
have multiple parents.
"""
def __init__(self, tid):
self.tid = tid # name of the task (string)
self.parent_peers = {} # parents
self.child_peers = {} # child -> weight
# processes are locally running processes constituing
# the task
self.processes = {} # process -> 1
# each process has `a relative process id', which
# identifies a particular process WITHIN a task.
# this is specifieid by the command interpreter to specify
# a particular process it wants to operate on.
# thus we keep a lookup table from relative id to the process
self.proc_by_rid = {} # rid -> proc
self.persist = 0 # 1 if it should never terminate
self.weight = 1
# note : self.processes give pid -> proc
def show(self):
return ("task_tree_node(%s, %d parents, %d children, %d procs, %d proc_by_rid)"
% (self.tid, len(self.parent_peers), len(self.child_peers),
len(self.processes), len(self.proc_by_rid)))
def forward_up(self, m, msg):
"""
send msg m to all parents.
"""
# msg = gxpm.unparse(m) # FASTER ---------
if dbg>=1:
ioman.LOG(("sending up msg to %d parents\n"
% len(self.parent_peers)))
for parent in self.parent_peers.keys():
x = parent.write_msg(msg)
if x == -1:
# this parent has gone
del self.parent_peers[parent]
if dbg>=1:
ioman.LOG("up msg to parent lost %d bytes "
"%d parents left [%s ...]\n"
% (len(msg), len(self.parent_peers), msg[0:30]))
else:
if dbg>=2:
ioman.LOG("up msg to parent OK\n")
# what we should do if we have no parents at all?
def close_connection_to_parent(self, parent):
if dbg>=2:
ioman.LOG("close_connection_to_parent:\n")
x = parent.write_eof()
if dbg>=1 and x == -1:
ioman.LOG("close_connection_to_parent: parent.write_eof() failed\n")
def close_up(self):
"""
If close_on_fin flag is set, this task node has been told
to close channels to the parents upon termination.
So we close them.
"""
for parent,keep_connection in self.parent_peers.items():
if keep_connection < gxpm.keep_connection_forever:
self.close_connection_to_parent(parent)
del self.parent_peers[parent]
def is_dead(self):
"""
This particular node is considered dead if it has no
running child processes and child peers. used to detect
termination of the whole task.
"""
if self.persist: return 0
if len(self.child_peers) > 0: return 0
if len(self.processes) > 0: return 0
return 1
# -------------------------------------------------------------------
# options to bring up gxp
# -------------------------------------------------------------------
class gxpd_opts(opt.cmd_opts):
def __init__(self):
# (type, default)
# types supported
# s : string
# i : int
# f : float
# l : list of strings
# None : flag
opt.cmd_opts.__init__(self)
# gupid of parent gxpd.py
self.parent = ("s", "")
# in which name it is explored
self.target_label = ("s", "")
# address to listen to
self.listen = ("s", "unix:")
# 1 if it is created with --create_session 1
# self.created_explicitly = ("i", 0)
# prefix of stdout/stderr/unix-socket
self.name_prefix = ("s", "gxp-00000000")
self.qlen = ("i", 1000)
self.remove_self = (None, 0)
self.root_gupid = ("s", "")
self.continue_after_close = (None, 0)
# short version
self.p = "parent"
self.l = "listen"
# -------------------------------------------------------------------
#
# -------------------------------------------------------------------
class gxpd_environment:
"""
Environment variables set for gxp daemons and inherited
to subprocesses
"""
def __init__(self, dict):
self.dict = dict
e = os.environ
for k,v in dict.items():
setattr(self, k, v)
e[k] = v
class gxpd_profiler:
def __init__(self):
self.prof_file = None
self.prof = None
self.to_start = 0
self.to_stop = 0
def mark_start(self, file):
import hotshot
if self.prof is None:
self.to_start = 1
self.prof_file = file
self.prof = hotshot.Profile(self.prof_file)
return 0
else:
return -1
def started(self):
self.to_start = 0
def mark_stop(self):
if self.prof is not None:
self.to_stop = 1
return 0
else:
return -1
def stopped(self):
import hotshot.stats
self.to_stop = 0
self.prof.close()
stats = hotshot.stats.load(self.prof_file)
stats.strip_dirs()
stats.sort_stats('time', 'calls')
self.prof_file = None
self.prof = None
# -------------------------------------------------------------------
#
# -------------------------------------------------------------------
def Es(s):
os.write(2, s)
def get_this_file_xxx():
g = globals()
file = None
if __name__ == "__main__" and \
len(sys.argv) > 0 and len(sys.argv[0]) > 0:
# run from command line (python .../gxpd.py)
file = sys.argv[0]
elif g.has_key("__file__"):
# appears this has been loaded as a module
file = g["__file__"]
# if it is .pyc file, get .py instead
m = re.match("(.+)\.pyc$", file)
if m: file = m.group(1) + ".py"
if file is None:
Es("cannot find the location of gxpd.py\n")
return None
#file = os.path.abspath(file)
file = os.path.realpath(file)
if os.access(file, os.F_OK) == 0:
Es("source file %s is missing!\n" % file)
return None
elif os.access(file, os.R_OK) == 0:
Es("cannot read source file %s!\n" % file)
return None
else:
return file
class gxpd(ioman.ioman):
"""
gxp daemon that basically has the following functions.
(1) run a child process
(2) manage all IOs (stdin/out/err, pipes from/to children,
connections to sockets it is listening)
"""
# taken from python 2.4 os module. copied here for portability
# to older python versions
EX_OK = 0
EX_USAGE = 64
EX_OSERR = 71
EX_CONFIG = 78
def init(self, opts):
self.opts = opts
# set of files that should be cleaned up on exit
self.remove_on_exit = []
self.quit = 0
# addresses to accept connections from command interpreters
self.listen_addrs = []
# calc some identification information
# and build globally unique process id
self.hostname = self.gethostname()
self.user_name = self.get_user_name()
self.boot_time = self.get_boot_time()
self.pid = os.getpid()
self.gupid = self.get_gupid()
self.short_gupid = self.get_short_gupid()
# log filename
ioman.set_log_filename("log-%s" % self.gupid)
# hogehoge ----------------------
self.my_addrs = ifconfig.get_my_addrs("") # ugly
self.upgrade_listen_channel = None
# hogehoge ----------------------
# target label
self.target_label = None
# parent peer (set by setup_parent_peer)
self.parent = None
# live tasks
self.tasks = {}
# environment (gxpd_environment)
self.gxpd_env = None
# prof object
self.profiler = gxpd_profiler()
return 0
def gethostname(self):
# gxpd dies with error: AF_UNIX path too long
# an incomplete workaround here.
# truncate FQDN into shorter one
h = socket.gethostname()
m = re.match("(\.*[^\.]*)", h)
assert m
return m.group(1)
def get_boot_time(self):
return time.strftime("%Y-%m-%d-%H-%M-%S")
def get_user_name(self):
return os.environ.get("USER", "unknown")
def get_gupid(self):
"""
gupid = globally unique process id
"""
h = self.hostname
u = self.user_name
t = self.boot_time
pid = self.pid
return "%s-%s-%s-%s" % (h, u, t, pid)
def get_short_gupid(self):
"""
short gupid used to name daemon socket file,
because unix domain socket does not allow too long
pathnames. It does not contain host/user information.
user information is (most of the time) included
in the upper directory name (/tmp/gxp-USER-xxxxx/...).
exclusion of hostname is a potential source of conflict,
but since /tmp is not normally shared, it should be OK...
"""
t = self.boot_time
pid = self.pid
return "%s-%s" % (t, pid)
def get_gxp_tmp(self):
suffix = os.environ.get("GXP_TMP_SUFFIX", "default")
return os.path.join("/tmp", ("gxp-%s-%s" % (self.user_name, suffix)))
def ensure_dir(self, directory):
try:
# os.makedirs(directory, 0777)
os.makedirs(directory, 0700)
except OSError,e:
if e.args[0] == errno.EEXIST:
pass
else:
raise
os.chmod(directory, 0700)
def parse_listen_arg(self, listen_arg, name_prefix): # created_explicitly
"""
Syntax of listen_arg
unix:path | inet:addr:port
path, addr, port may be omitted
Return (AF_TYPE,addr) where addr is whatever is
passed to bind system call.
(for inet sockets, it is (ip_addr,port). for unix domain
sockets, it is a path name).
e.g.,
'unix:hoge' --> (AF_UNIX, 'hoge')
'inet:123.456.78.9:50' --> (AF_INET, ('123.456.78.9', 50))
reasonably handle default cases:
'inet::' --> (AF_INET, ('', 0))
"""
if listen_arg == "":
return None,"" # no error, no listen
fields = string.split(listen_arg, ":", 1)
if len(fields) == 2:
[ af_str, rest ] = fields
elif len(fields) == 1:
[ af_str ] = fields
rest = ""
else:
bomb()
af_str = string.upper(af_str)
if af_str == "TCP" or af_str == "INET":
# find the last ':' and split there
i = string.rfind(rest, ":")
if i == -1:
addr = rest
port = 0
else:
addr = rest[:i]
port = int(rest[i+1:]) # xxxx
return socket.AF_INET,(addr,port)
elif af_str == "UNIX":
path = rest
if path == "":
gxp_tmp = self.get_gxp_tmp()
self.ensure_dir(gxp_tmp)
if 0:
if created_explicitly:
prefix = "Gxpd"
else:
prefix = "gxpd"
path = os.path.join(self.get_gxp_tmp(),
("%s-daemon-%s" % (name_prefix,
self.short_gupid)))
return socket.AF_UNIX,path
elif af_str == "NONE":
return 0,None
else:
return None,None # error
# created_explicitly,
def setup_channel_listen(self, listen_arg, name_prefix, qlen):
"""
Open a socket to listen on. af is an address family
(normally socket.AF_INET), addr is an address to bind to
(we accept anonymous name ("",0), and it is the typical),
and qlen is the queue length (backlog).
return 0 on success, -1 on error
"""
# created_explicitly
af,addr = self.parse_listen_arg(listen_arg, name_prefix)
if addr is None:
if af == 0:
return 0
else:
assert af is None, af
Es("%s : invalid listen addr '%s'\n" \
% (self.gupid, listen_arg))
return -1
s = ioman.mk_non_interruptible_socket(af, socket.SOCK_STREAM)
s.bind(addr)
if af == socket.AF_UNIX:
os.chmod(addr, 0600)
self.remove_on_exit.append(addr)
s.listen(qlen)
# blocking = 1
ch = ioman.achannel(ioman.primitive_channel_socket(s, 1))
self.add_rchannel(ch)
self.listen_addrs.append(addr)
if dbg>=2:
ioman.LOG("listening on %s\n" % addr)
return 0
def redirect_stdout_stderr(self):
# xp = open("/tmp/xxx", "wb")
# os.dup2(xp.fileno(), 2)
# if xp.fileno() > 2: xp.close()
opts = self.opts
if 0:
if opts.created_explicitly:
oprefix = "Gxpout"
eprefix = "Gxperr"
else:
oprefix = "gxpout"
eprefix = "gxperr"
opath = os.path.join(self.get_gxp_tmp(),
("%s-stdout-%s" % (opts.name_prefix, self.gupid)))
epath = os.path.join(self.get_gxp_tmp(),
("%s-stderr-%s" % (opts.name_prefix, self.gupid)))
if dbg>=2:
ioman.LOG("redirecting stdout to %s\n" % opath)
ioman.LOG("redirecting stderr to %s\n" % epath)
op = open(opath, "wb")
os.chmod(opath, 0600)
os.dup2(op.fileno(), 1)
if op.fileno() > 1: op.close()
ep = open(epath, "wb")
os.chmod(epath, 0600)
os.dup2(ep.fileno(), 2)
if ep.fileno() > 2: ep.close()
def setup_parent_peer(self, opts):
"""
Set up a data structure to talk to my parent. It is
not necessarily the process that really `forked' me.
It is rather a `conceptual' parent process which may
be a remote process that did something like
'ssh <this_node> <this_program>.
In any case, I am presumably connected to the conceptual
parent via some file descriptors. For now, we assume file
descriptors 0,1,2 are connected to the parent.
"""
# not useful anymore
# self.redirect_stdout_stderr(opts)
# opts.no_stdin
if dbg>=2:
ioman.LOG(("setup parent peer (name = %s)\n"
% opts.parent))
parent = parent_peer(opts.parent, 0)
for ch in parent.r_channels_rev.keys():
self.add_rchannel(ch)
for ch in parent.w_channels_rev.keys():
self.add_wchannel(ch)
self.parent = parent
return 0
def upgrade_parent_peer(self, ch, ev):
if ev.kind == ioman.ch_event.OK:
if dbg>=2:
ioman.LOG("got connection to upgrade socket\n")
new_parent = connect_peer(self.parent.peer_name,
ev.new_so)
new_parent.set_critical()
if fix_2007_12_25: self.parent.clear_critical()
# self.parent.discard()
# ioman.LOG("yattayo\n")
self.parent = new_parent
for ch in new_parent.r_channels_rev.keys():
self.add_rchannel(ch)
for ch in new_parent.w_channels_rev.keys():
self.add_wchannel(ch)
self.parent.write_msg("Connection upgrade OK\n")
if dbg>=2:
ioman.LOG("sent con upgrade ack to parent\n")
elif ev.kind == ioman.ch_event.TIMEOUT:
if dbg>=2:
ioman.LOG("got timeout to upgrade socket\n")
self.parent.write_msg("Connection upgrade TIMEOUT\n")
if dbg>=2:
ioman.LOG("sent failure notification to parent\n")
elif ev.kind == ioman.ch_event.IO_ERROR:
if dbg>=1:
ioman.LOG("IO error on listen channel\n")
self.quit = 1
else:
assert 0,ev.kind
# ------------- tasks and processes -------------
def check_task_status(self, task):
"""
Check if the task node is already `useless.'
It is useless if it has no running local processes,
and if it has no child task nodes. That is, no processes
are running under the subtree rooted at task.
If so, send an event (event_fin) upward to signal
task death (if the root node becomes garbage, the task
is considered finished).
"""
if task.is_dead():
if dbg>=2:
ioman.LOG("tid %s is dead\n" % task.tid)
# if so, send fin event
m = gxpm.syn(self.gupid,
task.tid, gxpm.event_fin(task.weight))
task.forward_up(m, gxpm.unparse(m))
# close the channel to the parent if told to do so
# (normally so at the root).
task.close_up()
# delete the task in my table
del self.tasks[task.tid]
self.send_event_invalidate_view(task.tid)
def send_event_invalidate_view(self, tid):
"""
send notifications to all connecting gxpc procs
"""
parents = {}
for task in self.tasks.values():
if task.tid == tid: continue
for p in task.parent_peers.keys():
if isinstance(p, connect_peer) and not parents.has_key(p):
if dbg>=1:
ioman.LOG(("send notification to parent peer %s\n"
% p.peer_name))
ev = gxpm.event_invalidate_view()
m = gxpm.up(self.gupid, tid, ev)
msg = gxpm.unparse(m)
x = p.write_msg(msg)
if x == -1:
# this parent has gone
del task.parent_peers[p]
if dbg>=1:
ioman.LOG("notification to parent lost\n")
else:
parents[p] = None
if dbg>=2:
ioman.LOG("notification to parent OK\n")
def cleanup_process(self, p):
# task p belongs to
task = p.task
pid = p.pid
rid = p.rid
if not task.processes.has_key(p.pid):
if dbg>=2:
ioman.LOG("pid = %s rid = %s already garbage\n" \
% (p.pid, p.rid))
return
if dbg>=2:
ioman.LOG("pid = %s rid = %s garbage\n" \
% (p.pid, p.rid))
# delete p from its group
del task.processes[p.pid]
# 2010 5/5 fixed memory leak bugs
del task.proc_by_rid[rid]
# let the client know the process is dead
m = gxpm.up(self.gupid, task.tid,
gxpm.event_die("proc", rid,
pid, p.term_status, p.rusage,
p.time_start, p.time_end))
task.forward_up(m, gxpm.unparse(m))
# 2007 12/2 tau
# fixed a descriptor-leak bug that does not close
# stdin of the process
p.discard()
# delete the task it belongs to, if necessary
self.check_task_status(task)
# NEW handle cases where a child gxp died, and
# some tasks use it
if isinstance(p, gxp_peer_base):
for t in self.tasks.values():
if t.child_peers.has_key(p):
if fix_2007_12_25:
err_msg = ("%s : gxp process %s is dead\n" %
(self.gupid, p.peer_name))
m = gxpm.up(self.gupid, task.tid,
gxpm.event_info(None, err_msg))
t.forward_up(m, gxpm.unparse(m))
if dbg>=1: ioman.LOG(err_msg)
del t.child_peers[p]
self.check_task_status(t)
def check_proc_status(self, p):
"""
Check if the process is garbage. It is garbage if
the gxp has recognized its termination and all the
pipes from it to the gxp has been closed.
If so, first send an event upwards notifying of processs
termination. Delete the process from the task it belongs to.
It may in turn mark the task as dead, which may trigger
propagation of fin events upward.
"""
# delete p if p becomes garbage
if p.is_garbage():
self.cleanup_process(p)
else:
if dbg>=2:
ioman.LOG("pid = %s rid = %s still alive\n" \
% (p.pid, p.rid))
# ------------- handling syn msgs -------------
def handle_syn(self, ch, m):
"""
syn msg is used to detect the termination of a task.
To detect global terminatin of a task, we assign weights
on task nodes. A task node that has received n msgs
from above has weight n + 1. A parent node also
remembers the number of times it has sent msgs to
each child, plus one.
When a task node is deleted, it generates a syn msg
that carries its weight. When it gets a syn msg signaling
the deletion of a child node, it subtracts the weight
carried on the syn msg from what it remembers as the
weight of the child. If the weight becomes zero, the
parent deletes the task from its table.
This mechanism is necessary to avoid race conditions
between downward msgs creating child processes under
a task and upward msgs generated when a process is gone.
"""
task = self.tasks[m.tid]
task.child_peers[ch.proc] = task.child_peers[ch.proc] - m.event.weight
assert task.child_peers[ch.proc] >= 0, \
(task.child_peers[ch.proc], m.event.weight)
if task.child_peers[ch.proc] == 0:
del task.child_peers[ch.proc]
self.check_task_status(task)
# ------------- handling down msgs -------------
def search_peer(self, peer_name):
"""
return a neighboring gxp process matching peer_name.
if not found return None.
"""
for p in self.processes.values():
if isinstance(p, gxp_peer_base) and \
p.state == gxp_peer_base.STATE_LIVE and \
re.match(peer_name, p.peer_name):
return p
return None
def all_peers_except(self, procs):
"""
return a list of all neighboring gxp processes except
for those in procs.
"""
P = []
for p in self.processes.values():
if isinstance(p, gxp_peer_base) and \
p.state == gxp_peer_base.STATE_LIVE and \
not procs.has_key(p):
P.append(p)
return P
def register_task(self, tid, parent, target, persist, keep_connection):
"""
Register a task named tid, with the specified parent.
If a task of the given name (tid) does not exist, create one
(common case). Otherwise it simply adds parent as
(another) parent of it.
target is the tree of target (gxpm.target_tree).
persist is 1 if this task should never die.
keep_connection is
gxpm.keep_connection_never if the connection to the parent
should be immediately closed.
gxpm.keep_connection_until_fin if the connection to the
parent should closed when all procs are finished.
gxpm.keep_connection_never if the connection to the parent
should never be closed.
"""
if self.tasks.has_key(tid):
if dbg>=2:
ioman.LOG("tid %s exists\n" % tid)
task = self.tasks[tid]
task.weight = task.weight + 1 # ???
# if this is an additional process to an existing task,
# notify other gxps of them
else:
if dbg>=2:
ioman.LOG("tid %s created\n" % tid)
task = task_tree_node(tid)
self.tasks[tid] = task
# update persistent flag of the task
if persist: task.persist = persist
# add the sender as a new parent
if task.parent_peers.has_key(parent):
task.parent_peers[parent] = max(task.parent_peers[parent],
keep_connection)
else:
task.parent_peers[parent] = keep_connection
if task.parent_peers[parent] == gxpm.keep_connection_never:
task.close_connection_to_parent(parent)
return task
def forward_down(self, task, parent, m, msg):
"""
forward msg m down, along the tree specified with
target tree in m.
the m should look like:
<down>
<target> ... </target>
<tid> ... </tid>
...
</down>
"""
# get destination
# <target><tree ...>...</tree></target>
root = m.target
# <tree ...>...</tree>
# root = target.children[0]
if root.children is None:
# m says this should be forwarded to all children.
# m_ = m.copy()
# delete "close" attribute, even originally present,
# to prevent the child from disconnecting the connection
# to this gxp upon termination.
# m_.del_subtree("close")
# msg_ = m_.to_str()
if m.keep_connection < gxpm.keep_connection_forever:
# non-roots should always keep connection to the parent
m_keep_connection = m.keep_connection
m.keep_connection = gxpm.keep_connection_forever
msg_ = gxpm.unparse(m)
m.keep_connection = m_keep_connection
else:
msg_ = msg
# forward the msg down (to everybody except for
# the parent)
peers = self.all_peers_except({ parent : 1 })
for peer in peers:
# increment its weight by one, reflecting the
# fact it has sent a msg to it.
# FIX??: if this msg has been lost due to the crash
# of the gxpd hosting the child node, then we can
# never delete of the child?
# Or it has been fixed??? (see check_proc_status)
if not task.child_peers.has_key(peer):
task.child_peers[peer] = 0
task.child_peers[peer] = task.child_peers[peer] + 1
peer.write_msg(msg_)
else:
# m says this should be forwarded to some specified
# children
for t in root.children:
child_name = t.name
# look for the peer of the specified name
peer = self.search_peer(child_name)
if peer is None:
record = ("no children of name %s. perhaps it's dead\n"
% child_name)
if dbg>=1: ioman.LOG(record)
err_msg = "%s : %s" % (self.gupid, record)
em = gxpm.up(self.gupid, task.tid,
gxpm.event_info(None, err_msg))
task.forward_up(em, gxpm.unparse(em))
elif peer is parent:
# never send a msg to the parent (why not?)
continue
else:
# m_ = m.copy()
# delete "close" attribute to prevent the child
# from disconecting the channel to me
# m_.del_subtree("close")
# set the target of m to the subtree rooted at
# the destination peer. i.e. if the original
# taget is a -- b -- c
# +-d -- e
# and we are about to forward m to b, the target
# of the msg is now b -- c
# m_.set_subtree("target", new_tgt)
# m_close,m_target = m.close,m.target
m_keep_connection,m_target = m.keep_connection,m.target
m.keep_connection,m.target = gxpm.keep_connection_forever,t
msg_ = gxpm.unparse(m)
m.keep_connection,m.target = m_keep_connection,m_target
if not task.child_peers.has_key(peer):
task.child_peers[peer] = 0
# increment weight by one (see above)
task.child_peers[peer] = task.child_peers[peer] + 1
peer.write_msg(msg_)
# ------------- handlers for individual actions -------------
#
# action quit
#
def do_action_quit(self, task, parent, down_m, tgt, action):
"""<action name=quit></action>"""
self.quit = 1