This repository has been archived by the owner on Sep 23, 2020. It is now read-only.
/
workspacepilot.py
4692 lines (3408 loc) · 145 KB
/
workspacepilot.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
#!/usr/bin/env python
# Copyright 1999-2008 University of Chicago
# Project home: http://www.nimbusproject.org
# A code folding editor is recommended, folds hand-marked with {{{ and }}}
# Alternatively, see INDEX below for section line numbers.
# ############################################################
# I. Globals
# #########################################################{{{
VERSION = "2.5"
# Apache License 2.0:
LICENSE = """
Copyright 1999-2008 University of Chicago
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
"""
# result of "generate-index.py < workspacepilot.py"
INDEX = """
I. Globals (lines 10-69)
II. Embedded, default configuration file (lines 71-188)
III. Imports (lines 190-216)
IV. Exceptions (lines 218-344)
V. Logging (lines 346-565)
VI. Signal handlers (lines 567-669)
VII. Timer (lines 671-696)
VIII. Path/system utilities (lines 698-1057)
IX. Action (lines 1059-1110)
X. ReserveSlot(Action) (lines 1112-1715)
XI. KillNine(ReserveSlot) (lines 1717-1795)
XII. ListenerThread(Thread) (lines 1797-1902)
XIII. StateChangeListener (lines 1904-2130)
XIV. XenActions(StateChangeListener) (lines 2132-2846)
XV. FakeXenActions(XenActions) (lines 2848-2962)
XVI. XenKillNine(XenActions) (lines 2964-3095)
XVII. VWSNotifications(StateChangeListener) (lines 3097-3712)
XVIII. Configuration objects (lines 3714-3944)
XIX. Convert configurations (lines 3946-4206)
XX. External configuration (lines 4208-4278)
XXI. Commandline arguments (lines 4280-4495)
XXII. Standalone entry and exit (lines 4497-4690)
"""
RESTART_XEND_SECONDS_DEFAULT = 2.0
# evaluate prefix, for log messages
EP = "evaluate:"
# Other sections also set up globals:
# default config (II), logging (V), signals (VI), timer (VII)
# }}} END: I. Globals
# ############################################################
# II. Embedded, default configuration file
# #########################################################{{{
DEFAULTCONFIG = """
# This is the default configuration file for the program.
# It can be changed inline or copied out into a file whose path can
# be passed into the program via command-line. If that is done, the
# program will NOT fall back to this default configuration if there
# is an error or misconfiguration with the supplied config file.
[http]
# Shared secret needs to match container configuration (users.properties)
# connection uses digest access authentication so this is not sent in the clear
secret: pw_here
# Account value should not need to be changed, it's not a system account name.
# However, if this is commented out, HTTP based notifications will be disabled
# even if the container is asking for them. (But it's best to just control
# notification behavior from the service configuration)
account: pilotaccount
[logging]
# if logfiledir is enabled it must be an absolute path. If it is missing
# there will be no file based logging.
# Note that in many circumstances the pilot job's stdout/stderr
# pipe will be cut off by the LRM, leaving file based logging as the only
# window for troubleshooting and audit.
logfiledir = /tmp/
# If logfileprefixis is "pilot-", example files: "pilot-$ID.txt" where ID is
# the slot ID (UUID) and "pilot-otherlogs.txt" when no slot ID is available.
# May be missing.
logfileprefix = workspace-pilot-
[xen]
# Guides whether you need sudo or not for xm commands. You may be using
# unix sockets with the xen-api for example (which is a good configuration
# if the permissions are correct on /var/run/xend/xen-api.sock ).
# Anything that is not 'yes' is taken as a no.
xmsudo: yes
# Should be an absolute path if using sudo, so that sudo rule contains an
# absolute path.
xm: /usr/sbin/xm
# Minimum MB to ever let dom0 memory be decreased to (safety check, required)
# xend-config.sxp file has a safety check as well
minmem: 256
# The dom0 MB to set after a kill-nine operation. This should match the
# node's boot parameter (e.g. grub line of dom0_mem=2007M). See documentation
# for how to arrive at this number.
dom0_mem: 2007
# This is optional. If configured and xend is down, this will be used
# to try and restart xend via 'xend restart'. If unconfigured, xend being
# down is just an unrecoverable error.
# Adds on the order of a ~100ms if all is well.
# NOTE: if you are using virtual interfaces (e.g. "eth0:0") in dom0, a
# xend restart will leave your machine without networking. In the
# future we may add the ability to automatically take those down
# and bring them back afterwards. For now consider aliasing xend
# to a wrapper script that does this for you.
# NOTE: requires extra sudo policy line. This should be an absolute path
# so that sudo rule contains absolute path.
#xend: /usr/sbin/xend
# Also optional, used if xend is configured. Seconds to wait for
# xend to boot after we found it missing and restarted it.
# If unconfigured, default is 2.0 seconds
#restart_xend_secs: 0.3
[systempaths]
# This is only necessary if using SSH as a backup notification mechanism
# (relative or absolute is fine). If this is commented out, SSH notifications
# will be disabled even if the container is asking for them. (But it's
# best to just control notification behavior from the service configuration)
ssh: ssh
# If you are using xm via sudo or using xend, this is needed. It should be an
# absolute path. See 'xmsudo' configuration.
sudo: /usr/bin/sudo
[other]
# This allows you to force what this program thinks the hostname is
# in case the gethostname system call returns the incorrect name for the
# purposes of notifications because of some DNS or multi-homing issue.
# Not set by default: uncomment and insert the proper hostname.
#forcehostname:
# When the program receives a signal to end before it expected to, it
# will sleep a short time, giving a chance for plugins to take action
# to make way for the slot to be freed.
# For example, the workspace service is notified of the situation and
# will run shutdown-trash to make way. This setting is the ratio of
# the grace period to wait until going ahead with unreserving the slot.
# After this wait the included Xen plugin will kill anything in its way
# to make sure the slot is relinquished.
# Required.
# Must be 0 or float between 0 and 1 (1 does not make any sense).
earlywaitratio = 0.5
# This allows you to force the path of the credential used for SSH
# in case the account's default credential is not the needed one.
# Not set by default: uncomment and insert the absolute path.
#sshcredential:
"""
# }}} END: II. Embedded, default configuration file
# ############################################################
# III. Imports
# #########################################################{{{
import ConfigParser
import grp
import logging
import optparse
import os
import pwd
import signal
import socket
import stat
import string
import sys
import time
import urllib2
try:
from threading import Thread
except ImportError:
from dummy_threading import Thread
# not using subprocess package to maintain at least python 2.3 compat.
from popen2 import Popen3
# }}} END: III. Imports
# ############################################################
# IV. Exceptions
# #########################################################{{{
class InvalidInput(Exception):
"""Exception for illegal commandline syntax/combinations."""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class InvalidConfig(Exception):
"""Exception for misconfigurations."""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class IncompatibleEnvironment(Exception):
"""Exception for when something has determined a problem with the
deployment environment."""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class UnexpectedError(Exception):
"""Exception for when a function/listener cannot proceed."""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class ProgrammingError(Exception):
"""Not listed in docstrings, should never be seen except during
development."""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class AKilledVM:
"""Container for reporting killed VMs via KilledVMs exception."""
def __init__(self, vmid, name, mem):
"""Populate the object with kill information.
Required parameter:
* vmid -- VMM's VM ID number (int)
* name -- VMM's VM name (str)
* mem -- memory VM was consuming (int)
Available properties:
* vmid -- VMM's VM ID number
* name -- VMM's VM name
* mem -- memory VM was consuming
"""
if not isinstance(vmid, int):
raise ProgrammingError("vmid not an int")
if not isinstance(name, str):
raise ProgrammingError("name not a string")
if not isinstance(mem, int):
raise ProgrammingError("mem not an int")
self.vmid = vmid
self.name = name
self.mem = mem
def __str__(self):
return "vmid=%d,name='%s',mem=%d" % (self.vmid, self.name, self.mem)
class KilledVMs(Exception):
"""Exception thrown by listener when it has destroyed a running VM."""
def __init__(self, listofVMs):
"""Populate the exception with list of killed VMs.
Required parameter:
* listofVMs -- a list of AKilledVM instances with length > 0
Available property:
* vms -- the list of AKilledVM instances
"""
errmsg = "listofVMs must be list with length > 0"
if listofVMs == None:
raise ProgrammingError(errmsg)
if not isinstance(listofVMs, list):
raise ProgrammingError(errmsg)
if len(listofVMs) < 1:
raise ProgrammingError(errmsg)
self.vms = listofVMs
def __str__(self):
ret = ""
for n,vm in enumerate(self.vms):
ret += "| #%d: %s " % (n+1,vm)
return ret
# }}} END: IV. Exceptions
# ############################################################
# V. Logging
# #########################################################{{{
class logWrap:
def __init__(self, logger):
"""This class is used to silence logging issues (broken pipe when
detached, file permission change, etc) from impeding operations.
Required parameters:
* logger -- the real logger
"""
self.logger = logger
def wrap(func, *args, **kw):
try:
result = func(*args, **kw)
except:
return None
return result
def debug(*args, **kw):
return self.wrap(self.logger.debug, *args, **kw)
def error(*args, **kw):
return self.wrap(self.logger.error, *args, **kw)
def info(*args, **kw):
return self.wrap(self.logger.info, *args, **kw)
def exception(*args, **kw):
return self.wrap(self.logger.exception, *args, **kw)
def critical(*args, **kw):
return self.wrap(self.logger.critical, *args, **kw)
def addHandler(*args, **kw):
return self.wrap(self.logger.addHandler, *args, **kw)
def getlog(override=None):
"""Allow developer to replace logging mechanism, e.g. if this
module is incorporated into another program as an API.
Keyword arguments:
* override -- Custom logger (default None, uses global variable)
"""
global _log
if override:
_log = override
try:
_log
except:
_log = logging.getLogger("workspace-pilot")
_log.setLevel(logging.DEBUG)
return _log
def configureLogging(level,
formatstring=None,
logger=None,
trace=False,
slotid=None,
stdout=False,
logfiledir=None,
logfileprefix=None):
"""Configure the logging format and mechanism. Sets global 'log' variable.
Required parameter:
* level -- log level
Keyword arguments:
* formatstring -- Custom logging format (default None, uses time+level+msg)
* logger -- Custom logger (default None)
* trace -- trace (default False)
* slotid -- identifier (default None)
* stdout -- also log to stdout (use with caution) (default False)
* logfiledir -- directory for log files (default None)
* logfileprefix -- prefix for log files, may remain None (default None)
"""
global log
logger = getlog(override=logger)
if not formatstring:
if trace:
formatstring = "%(asctime)s %(levelname)s @%(lineno)d: %(message)s"
else:
formatstring = "%(asctime)s %(levelname)s: %(message)s"
formatter = logging.Formatter(formatstring)
tracemessage = ""
if logfiledir:
if not os.path.isabs(logfiledir):
msg = "logfiledir is not an absolute path: '%s'" % logfiledir
raise InvalidConfig(msg)
if not os.path.exists(logfiledir):
msg = "logfiledir does not exist: '%s'" % logfiledir
raise InvalidConfig(msg)
if not os.path.isdir(logfiledir):
msg = "logfiledir is not a directory: '%s'" % logfiledir
raise InvalidConfig(msg)
logfilepath = ""
if logfileprefix:
logfilepath += str(logfileprefix)
if slotid:
logfilepath += str(slotid)
else:
logfilepath += str("otherlogs")
logfilepath += ".txt"
logfilepath = os.path.join(logfiledir, logfilepath)
f = None
try:
f = file(logfilepath, 'a')
f.write("\n## auto-generated @ %s\n\n" % time.ctime())
finally:
if f:
f.close()
logfilehandler = logging.FileHandler(logfilepath)
logfilehandler.setLevel(level)
logfilehandler.setFormatter(formatter)
logger.addHandler(logfilehandler)
tracemessage += "[file logging enabled @ '%s'] " % logfilepath
if stdout:
ch = logging.StreamHandler()
ch.setLevel(level)
ch.setFormatter(formatter)
logger.addHandler(ch)
tracemessage += "[stdout logging enabled]"
# set global variable
log = logger
if trace and tracemessage:
log.debug(tracemessage)
TIMESTAMP_PATH=None
def persistent_timestamp(eventname, workspid=0):
"""Record an event timestamp"""
if not TIMESTAMP_PATH:
return
# workspid will always be 0 or >0 from pilot, never -1
global _timestamp_lines
try:
_timestamp_lines
except:
_timestamp_lines = []
# needs milliseconds too
curtime = time.time()
timestr = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime(curtime))
ms = int((curtime - int(curtime)) * 1000)
timestr = timestr + "-" + str(ms)
seppi = "___"
line = seppi + str(eventname) + seppi + timestr + seppi + str(workspid) + seppi
try:
log.debug(line)
except:
pass
_timestamp_lines.append(line)
_timestamp_lines.append("\n")
return None
def write_persistent_timestamps():
"""Actually write the file out"""
if not TIMESTAMP_PATH:
return
global _timestamp_lines
try:
_timestamp_lines
except:
msg = "persistent_timestamp() never called?"
try:
log.critical(msg)
except:
print >> sys.stderr, msg
return None
f = None
try:
f = open(TIMESTAMP_PATH, 'a')
f.writelines(_timestamp_lines)
finally:
if f:
f.close()
_timestamp_lines = []
# }}} END: V. Logging
# ############################################################
# VI. Signal handlers
# #########################################################{{{
def getaction():
"""Used for signal handling"""
try:
_action
except:
return None
return _action
def setaction(action):
"""Used for signal handling"""
global _action
_action = action
def signal_handler(signame):
"""Triage a signal
Return (current action, elapsed secs) or **os._exit** (immediate stop).
"""
elapsed = elapsedsecs()
action = getaction()
if elapsed != None:
msg = "%s, elapsed seconds: %.3f" % (signame, elapsed)
else:
msg = "%s, elapsed seconds not recorded" % signame
if not log:
msg += ". No logger, assuming main was never traversed"
if action:
msg += " (but there was an action configured??)"
print >> sys.stderr, msg
os._exit(6)
print >> sys.stderr, msg
os._exit(5)
log.error(msg)
if not action:
log.error("no current action, assuming main was never traversed")
os._exit(5)
if not elapsed:
log.error("no elapsed seconds, assuming main was never traversed")
os._exit(5)
return (action, elapsed)
def sigint_handler(signum, frame):
"""Handle SIGINT"""
(action, elapsed) = signal_handler("SIGINT")
err = ""
try:
action.handle_sigint(elapsed)
except:
exception_type = sys.exc_type
try:
exceptname = exception_type.__name__
except AttributeError:
exceptname = exception_type
err = "Problem: %s: %s" % (str(exceptname), str(sys.exc_value))
write_persistent_timestamps()
if err:
log.error(err)
os._exit(6)
else:
os._exit(5)
def sigterm_handler(signum, frame):
"""Handle SIGTERM"""
(action, elapsed) = signal_handler("SIGTERM")
persistent_timestamp("PILOT18")
err = ""
try:
action.handle_sigterm(elapsed)
except:
exception_type = sys.exc_type
try:
exceptname = exception_type.__name__
except AttributeError:
exceptname = exception_type
err = "Problem: %s: %s" % (str(exceptname), str(sys.exc_value))
persistent_timestamp("PILOT90")
write_persistent_timestamps()
if err:
log.error(err)
os._exit(6)
else:
os._exit(5)
# }}} END: VI. Signal handlers
# ############################################################
# VII. Timer
# #########################################################{{{
def starttimer():
"""Record current time"""
global _t0
_t0 = time.time()
return None
def elapsedsecs():
"""Return elapsed seconds (float) since starttimer() was called."""
try:
_t0
except:
msg = "starttimer() never called"
if log:
log.critical(msg)
else:
print >> sys.stderr, msg
return None
t1 = time.time()
return t1 - _t0
# }}} END: VII. Timer
# ############################################################
# VIII. Path/system utilities
# #########################################################{{{
def checkabsexists(path, name):
"""Checks if path is absolute and exists.
Raises IncompatibleEnvironment if there is a problem.
Returns nothing.
"""
if not os.path.exists(path):
msg = "%s path '%s' does not exist on filesystem" % (name, path)
log.error(msg)
raise IncompatibleEnvironment(msg)
if path[0] != '/':
msg = "%s path '%s' should be absolute path" % (name, path)
log.error(msg)
raise IncompatibleEnvironment(msg)
def bashEscape(cmd):
"""returns \ escapes for some bash special characters
Required parameter:
* cmd - command string
Return escaped string.
"""
if not cmd:
return cmd
escs = "\\'`|;()?#$^&*="
for e in escs:
idx = 0
ret = 0
while ret != -1:
ret = cmd.find(e, idx)
if ret >= 0:
cmd = "%s\%s" % (cmd[:ret],cmd[ret:])
idx = ret + 2
return cmd
def modeStr(mode):
"""Returns string form of given mode."""
string=""
mode=stat.S_IMODE(mode)
for i in ("USR", "GRP", "OTH"):
for perm in "R", "W", "X":
if mode & getattr(stat, "S_I"+ perm + i):
string = string + perm.lower()
else:
string = string + "-"
return string
def checkrootpermissions(path, trace=False):
"""Check if root is the only account with ownership and write permissions
up to the / directory.
Required parameter:
* path -- Path in question. Assumed to be absolute
Keyword parameter:
* trace -- trace boolean, default False
Raises IncompatibleEnvironment if there is a problem.
"""
uidx = stat.ST_UID
gidx = stat.ST_GID
midx = stat.ST_MODE
log.debug("checking permissions: '%s'" % path)
# not guaranteed to be 'root'
pwentry = pwd.getpwuid(0)
uid0str = pwentry[0]
done = False
first = True
chownid = 0
chownuserstr = uid0str
while not done:
if not first:
(path, old) = os.path.split(path)
else:
first = False
try:
en = os.stat(path)
except:
exception_type = sys.exc_type
try:
exceptname = exception_type.__name__
except AttributeError:
exceptname = exception_type
name = str(exceptname)
err = str(sys.exc_value)
errmsg = "Problem stat-ing '%s': %s: %s\n" % (path, name, err)
log.error(errmsg)
raise IncompatibleEnvironment(errmsg)
if path == '/':
done = True
if trace:
permdetails = "%d:%d %s" % (en[uidx], en[gidx], modeStr(en[midx]))
if en[uidx] != chownid:
pwentry = pwd.getpwuid(en[uidx])
currchownuserstr = pwentry[0]
msg = "ownership of '%s' is %d " % (path, en[uidx])
msg += "(%s) but should be %d " % (currchownuserstr, chownid)
msg += "(%s)" % (chownuserstr)
raise IncompatibleEnvironment(msg)
else:
en = os.stat(path)
mode = stat.S_IMODE(en[midx])
pwentry = pwd.getpwuid(en[uidx])
currnam = pwentry[0]
grentry = grp.getgrgid(en[gidx])
currgrp = grentry[0]
worldrx = False
# not checking for the sticky bit, sane /tmp directories
# would not pass these simple tests (admin knows best)
if mode & stat.S_IWGRP or mode & stat.S_IWOTH:
msg = "'%s' has wrong permissions, " % path
msg += "path and all parent directories should only be "
msg += "owned and writeable by %s. Permissions: " % uid0str
msg += "%s:%s %s" % (currnam, currgrp, modeStr(en[midx]))
raise IncompatibleEnvironment(msg)
elif mode & stat.S_IROTH and mode & stat.S_IXOTH:
worldrx = True
if not worldrx:
msg = "OK: '%s'" % path
else:
msg = "OK: (world R+X) '%s'" % path
if trace:
msg += " (%s)" % permdetails
log.info(msg)
class SimpleRunThread(Thread):
"""Run a command with timeout options, delay, stdin, etc."""
def __init__ (self, cmd, killsig=-1, killtime=0, stdin=None, delay=None):
"""Populate the thread.
Required parameters:
* cmd -- command to run
Keyword parameters:
* killsig -- signum to kill with, default is unset
(needed if you set a killtime)
* killtime -- secs (float or int) to wait before kill, default is
unset (if set, needs killsig parameter)
* stdin -- optional stdin to push, default is unset
* delay -- secs (float or int) to wait before invoking cmd
Properties available:
* stdout -- stdout data or None
* stderr -- stderr data or None
* killed -- boolean, set True if cmd was killed
* exception -- if kill won't work
"""
Thread.__init__(self)
self.cmd = cmd
self.stdin = stdin
self.killsig = killsig
self.killtime = float(killtime)
self.delay = delay
self.exception = None
self.exit = None
self.stdout = None
self.stderr = None
self.killed = False
def run(self):
if self.delay:
log.debug("delaying for %.3f secs: '%s'" % (self.delay, self.cmd))
time.sleep(self.delay)
log.debug("program starting '%s'" % self.cmd)
p = Popen3(self.cmd, True)
if self.stdin:
if p.poll() == -1:
p.tochild.write(self.stdin)
p.tochild.flush()
p.tochild.close()
#log.debug("wrote '%s' to child" % self.stdin)
else:
log.error("child exited before stdin was written to")
done = False
while not done and self.killtime > 0:
time.sleep(0.2)
if p.poll() != -1:
done = True
self.killtime -= 0.2
if not done and self.killsig != -1:
try:
os.kill(p.pid, self.killsig)
self.killed = True
except OSError, e:
log.exception("problem killing")
self.exception = e
return
self.exit = p.wait()
self.stdout = p.fromchild.read()
self.stderr = p.childerr.read()
p.fromchild.close()
p.childerr.close()
log.debug("program ended: '%s'" % self.cmd)
def runsudotest(cmd, allowbadexit=False):
"""Run a test sudo command.
Required parameter:
* cmd -- command to run, string
Keyword parameters:
* allowbadexit -- don't throw exception if there was only a bad exit code
(default False)
Return stdout if successful.
Raises IncompatibleEnvironment if there is a problem.
"""
thr = SimpleRunThread(cmd, killsig=signal.SIGKILL, killtime=3)
thr.start()
thr.join()
configsudo = "\n\n **SUDO PROBLEM** Guessing you need to manually run "
configsudo += "sudo once in a terminal (try '%s'), many systems " % cmd
configsudo += "require each account to accept 'the rules' one time.\n\n"
if thr.stderr or thr.exit:
msg = "Problem running '%s'." % cmd
msg += "exit code = %d, stderr = %s" % (thr.exit, thr.stderr)
if thr.stderr.rfind("usual lecture") > 0:
msg += configsudo
if allowbadexit:
log.debug("OK error: %s" % msg)
else:
raise IncompatibleEnvironment(msg)
# sudo child won't take signals
if thr.exception:
raise IncompatibleEnvironment(configsudo)
return thr.stdout
def runexe(cmd, killtime=2.0):
"""Run a system program.
Required parameter:
* cmd -- command to run, string
Keyword parameter:
* killtime -- how many seconds to wait before SIGKILL (int or float)
Default is 2.0 seconds.
Return (exitcode, stdout, stderr)
* exitcode -- integer exit code
* stdout -- stdout or None
* stderr -- stderr or None
Raises IncompatibleEnvironment for serious issue (but not on non-zero exit)
"""