3 # Copyright (c) 2003 Intel Corporation
6 # Copyright (c) 2004-2006 The Trustees of Princeton University
8 # expected /proc/partitions format
10 from __future__ import print_function
12 import os, sys, shutil
20 from Exceptions import *
23 # the simplest way to debug is to let the node take off,
24 # ssh into it as root using the debug ssh key in /etc/planetlab
25 # then go to /tmp/source
26 # edit this file locally to turn on breakpoints if needed, then run
30 ### handling breakpoints in the startup process
31 import select, sys, string
33 ### global debugging settings
35 # enabling this will cause the node to ask for breakpoint-mode at startup
36 # production code should read False/False
38 # default for when prompt is turned off, or it's on but the timeout triggers
39 BREAKPOINT_MODE = False
41 # verbose mode is just fine
43 # in seconds : if no input, proceed
46 def prompt_for_breakpoint_mode():
48 global BREAKPOINT_MODE
50 default_answer = BREAKPOINT_MODE
56 sys.stdout.write ("Want to run in breakpoint mode ? {} ".format(display))
58 r, w, e = select.select ([sys.stdin], [], [], PROMPT_TIMEOUT)
60 answer = string.strip(sys.stdin.readline())
62 sys.stdout.write("\nTimed-out ({}s)".format(PROMPT_TIMEOUT))
64 BREAKPOINT_MODE = (answer == "y" or answer == "Y")
66 BREAKPOINT_MODE = default_answer
70 sys.stdout.write("\nCurrent BREAKPOINT_MODE is {}\n".format(label))
72 def breakpoint (message, cmd = None):
78 message = message + " -- Entering bash - type ^D to proceed"
84 ########################################
87 from python docs for os.makedirs:
88 Throws an error exception if the leaf directory
89 already exists or cannot be created.
91 That is real useful. Instead, we'll create the directory, then use a
92 separate function to test for its existance.
94 Return 1 if the directory exists and/or has been created, a BootManagerException
95 otherwise. Does not test the writability of said directory.
104 raise BootManagerException("Unable to create directory tree: {}".format(path))
112 remove a directory tree, return 1 if successful, a BootManagerException
122 except OSError as desc:
123 raise BootManagerException("Unable to remove directory tree: {}".format(path))
128 def sysexec(cmd, log=None, fsck=False, shell=False):
130 execute a system command, output the results to the logger
133 return 1 if command completed (return code of non-zero),
134 0 if failed. A BootManagerException is raised if the command
135 was unable to execute or was interrupted by the user with Ctrl+C
138 # Thierry - Jan. 6 2011
139 # would probably make sense to look for | here as well
140 # however this is fragile and hard to test thoroughly
141 # let the caller set 'shell' when that is desirable
142 if shell or cmd.__contains__(">"):
143 prog = subprocess.Popen(cmd, shell=True)
145 log.write("sysexec (shell mode) >>> {}".format(cmd))
147 print("sysexec (shell mode) >>> {}".format(cmd))
149 prog = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
151 log.write("sysexec >>> {}\n".format(cmd))
153 print("sysexec >>> {}".format(cmd))
155 raise BootManagerException(
156 "Unable to create instance of subprocess.Popen "
157 "for command: {}".format(cmd))
159 (stdoutdata, stderrdata) = prog.communicate()
160 except KeyboardInterrupt:
161 raise BootManagerException("Interrupted by user")
163 # log stdout & stderr
166 log.write("==========stdout\n" + stdoutdata)
168 log.write("==========stderr\n" + stderrdata)
170 returncode = prog.wait()
173 # The exit code returned by fsck is the sum of the following conditions:
175 # 1 - File system errors corrected
176 # 2 - System should be rebooted
177 # 4 - File system errors left uncorrected
178 # 8 - Operational error
179 # 16 - Usage or syntax error
180 # 32 - Fsck canceled by user request
181 # 128 - Shared library error
182 if returncode != 0 and returncode != 1:
183 raise BootManagerException("Running {} failed (rc={})".format(cmd, returncode))
186 raise BootManagerException("Running {} failed (rc={})".format(cmd, returncode))
192 def sysexec_chroot(path, cmd, log=None, shell=False):
194 same as sysexec, but inside a chroot
197 release = os.uname()[2]
198 # 2.6.12 kernels need this
199 if release[:5] == "2.6.1":
200 library = "{}/lib/libc-opendir-hack.so".format(path)
201 if not os.path.exists(library):
202 shutil.copy("./libc-opendir-hack.so", library)
203 preload = "/bin/env LD_PRELOAD=/lib/libc-opendir-hack.so"
204 sysexec("chroot {} {} {}".format(path, preload, cmd), log, shell=shell)
207 def sysexec_chroot_noerr(path, cmd, log=None, shell=False):
209 same as sysexec_chroot, but capture boot manager exceptions
213 rc = sysexec_chroot(cmd, log, shell=shell)
214 except BootManagerException as e:
220 def sysexec_noerr(cmd, log=None, shell=False):
222 same as sysexec, but capture boot manager exceptions
226 rc = sysexec(cmd, log, shell=shell)
227 except BootManagerException as e:
236 change to a directory, return 1 if successful, a BootManagerException if failure
241 raise BootManagerException("Unable to change to directory: {}".format(dir))
247 def removefile(filepath):
249 removes a file, return 1 if successful, 0 if failure
254 raise BootManagerException("Unable to remove file: {}".format(filepath))
260 # from: http://forums.devshed.com/archive/t-51149/
261 # Ethernet-card-address-Through-Python-or-C
263 def get_mac_from_interface(ifname):
265 given a device name, like eth0, return its mac_address.
266 return None if the device doesn't exist.
269 SIOCGIFHWADDR = 0x8927 # magic number
271 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
272 ifname = string.strip(ifname)
273 ifr = ifname + '\0'*(32-len(ifname))
276 r = fcntl.ioctl(s.fileno(), SIOCGIFHWADDR,ifr)
277 ret = ':'.join(["{:02x}".format(ord(n)) for n in r[18:24]])
283 def check_file_hash(filename, hash_filename):
284 """Check the file's integrity with a given hash."""
285 return sha1_file(filename) == open(hash_filename).read().split()[0].strip()
287 def sha1_file(filename):
288 """Calculate sha1 hash of file."""
296 f = file(filename, 'rb')
298 # 256 KB seems ideal for speed/memory tradeoff
299 # It wont get much faster with bigger blocks, but
301 block = f.read(256 * 1024)
306 # Simple trick to keep total heap even lower
307 # Delete the previous block, so while next one is read
308 # we wont have two allocated blocks with same size
312 raise BootManagerException("Cannot calculate SHA1 hash of {}".format(filename))