6 # Copyright (c) 2003 Intel Corporation
9 # Copyright (c) 2004-2006 The Trustees of Princeton University
10 # All rights reserved.
11 # expected /proc/partitions format
13 import os, sys, shutil
20 from Exceptions import *
23 ### handling breakpoints in the startup process
24 import select, sys, string
26 ### global debug settings
27 # NOTE. when BREAKPOINT_MODE turns out enabled,
28 # you have to attend the boot phase, that would hang otherwise
30 # enabling this will cause the node to ask for breakpoint-mode at startup
31 # production code should read False/False
33 # default for when prompt is turned off, or it's on but the timeout triggers
37 # in seconds : if no input, proceed
40 def prompt_for_breakpoint_mode ():
42 global BREAKPOINT_MODE
44 default_answer=BREAKPOINT_MODE
50 sys.stdout.write ("Want to run in breakpoint mode ? %s "%display)
52 r,w,e = select.select ([sys.stdin],[],[],PROMPT_TIMEOUT)
54 answer = string.strip(sys.stdin.readline())
56 sys.stdout.write("\nTimed-out (%d s)"%PROMPT_TIMEOUT)
58 BREAKPOINT_MODE = ( answer == "y" or answer == "Y")
60 BREAKPOINT_MODE = default_answer
64 sys.stdout.write("\nCurrent BREAKPOINT_MODE is %s\n"%label)
66 def breakpoint (message, cmd = None):
72 message=message+" -- Entering bash - type ^D to proceed"
78 ########################################
81 from python docs for os.makedirs:
82 Throws an error exception if the leaf directory
83 already exists or cannot be created.
85 That is real useful. Instead, we'll create the directory, then use a
86 separate function to test for its existance.
88 Return 1 if the directory exists and/or has been created, a BootManagerException
89 otherwise. Does not test the writability of said directory.
98 raise BootManagerException, "Unable to create directory tree: %s" % path
104 def removedir( path ):
106 remove a directory tree, return 1 if successful, a BootManagerException
115 shutil.rmtree( path )
116 except OSError, desc:
117 raise BootManagerException, "Unable to remove directory tree: %s" % path
123 def sysexec( cmd, log= None ):
125 execute a system command, output the results to the logger
128 return 1 if command completed (return code of non-zero),
129 0 if failed. A BootManagerException is raised if the command
130 was unable to execute or was interrupted by the user with Ctrl+C
133 print ("sysexec >>> %s" % cmd)
134 prog= popen2.Popen4( cmd, 0 )
136 raise BootManagerException, \
137 "Unable to create instance of popen2.Popen4 " \
138 "for command: %s" % cmd
142 for line in prog.fromchild:
144 except KeyboardInterrupt:
145 raise BootManagerException, "Interrupted by user"
147 returncode= prog.wait()
148 # revert http://git.planet-lab.org/?p=bootmanager.git;a=commitdiff;h=cca3a2cd2096c0235dddb5982b1f05c8d4c7f916
149 # as 256 returned by Python
155 #prog = popen2.Popen4( cmd, 0 )
156 #returncode = prog.wait()
162 raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode)
168 def sysexec_chroot( path, cmd, log= None ):
170 same as sysexec, but inside a chroot
173 release = os.uname()[2]
174 # 2.6.12 kernels need this
175 if release[:5] == "2.6.1":
176 library = "%s/lib/libc-opendir-hack.so" % path
177 if not os.path.exists(library):
178 shutil.copy("./libc-opendir-hack.so", library)
179 preload = "/bin/env LD_PRELOAD=/lib/libc-opendir-hack.so"
180 sysexec("chroot %s %s %s" % (path, preload, cmd), log)
183 def sysexec_chroot_noerr( path, cmd, log= None ):
185 same as sysexec_chroot, but capture boot manager exceptions
189 rc= syexec_chroot( cmd, log )
190 except BootManagerException, e:
196 def sysexec_noerr( cmd, log= None ):
198 same as sysexec, but capture boot manager exceptions
202 rc= sysexec( cmd, log )
203 except BootManagerException, e:
212 change to a directory, return 1 if successful, a BootManagerException if failure
217 raise BootManagerException, "Unable to change to directory: %s" % dir
223 def removefile( filepath ):
225 removes a file, return 1 if successful, 0 if failure
228 os.remove( filepath )
230 raise BootManagerException, "Unable to remove file: %s" % filepath
236 # from: http://forums.devshed.com/archive/t-51149/
237 # Ethernet-card-address-Through-Python-or-C
240 return "%02x" % (ord(n))
242 def get_mac_from_interface(ifname):
244 given a device name, like eth0, return its mac_address.
245 return None if the device doesn't exist.
248 SIOCGIFHWADDR = 0x8927 # magic number
250 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
251 ifname = string.strip(ifname)
252 ifr = ifname + '\0'*(32-len(ifname))
255 r= fcntl.ioctl(s.fileno(),SIOCGIFHWADDR,ifr)
256 addr = map(hexy,r[18:24])
257 ret = (':'.join(map(str, addr)))
263 def check_file_hash(filename, hash_filename):
264 """Check the file's integrity with a given hash."""
265 return sha1_file(filename) == open(hash_filename).read().split()[0].strip()
267 def sha1_file(filename):
268 """Calculate sha1 hash of file."""
276 f = file(filename, 'rb')
278 # 256 KB seems ideal for speed/memory tradeoff
279 # It wont get much faster with bigger blocks, but
281 block = f.read(256 * 1024)
286 # Simple trick to keep total heap even lower
287 # Delete the previous block, so while next one is read
288 # we wont have two allocated blocks with same size
292 raise BootManagerException, "Cannot calculate SHA1 hash of %s" % filename