3 # Copyright (c) 2003 Intel Corporation
6 # Copyright (c) 2004-2006 The Trustees of Princeton University
8 # expected /proc/partitions format
10 import os, sys, shutil
18 from Exceptions import *
21 # the simplest way to debug is to let the node take off,
22 # ssh into it as root using the debug ssh key in /etc/planetlab
23 # then go to /tmp/source
24 # edit this file locally to turn on breakpoints if needed, then run
28 ### handling breakpoints in the startup process
29 import select, sys, string
31 ### global debugging settings
33 # enabling this will cause the node to ask for breakpoint-mode at startup
34 # production code should read False/False
36 # default for when prompt is turned off, or it's on but the timeout triggers
37 BREAKPOINT_MODE = False
39 # verbose mode is just fine
41 # in seconds : if no input, proceed
44 def prompt_for_breakpoint_mode ():
46 global BREAKPOINT_MODE
48 default_answer = BREAKPOINT_MODE
54 sys.stdout.write ("Want to run in breakpoint mode ? {} ".format(display))
56 r, w, e = select.select ([sys.stdin], [], [], PROMPT_TIMEOUT)
58 answer = string.strip(sys.stdin.readline())
60 sys.stdout.write("\nTimed-out ({}s)".format(PROMPT_TIMEOUT))
62 BREAKPOINT_MODE = (answer == "y" or answer == "Y")
64 BREAKPOINT_MODE = default_answer
68 sys.stdout.write("\nCurrent BREAKPOINT_MODE is {}\n".format(label))
70 def breakpoint (message, cmd = None):
76 message = message + " -- Entering bash - type ^D to proceed"
82 ########################################
85 from python docs for os.makedirs:
86 Throws an error exception if the leaf directory
87 already exists or cannot be created.
89 That is real useful. Instead, we'll create the directory, then use a
90 separate function to test for its existance.
92 Return 1 if the directory exists and/or has been created, a BootManagerException
93 otherwise. Does not test the writability of said directory.
102 raise BootManagerException("Unable to create directory tree: {}".format(path))
110 remove a directory tree, return 1 if successful, a BootManagerException
120 except OSError as desc:
121 raise BootManagerException("Unable to remove directory tree: {}".format(path))
126 def sysexec(cmd, log=None, fsck=False, shell=False):
128 execute a system command, output the results to the logger
131 return 1 if command completed (return code of non-zero),
132 0 if failed. A BootManagerException is raised if the command
133 was unable to execute or was interrupted by the user with Ctrl+C
136 # Thierry - Jan. 6 2011
137 # would probably make sense to look for | here as well
138 # however this is fragile and hard to test thoroughly
139 # let the caller set 'shell' when that is desirable
140 if shell or cmd.__contains__(">"):
141 prog = subprocess.Popen(cmd, shell=True)
143 log.write("sysexec (shell mode) >>> {}".format(cmd))
145 print "sysexec (shell mode) >>> {}".format(cmd)
147 prog = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
149 log.write("sysexec >>> {}\n".format(cmd))
151 print "sysexec >>> {}".format(cmd)
153 raise BootManagerException(
154 "Unable to create instance of subprocess.Popen "
155 "for command: {}".format(cmd))
157 (stdoutdata, stderrdata) = prog.communicate()
158 except KeyboardInterrupt:
159 raise BootManagerException("Interrupted by user")
161 # log stdout & stderr
164 log.write("==========stdout\n" + stdoutdata)
166 log.write("==========stderr\n" + stderrdata)
168 returncode = prog.wait()
171 # The exit code returned by fsck is the sum of the following conditions:
173 # 1 - File system errors corrected
174 # 2 - System should be rebooted
175 # 4 - File system errors left uncorrected
176 # 8 - Operational error
177 # 16 - Usage or syntax error
178 # 32 - Fsck canceled by user request
179 # 128 - Shared library error
180 if returncode != 0 and returncode != 1:
181 raise BootManagerException("Running {} failed (rc={})".format(cmd, returncode))
184 raise BootManagerException("Running {} failed (rc={})".format(cmd, returncode))
190 def sysexec_chroot(path, cmd, log=None, shell=False):
192 same as sysexec, but inside a chroot
195 release = os.uname()[2]
196 # 2.6.12 kernels need this
197 if release[:5] == "2.6.1":
198 library = "{}/lib/libc-opendir-hack.so".format(path)
199 if not os.path.exists(library):
200 shutil.copy("./libc-opendir-hack.so", library)
201 preload = "/bin/env LD_PRELOAD=/lib/libc-opendir-hack.so"
202 sysexec("chroot {} {} {}".format(path, preload, cmd), log, shell=shell)
205 def sysexec_chroot_noerr(path, cmd, log=None, shell=False):
207 same as sysexec_chroot, but capture boot manager exceptions
211 rc = sysexec_chroot(cmd, log, shell=shell)
212 except BootManagerException as e:
218 def sysexec_noerr(cmd, log=None, shell=False):
220 same as sysexec, but capture boot manager exceptions
224 rc= sysexec(cmd, log, shell=shell)
225 except BootManagerException as e:
234 change to a directory, return 1 if successful, a BootManagerException if failure
239 raise BootManagerException("Unable to change to directory: {}".format(dir))
245 def removefile(filepath):
247 removes a file, return 1 if successful, 0 if failure
252 raise BootManagerException("Unable to remove file: {}".format(filepath))
258 # from: http://forums.devshed.com/archive/t-51149/
259 # Ethernet-card-address-Through-Python-or-C
261 def get_mac_from_interface(ifname):
263 given a device name, like eth0, return its mac_address.
264 return None if the device doesn't exist.
267 SIOCGIFHWADDR = 0x8927 # magic number
269 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
270 ifname = string.strip(ifname)
271 ifr = ifname + '\0'*(32-len(ifname))
274 r = fcntl.ioctl(s.fileno(), SIOCGIFHWADDR,ifr)
275 ret = ':'.join(["{:02x}".format(ord(n)) for n in r[18:24]])
281 def check_file_hash(filename, hash_filename):
282 """Check the file's integrity with a given hash."""
283 return sha1_file(filename) == open(hash_filename).read().split()[0].strip()
285 def sha1_file(filename):
286 """Calculate sha1 hash of file."""
294 f = file(filename, 'rb')
296 # 256 KB seems ideal for speed/memory tradeoff
297 # It wont get much faster with bigger blocks, but
299 block = f.read(256 * 1024)
304 # Simple trick to keep total heap even lower
305 # Delete the previous block, so while next one is read
306 # we wont have two allocated blocks with same size
310 raise BootManagerException("Cannot calculate SHA1 hash of {}".format(filename))