-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgxpc.py
executable file
·5574 lines (5033 loc) · 195 KB
/
gxpc.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) 2009 by Kenjiro Taura. All rights reserved.
# Copyright (c) 2008 by Kenjiro Taura. All rights reserved.
# Copyright (c) 2007 by Kenjiro Taura. All rights reserved.
# Copyright (c) 2006 by Kenjiro Taura. All rights reserved.
# Copyright (c) 2005 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/gxpc.py,v 1.76 2012/07/04 15:32:53 ttaauu Exp $
# $Name: $
#
def prompt_():
s = os.environ.get("GXP_SESSION", "")
if s == "":
D = "/tmp/gxp-%s-%s" % (os.environ.get("USER", "unknown"),
os.environ.get("GXP_TMP_SUFFIX", "default"))
for d in os.listdir(D):
# "gxp-xxxxxxxx-session-..."
if d[0:4] == "gxp-" and d[12:21] == "-session-":
if s == "":
s = os.path.join(D, d)
else:
os.write(1, "[?/?/?]\n")
return 1
fp = open(s)
os.write(1, fp.readline())
return 0
def prompt():
try:
return prompt_()
except:
return 1
import os,sys
if len(sys.argv) == 2 and sys.argv[1] == "prompt":
os._exit(prompt())
def import_safe_pickler():
import cPickle,pickle
try:
cPickle.dumps(None)
return cPickle
except:
return pickle
pickler = import_safe_pickler()
import cStringIO,errno,fcntl,glob,random,re
import select,signal,socket,stat # shlex
import string,time,threading,types,copy
import opt,gxpm,this_file
# ,gxpd
#
# gxp frontend (command interpreter) that talks to daemons
#
def Ws(s):
sys.stdout.write(s)
def Es(s):
sys.stderr.write(s)
def Ef():
sys.stderr.flush()
class counter:
def __init__(self, init):
self.x = init
def decrement(self):
x = self.x
self.x = x - 1
return x
def add(self, y):
self.x += y
class peer_tree_node:
def __init__(self):
self.name = None # peer_name. initially None
self.hostname = None
self.children = {} # nid -> peer_tree_node
self.cmd = None # cmd issued to get this peer
self.target_label = None # target label
self.eenv = gxpm.exec_env()
def show_rec(self, indent):
spaces = " " * indent
Ws(("%s%s (= %s %s)\n"
% (spaces, self.name, self.hostname, self.target_label)))
for c in self.children.values():
c.show_rec(indent + 1)
def show(self):
self.show_rec(0)
class login_method_configs:
def __init__(self):
# syntax of the following.
# if the first character is non alphabetical, use
# it as the separator (see ssh below, which uses :)
# otherwise it uses whitespaces as the separator
self.ssh = ("ssh -o StrictHostKeyChecking=no "
"-o PreferredAuthentications=hostbased,publickey "
"-A %target% %cmd%")
self.ssh_as = ("ssh -o StrictHostKeyChecking=no "
"-o PreferredAuthentications=hostbased,publickey "
"-A -l %user% %target% %cmd%")
self.rsh = "rsh %target% %cmd%"
self.rsh_as = "rsh -l %user% %target% %cmd%"
self.sh = "sh -c %cmd%"
self.qrsh = "qrsh %cmd%"
self.qrsh_host = "qrsh -l hostname=%target% %cmd%"
self.sge = "qsub_wrap --sys sge %cmd%"
self.sge_host = "qsub_wrap --sys sge %cmd% -- -l hostname=%target%"
self.torque = "qsub_wrap --sys torque %cmd%"
self.torque_n = ("qsub_wrap --sys torque %cmd% "
"-- -l nodes=%nodes:-1%:ppn=%ppn:-1%")
self.torque_host = ("qsub_wrap --sys torque %cmd% "
"-- -l nodes=1:%target%:ppn=%ppn:-1%")
self.torque_psched = ("qsub_wrap --sys torque_psched %cmd% "
"-- --node %target% --lib %lib:-libtorque.so%")
self.condor = "qsub_wrap --sys condor %cmd%"
self.nqs_hitachi = "qsub_wrap --sys nqs_hitachi %cmd%"
self.nqs_fujitsu = "qsub_wrap --sys nqs_fujitsu %cmd%"
# aliases
self.hitachi = "qsub_wrap --sys nqs_hitachi %cmd%"
self.fujitsu = "qsub_wrap --sys nqs_fujitsu %cmd%"
self.n1ge = "qsub_wrap --sys n1ge %cmd%"
self.n1ge_host = "qsub_wrap --sys n1ge %cmd% -l host=%target%"
self.tsubame = ("qsub_wrap --sys n1ge "
"--timeout %timeout:-100% %cmd% "
"--qsub n1ge --qstat qstat --qdel qdelete %cmd% "
"-- -q %q% -g %g% -mem %mem:-4.0% -rt %cpu:-30%")
self.ha8000 = ("qsub_wrap --sys nqs_hitachi "
"--timeout %timeout:-100% --addr 10 %cmd% "
"-- -q %q% -N %nodes:-1% -J T%ppn:-1% "
"-lT %cpu:-5%:00 -lm %mem:-28%gb")
self.hx600 = ("qsub_wrap --sys nqs_fujitsu "
"--timeout %timeout:-100% %cmd% "
"-- -q %q% -g %g% -lP %nodes:-1% -lp %ppn:-1% "
"-cp %cpu:-5%:00 -lm %mem:-28%gb "
"-nr -Pvn UNPack")
self.tsubame2 = ("qsub_wrap --sys torque "
"--timeout %timeout:-100% "
"--qsub t2sub --qstat t2stat --qdel t2del %cmd% "
"-- -q %q% -W group_list=%group_list% -l walltime=%walltime:-1:00:00% "
"-l select=%nodes:-1%:ncpus=%ncpus:-12%:mem=%mem:-52%gb "
"-l place=%place:-scatter%")
self.fx10 = "qsub_wrap --sys pjsub %cmd%"
self.ofp = ("qsub_wrap --sys pjsub "
"--timeout %timeout:-100% "
"--script_dir %lustre_dir% "
"%cmd% "
"-- "
"-L rscgrp=%rscgrp:-regular-cache% "
"-L elapse=%elapse:-1:00:00% "
"-L node=1 "
"-g %group% ")
# reedbush-u system on utokyo
self.reedbush = ("qsub_wrap --sys torque "
"--timeout %timeout:-100% "
"--qstat rbstat "
"--script_dir %lustre_dir% "
"%cmd% "
"-- -q %q% "
"-l select=%nodes:-1%:ncpus=%ncpus:-36%:mpiprocs=%mpiprocs:-1%:ompthreads=%ompthreads:-1% "
"-W group_list=%group_list% "
"-l walltime=%walltime:-1:00:00% ")
# kyoto university MPP (system A)
# the script needs to invoke python by aprun python ...
# the address to connect back to is 10.7.x.x, among
# other addrs like 10.5.x.x, 10.6.x.x, etc.
# usage example: request 3 nodes from host xe-????
# gxpc use kyoto_mpp xe foo
# gxpc explore -a q=queue_name -a ug=user_group_name foo 3
self.kyoto_mpp = [ "qsub_wrap",
"--python", "aprun python",
"--addr", "10.7",
"--sys", "lsf", "%cmd%",
"--",
"-q", "%q%", "-ug", "%ug%",
"-A", "p=%p:-1%:t=%t:-16%:c=%c:-16%:m=%m:-61440M%",
"-W", "%W:-24:00%" ]
# kyoto university cluster (system B)
# the address to connect back to is 10.5.x.x, among
# other addrs like 10.4.x.x, 10.6.x.x, etc.
# usage example: request 3 nodes from host ap-???
# gxpc use kyoto_cluster ap foo
# gxpc explore -a q=queue_name -a ug=user_group_name foo 3
self.kyoto_cluster = ("qsub_wrap --addr 10.5 "
"--sys lsf %cmd% "
"-- -q %q% -ug %ug% "
"-A p=%p:-1%:t=%t:-16%:c=%c:-16%:m=%m:-61440M% "
"-W %W:-24:00%")
class mask_patterns:
def __init__(self, hostmask, gupidmask, targetmask, idxmask):
self.hostmask = hostmask
self.gupidmask = gupidmask
self.targetmask = targetmask
self.idxmask = idxmask
class session_state:
"""
State of a gxp session.
A session lasts longer than a single command.
Regular command execution:
1. specified exec tree is chosen and used to send msgs
2. last_exec_tree is set to the chosen exec tree.
last_term_status is cleared (empty dictionary)
3. termination statuses are written into last_term_status
4. when execution is done, last_exec_tree and last_term_status
are examined and nodes that are marked successful are counted.
5. update last_ok_count by this.
smask/pushmask:
1. make a new exec tree based on last_exec_tree and
last_term_status.
2. install the new tree as stack_exec_trees[0]
smask will overwrite the old stack_exec_trees[0],
whereas pushmask will not (push).
rmask/explore:
1. stack_exec_trees[0] will become the whole peer_tree
2. update peer_tree_count
3. last_ok_count = peer_tree_count
popmask:
1. delete stack_exec_trees[0]
2.
"""
def __init__(self, filename):
self.filename = filename
self.peer_tree = None # tree of all live peers
self.stack_exec_trees = [ None ] # exec tree,exec count
self.saved_exec_trees = {} #
# exec tree used for the last submission
self.last_exec_tree = None
self.last_term_status = None
# of nodes in peer_tree
self.peer_tree_count = None
# of nodes with eflag=1 in stack_exec_trees[0]
self.cur_exec_count = None
# of nodes with term_status=1 in last_exec_tree
self.last_ok_count = None
# gupid -> peer_tree_node
self.reached = None
# dict of successfully reached targets
self.successful_targets = {}
# whatever is specified via edges commands
self.edges = []
# some explore parameters
#
# self.max_children_soft = 10
# self.max_children_hard = 100
self.default_explore_opts = None
# specified targets
# self.target_hosts = []
# creatd flag is 1 if this was just created.
# 0 if unpickled from disk (cleard upon save)
self.created = 1
# dirty is 0 if it is 100% sure that disk has the same image
# OK to always pretend it is 1.
self.dirty = 1
# set to 1 when other tasks change the state of the tree
self.invalid = 0
self.init_random_generator()
# e.g., [("ssh", ....), ("qrsh", ....)]
self.login_methods = {}
# default login methods
lm = login_method_configs()
for name,cmdline in lm.__dict__.items():
if type(cmdline) is types.ListType:
cmd = cmdline
else:
c = cmdline[0]
if c not in string.letters:
cmd = string.split(cmdline[1:], c)
else:
cmd = string.split(cmdline)
self.login_methods[name] = cmd
def show(self, level):
Ws("%s\n" % self.filename)
if level >= 1:
self.peer_tree.show()
if level >= 2:
Ws("stack_exec_trees:\n")
for ex,t in self.stack_exec_trees:
Ws(" %s: %s\n" % (ex, t.show()))
Ws("saved_exec_trees: %s\n" % self.saved_exec_trees)
Ws("last_exec_tree: %s\n" % self.last_exec_tree.show())
Ws("last_term_status: %s\n" % self.last_term_status)
Ws("peer_tree_count: %s\n" % self.peer_tree_count)
Ws("cur_exec_count: %s\n" % self.cur_exec_count)
Ws("last_ok_count: %s\n" % self.last_ok_count)
Ws("reached: %s\n" % self.reached)
Ws("successful_targets: %s\n" % self.successful_targets)
Ws("edges: %s\n" % self.edges)
Ws("default_explore_opts: %s\n" % self.default_explore_opts)
Ws("created: %s\n" % self.created)
Ws("dirty: %s\n" % self.dirty)
Ws("invalid: %s\n" % self.invalid)
Ws("login_methods: %s\n" % self.login_methods)
def init_random_generator(self):
self.rg = random.Random()
self.rg.seed(time.time() * os.getpid())
def randint(self, a, b):
return self.rg.randint(a, b)
def gen_random_id(self):
return self.randint(0, 10**8 - 1)
def mk_pat_from_mask(self, name, negname, mask, negmask):
if mask is not None:
try:
pat = re.compile(mask)
except Exception,e:
Es("gxpc: invalid %s '%s' %s\n" % (name, mask, e.args))
return None
elif negmask is not None:
try:
neg_pat = re.compile(negmask)
except Exception,e:
Es("gxpc: invalid %s '%s' %s\n" % (negname, e.args))
return None
pat = re.compile("(?!(%s))" % negmask)
else:
pat = re.compile(".")
return pat
def select_exec_tree(self, opts):
"""
mask : name, number, or None (all)
based on parameters given in the command line, select
and/or make the target tree
mask : given by -m (--withmask) 0
hostmask : given by -h (--withhostmask) .*
hostnegmask : given by -H (--withhostnegmask) .*
gupidmask : given by -g (--withgupidmask) .*
gupidnegmask : given by -G (--withgupidnegmask) .*
targetmask : given by -g (--withtargetmask) .*
targetnegmask : given by -G (--withtargetnegmask) .*
return ex,t
where ex is exec_count and t is tree
"""
# first choose the appropriate tree by mask
# most of the time it is in stack_exec_trees[0]
mask = opts.withmask
if self.peer_tree is None:
# special case
t = gxpm.target_tree(".*", ".*", ".*", 1, 0, gxpm.exec_env(), None)
ex = ""
elif mask is None:
ex,t = self.mk_whole_exec_tree(self.peer_tree)
elif type(mask) is types.StringType:
if self.saved_exec_trees.has_key(mask):
ex,t = self.saved_exec_trees[mask]
else:
Es("gxpc: no exec tree entry named %s\n" % mask)
return (None,None) # NG
elif type(mask) is types.IntType:
if 0 <= mask < len(self.stack_exec_trees):
ex,t = self.stack_exec_trees[mask]
else:
Es("gxpc: invalid mask value %d\n" % mask)
return (None,None) # NG
# then filter hosts by -h, -H, -g, -G, -i, -I
hostmask = self.mk_pat_from_mask("hostmask", "hostnegmask",
opts.withhostmask, opts.withhostnegmask)
if hostmask is None: return (None,None)
gupidmask = self.mk_pat_from_mask("gupidmask", "gupidnegmask",
opts.withgupidmask, opts.withgupidnegmask)
if gupidmask is None: return (None,None)
targetmask = self.mk_pat_from_mask("targetmask", "targetnegmask",
opts.withtargetmask, opts.withtargetnegmask)
if targetmask is None: return (None,None)
idxmask = self.mk_pat_from_mask("idxmask", "idxnegmask",
opts.withidxmask, opts.withidxnegmask)
if idxmask is None: return (None,None)
pats = mask_patterns(hostmask, gupidmask, targetmask, idxmask)
# 2. really filter nodes
ex_,t_ = self.mk_selected_exec_tree_rec2(t, pats)
if t_ is not None:
# set exec idx of nodes
ex__,_ = self.set_exec_idx_rec(t_, 0, 0, ex_)
assert (ex__ == ex_), (ex__, ex_)
self.last_exec_tree = t_
self.last_term_status = {}
return (ex_,t_)
def mk_selected_exec_tree_rec2(self, tgt, pats):
"""
like mk_selected_exec_tree_rec, but select nodes whose names match pat
"""
if tgt is None or tgt.name is None:
return (0, None)
elif tgt.children is None:
# tgt.children means allchildren, treated specially
# return (1, tgt)
# ex = "" means exec_count is unknown
return ("", tgt)
else:
T = []
C = 0
for child in tgt.children:
c,t = self.mk_selected_exec_tree_rec2(child, pats)
if t is not None:
T.append(t)
C = C + c
if tgt.eflag and pats.hostmask.match(tgt.hostname) \
and pats.gupidmask.match(tgt.name) \
and pats.targetmask.match(tgt.target_label) \
and pats.idxmask.match("%d" % tgt.exec_idx):
ef = 1
C = C + 1
else:
ef = 0
if C > 0:
return (C, gxpm.target_tree(tgt.name, tgt.hostname, tgt.target_label,
ef, None, tgt.eenv, T))
else:
return (0, None)
def mk_selected_exec_tree_rec(self, tgt, sign, status):
"""
tgt : instance of gxpm.target_tree.
sign : 1 or 0
status : dictionary gupid -> exit status (int)
return a pair (0, None) or (c, tree), where tree
is an instance of gxpm.target_tree. c is the number of nodes
in tree whose status (i.e., status[n.tgt_name]) match sign.
(if sign is 1, count nodes whose statuses are zero.
if sign is 0, count nodes whose statuses are non-zero).
tree is the one made by removing some nodes of tgt from
leaves. it removes node N if and only if N contains no nodes
under it whose status (obtained by status dictionary) do not
match sign.
"""
if tgt is None or tgt.name is None:
return (0, None)
elif tgt.children is None:
# tgt.children means allchildren, treated specially
return ("", tgt)
else:
T = []
C = 0
for child in tgt.children:
c,t = self.mk_selected_exec_tree_rec(child, sign,
status)
if t is not None:
T.append(t)
C = C + c
if tgt.eflag and \
((sign and status.get(tgt.name, 1) == 0) or \
(sign == 0 and status.get(tgt.name, 1) != 0)):
ef = 1
C = C + 1
else:
ef = 0
if C > 0:
return (C, gxpm.target_tree(tgt.name, tgt.hostname, tgt.target_label,
ef, None, tgt.eenv, T))
else:
return (0, None)
def mk_whole_exec_tree(self, ptree):
ex,tree = self.mk_whole_exec_tree_rec(ptree)
if tree is not None:
ex_,all = self.set_exec_idx_rec(tree, 0, 0, ex)
assert (ex_ == ex), (ex_, ex)
return ex,tree
def mk_whole_exec_tree_rec(self, ptree):
"""
ptree : instance of peer_tree
"""
if ptree is None or ptree.name is None:
return (0, None)
else:
T = []
C = 0
for child in ptree.children.values():
c,t = self.mk_whole_exec_tree_rec(child)
if t is not None:
T.append(t)
C = C + c
return (C + 1,
gxpm.target_tree(ptree.name, ptree.hostname, ptree.target_label,
1, None, ptree.eenv, T))
def set_exec_idx_rec(self, tgt, exec_idx, all_idx, num_execs):
"""
traverse target tree tgt and set exec_idx and num_execs of nodes.
return exec_idx,all_idx
where exec_idx is the number of nodes whose eflag is set
all_idx is the number of nodes
"""
assert (num_execs == "" or type(num_execs) is types.IntType), num_execs
all_idx = all_idx + 1
if tgt.eflag:
tgt.num_execs = num_execs
tgt.exec_idx = exec_idx
exec_idx = exec_idx + 1
# tgt.children means allchildren, treated specially
if tgt.children is None:
return "","" # unknown,unknown
else:
for child in tgt.children:
R = self.set_exec_idx_rec(child, exec_idx,
all_idx, num_execs)
exec_idx,all_idx = R
return exec_idx,all_idx
def set_selected_exec_tree(self, sign, push, name):
"""
smask/pushmask:
1. make a new exec tree based on last_exec_tree and
last_term_status.
2. install the new tree as stack_exec_trees[0]
smask will overwrite the old stack_exec_trees[0],
whereas pushmask will not (push).
"""
tgt = self.last_exec_tree
status = self.last_term_status
ex,tree = self.mk_selected_exec_tree_rec(tgt, sign, status)
if tree is not None:
ex_,_ = self.set_exec_idx_rec(tree, 0, 0, ex)
assert (ex_ == ex), (ex_, ex)
if push:
self.stack_exec_trees.insert(0, (ex, tree))
else:
self.stack_exec_trees[0] = (ex, tree)
if name is not None:
self.saved_exec_trees[name] = (ex, tree)
# update cache of cur_exec_count
self.cur_exec_count = ex
def reset_exec_tree(self):
"""
stack_exec_trees[0] will become the whole peer_tree
"""
ex,tree = self.mk_whole_exec_tree(self.peer_tree)
# 2008.7.9 is this what I should do?
self.last_exec_tree = tree
self.stack_exec_trees[0] = (ex,tree)
self.last_ok_count = ex
self.cur_exec_count = ex
self.peer_tree_count = ex
def mk_peer_tree(self, events):
"""
analyze the events received as a result of a ping command
and create the tree of live nodes
"""
# gupid -> peer_tree_node
reached = {}
# target_label -> count
successful_targets = {}
# first create an empty node for each live node
pongs = []
for gupid,tid,ev in events:
if isinstance(ev, gxpm.event_info_pong):
pongs.append((gupid, ev))
for gupid,pong in pongs:
reached[gupid] = peer_tree_node()
# fill their names and children. also find root
roots = []
for gupid,pong in pongs:
assert isinstance(pong, gxpm.event_info_pong), pong
# record attributes of the peer_tree_node for gupid
target_label = pong.targetlabel
t = reached[gupid]
t.name = gupid
t.hostname = pong.hostname
t.target_label = target_label
# record how many nodes we got for target_label
s = successful_targets.get(target_label, 0)
successful_targets[target_label] = s + 1
# record children of gupid
C = []
for cname in pong.children:
# add child
if reached.has_key(cname):
id = self.gen_random_id()
t.children[id] = reached[cname]
# no parent -> it is a root
if pong.parent == "": roots.append(t)
# obviously the root must be unique
if len(roots) != 1:
Es("gxpc: broken gxp daemon tree (deamons seem broken, roots=%s)\n" % roots)
return None,None,None
# check if parent and children are consistent
for gupid,pong in pongs:
# get gupid's parent
if pong.parent == "": continue
# check if gupid is a child of the parent
p = reached[pong.parent]
found = 0
for c in p.children.values():
if c.name == gupid:
found = 1
break
assert found == 1
return roots[0],reached,successful_targets
def construct_peer_tree(self, events):
R = self.mk_peer_tree(events)
peer_tree,reached,successful_targets = R
if peer_tree is None: return -1
self.peer_tree = peer_tree
self.reached = reached
self.successful_targets = successful_targets
self.reset_exec_tree()
return 0
def list_gupids_rec(self, tgt, gupids):
if tgt is None: return gupids
assert not gupids.has_key(tgt.name)
gupids[tgt.name] = 1
if tgt.children is not None:
for child in tgt.children:
self.list_gupids_rec(child, gupids)
return gupids
def trim_peer_tree_rec(self, peer_tree, reached,
successful_targets, target_gupids):
if not target_gupids.has_key(peer_tree.name):
return None
reached[peer_tree.name] = peer_tree
s = successful_targets.get(peer_tree.target_label, 0)
successful_targets[peer_tree.target_label] = s + 1
for id,child in peer_tree.children.items():
if self.trim_peer_tree_rec(child, reached,
successful_targets,
target_gupids) is None:
del peer_tree.children[id]
return peer_tree
def trim_peer_tree(self, tgt):
target_gupids = self.list_gupids_rec(tgt, {})
# trim all nodes that do not appear in targets
reached = {}
successful_targets = {}
peer_tree = self.trim_peer_tree_rec(self.peer_tree,
reached,
successful_targets,
target_gupids)
self.peer_tree = peer_tree
self.reached = reached
self.successful_targets = successful_targets
self.reset_exec_tree()
def restore_exec_tree(self, name):
if self.saved_exec_trees.has_key(name):
ex,tree = self.saved_exec_trees[name]
self.stack_exec_trees[0] = (ex,tree)
self.cur_exec_count = ex
return 0
else:
return -1
def pop_exec_tree(self):
if len(self.stack_exec_trees) > 1:
self.stack_exec_trees.pop(0)
ex,tree = self.stack_exec_trees[0]
self.cur_exec_count = ex
return 0 # OK
else:
return -1 # NG
def update_last_ok_count(self):
status = 0
ok = 0
for s in self.last_term_status.values():
if s == 0: ok = ok + 1
status = max(status, s)
self.last_ok_count = ok
return status
def clear_dirty(self):
self.dirty = 0
def set_dirty(self):
self.dirty = 1
def save(self, verbosity):
"""
save session state in a file
"""
if verbosity >= 2:
Es(("gxpc: save session created=%d dirty=%d invalid=%d %s\n"
% (self.created, self.dirty, self.invalid, self.filename)))
if self.created or self.dirty:
self.created = 0
self.invalid = 0
self.clear_dirty()
directory,base = os.path.split(self.filename)
# why _?
# otherwise it may be found by other processes as
# session file and deleted as a garbage
rand_base = "_%s-%d-%d" % (base, os.getpid(),
self.gen_random_id())
rand_file = os.path.join(directory, rand_base)
fd = os.open(rand_file,
os.O_CREAT|os.O_WRONLY|os.O_TRUNC)
wp = os.fdopen(fd, "wb")
# wp = open(self.filename, "wb")
wp.write("[%s/%s/%s]\n" % \
(self.last_ok_count,
self.cur_exec_count,
self.peer_tree_count))
pickler.dump(self, wp)
wp.close()
os.chmod(rand_file, 0600)
os.rename(rand_file, self.filename)
if self.peer_tree is None:
Es("gxpc: suggest gxpc ping\n")
else:
if verbosity >= 2:
Es("gxpc: clean session not saved\n")
class e_cmd_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)
self.pty = (None, 0)
self.up = ("s*", [])
self.down = ("s*", [])
self.updown = ("s*", [])
self.master = ("s", None)
# ------ global options that can also be given as e options.
# default values are in interpreter_opts
self.withall = (None, 0)
self.withmask = ("s", None)
self.withhostmask = ("s", None)
self.withhostnegmask = ("s", None)
self.withgupidmask = ("s", None)
self.withgupidnegmask = ("s", None)
self.withtargetmask = ("s", None)
self.withtargetnegmask = ("s", None)
self.withidxmask = ("s", None)
self.withidxnegmask = ("s", None)
self.timeout = ("f", None)
self.notify_proc_exit = ("i", None)
self.log_io = ("i", None)
self.persist = ("i", None)
self.keep_connection = ("i", None)
self.tid = ("s", None)
self.rid = ("s", None)
# self.dir = ("s", None)
self.dir = ("s*", [])
# given as list of var=val, and converted
# to dictionary in postcheck
self.export = ("s*", [])
self.rlimit = ("s*", [])
# ------
# self.join = (None, 0)
# short options
self.a = "withall"
self.m = "withmask"
self.h = "withhostmask"
self.H = "withhostnegmask"
self.g = "withgupidmask"
self.G = "withgupidnegmask"
self.t = "withtargetmask"
self.T = "withtargetnegmask"
self.i = "withidxmask"
self.I = "withidxnegmask"
def postcheck_up_or_down(self, arg, F, opt):
fields = string.split(arg, ":", 1)
if len(fields) == 1:
# [ fd ] --> [ fd, fd ]
fields.append(fields[0])
[ fd0,fd1 ] = map(lambda x: self.safe_atoi(x, None), fields)
if fd0 is None or fd1 is None:
Es(("invalid argument for --%s (%s)."
" It must be int or int:int (e.g., 3, 3:4)\n"
% (opt, arg)))
return None
if F.get(fd0) is None:
F[fd0] = ("--up %s" % arg)
else:
Es("gxpc: %s and --up %s is incompatible\n" \
% (F[fd0], arg))
return None
return (fd0, fd1)
def postcheck_updown(self, arg, F):
fields = string.split(arg, ":", 2)
if len(fields) == 1:
Es(("invalid argument for --updown (%s)."
" It must be int:int or int:int:cmd "
"(e.g., 3:4, or '3:4:grep hoge')\n" % arg))
return None
elif len(fields) == 2:
fds = fields
cmd = None
else:
fds = fields[:2]
[ cmd ] = fields[2:]
[ fd0,fd1 ] = map(lambda x: self.safe_atoi(x, None), fds)
if fd0 is None or fd1 is None:
Es(("invalid argument for --updown (%s)."
" It must be int:int or int:int:cmd "
"(e.g., 3:4, '3:4:grep hoge')\n"
% arg))
return None
if fd0 == fd1:
Es("gxpc: --updown %s is invalid\n" % arg)
return None
for fd in [ fd0, fd1 ]:
if F.get(fd) is None:
F[fd] = ("--updown %s" % arg)
else:
Es("gxpc: %s and --updown %s is incompatible\n" \
% (F[fd], arg))
return None
return (fd0, fd1, cmd)
def parse_export(self, export):
"""
export : list of "var=val"
"""
env = {}
for varval in export:
var_val = string.split(varval, "=", 1)
if len(var_val) == 1:
Es(("gxpc: invalid arg to --export (%s). "
"It should be var=val\n" % varval))
return None
[ var, val ] = var_val
env[var] = val
return env
def postcheck(self):
# check if updown is a list of int:int
up = []
down = []
updown = []
if self.pty:
F = { 0 : "--pty", 1 : "--pty", 2 : "--pty" }
else:
F = { 0 : None, 1 : None, 2 : None }
# parse --up
for arg in self.up:
x = self.postcheck_up_or_down(arg, F, "up")
if x is None: return -1
up.append(x)
# parse --down
for arg in self.down:
x = self.postcheck_up_or_down(arg, F, "down")
if x is None: return -1
down.append(x)
# parse --updown
for arg in self.updown:
x = self.postcheck_updown(arg, F)
if x is None: return -1
updown.append(x)
if F[0] is None: down.insert(0, (0, 0))
if F[2] is None: up.insert(0, (2, 2))
if F[1] is None: up.insert(0, (1, 1))
self.up = up
self.down = down
self.updown = updown
# if --withmask is given, use it
if self.withmask is not None:
self.withmask = self.safe_atoi(self.withmask,
self.withmask)
if self.withall:
self.withmask = None
self.export = self.parse_export(self.export)
if self.export is None: return -1
return 0
class hosts_parser_base:
def __init__(self):
self.filename = ""
self.cmd = ""
self.line_count = 0
def safe_atoi(self, x, defa):
try:
return string.atoi(x)
except ValueError,e:
return defa
def parse_error(self):
Es("%s:%d: parse error in line `%s'\n" % \
(self.filename, self.line_count, self.line))
return -1
def parse_fp(self, fp, filename, cmd, flag):
hosts = self.hosts.copy()
self.filename = filename
self.cmd = cmd
self.line_count = 0
eof = 0
while 1:
line = fp.readline()
if line == "":
eof = 1
break
self.line = line
self.line_count = self.line_count + 1
if line[0] == "#": continue
r = self.process_line(line, hosts, flag)
if r == 1: eof = 1
if r != 0: break
r = fp.close()
if eof == 0: return -1 # parse error (NG)
if r is not None and r != 0:
Es("command %s exited abnormally (output ignored)\n" \
% self.cmd)
return -1
self.hosts = hosts
return 0 # OK
def parse_file(self, filename, flag, signal_error):
fp = None
try:
fp = open(filename, "rb")
except IOError,e:
if signal_error:
Es("gxpc: %s: %s\n" % (filename, e.args))
if fp is not None:
self.parse_fp(fp, filename, None, flag)
def parse_pipe(self, cmd, flag):
fp = os.popen(cmd)
self.parse_fp(fp, None, cmd, flag)
def parse_args(self, args):
self.filename = "[cmdarg]"
self.line_count = 0
self.line = string.join(args, " ")
self.process_list(args, self.hosts, 1)
def parse(self, files, alias_files, cmds, args):
self.hosts = {}
for filename in files:
self.parse_file(filename, 1, 1)
for filename in alias_files:
self.parse_file(filename, 0, 0)
for cmd in cmds:
self.parse_pipe(cmd, 1)
self.parse_args(args)
return self.hosts
class etc_hosts_parser(hosts_parser_base):
"""
parse a file describing alias relationships