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
21 from Exceptions import *
24 ### handling breakpoints in the startup process
25 import select, sys, string
27 ### global debug settings
28 # NOTE. when BREAKPOINT_MODE turns out enabled,
29 # you have to attend the boot phase, that would hang otherwise
31 # enabling this will cause the node to ask for breakpoint-mode at startup
32 # production code should read False/False
34 # default for when prompt is turned off, or it's on but the timeout triggers
38 # in seconds : if no input, proceed
41 def prompt_for_breakpoint_mode ():
43 global BREAKPOINT_MODE
45 default_answer=BREAKPOINT_MODE
51 sys.stdout.write ("Want to run in breakpoint mode ? %s "%display)
53 r,w,e = select.select ([sys.stdin],[],[],PROMPT_TIMEOUT)
55 answer = string.strip(sys.stdin.readline())
57 sys.stdout.write("\nTimed-out (%d s)"%PROMPT_TIMEOUT)
59 BREAKPOINT_MODE = ( answer == "y" or answer == "Y")
61 BREAKPOINT_MODE = default_answer
65 sys.stdout.write("\nCurrent BREAKPOINT_MODE is %s\n"%label)
67 def breakpoint (message, cmd = None):
73 message=message+" -- Entering bash - type ^D to proceed"
79 ########################################
82 from python docs for os.makedirs:
83 Throws an error exception if the leaf directory
84 already exists or cannot be created.
86 That is real useful. Instead, we'll create the directory, then use a
87 separate function to test for its existance.
89 Return 1 if the directory exists and/or has been created, a BootManagerException
90 otherwise. Does not test the writability of said directory.
99 raise BootManagerException, "Unable to create directory tree: %s" % path
105 def removedir( path ):
107 remove a directory tree, return 1 if successful, a BootManagerException
116 shutil.rmtree( path )
117 except OSError, desc:
118 raise BootManagerException, "Unable to remove directory tree: %s" % path
124 def sysexec( cmd, log= None, fsck = False ):
126 execute a system command, output the results to the logger
129 return 1 if command completed (return code of non-zero),
130 0 if failed. A BootManagerException is raised if the command
131 was unable to execute or was interrupted by the user with Ctrl+C
134 print ("sysexec >>> %s" % cmd)
137 if cmd.__contains__(">"):
138 prog = subprocess.Popen(shlex.split(cmd), shell=True)
140 prog = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
142 raise BootManagerException, \
143 "Unable to create instance of subprocess.Popen " \
144 "for command: %s" % cmd
146 (stdoutdata, stderrdata) = prog.communicate()
147 except KeyboardInterrupt:
148 raise BootManagerException, "Interrupted by user"
151 log.write(stdoutdata)
153 returncode = prog.wait()
156 # The exit code returned by fsck is the sum of the following conditions:
158 # 1 - File system errors corrected
159 # 2 - System should be rebooted
160 # 4 - File system errors left uncorrected
161 # 8 - Operational error
162 # 16 - Usage or syntax error
163 # 32 - Fsck canceled by user request
164 # 128 - Shared library error
165 if returncode != 0 and returncode != 1:
166 raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode)
169 raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode)
175 def sysexec_chroot( path, cmd, log= None ):
177 same as sysexec, but inside a chroot
180 release = os.uname()[2]
181 # 2.6.12 kernels need this
182 if release[:5] == "2.6.1":
183 library = "%s/lib/libc-opendir-hack.so" % path
184 if not os.path.exists(library):
185 shutil.copy("./libc-opendir-hack.so", library)
186 preload = "/bin/env LD_PRELOAD=/lib/libc-opendir-hack.so"
187 sysexec("chroot %s %s %s" % (path, preload, cmd), log)
190 def sysexec_chroot_noerr( path, cmd, log= None ):
192 same as sysexec_chroot, but capture boot manager exceptions
196 rc= syexec_chroot( cmd, log )
197 except BootManagerException, e:
203 def sysexec_noerr( cmd, log= None ):
205 same as sysexec, but capture boot manager exceptions
209 rc= sysexec( cmd, log )
210 except BootManagerException, e:
219 change to a directory, return 1 if successful, a BootManagerException if failure
224 raise BootManagerException, "Unable to change to directory: %s" % dir
230 def removefile( filepath ):
232 removes a file, return 1 if successful, 0 if failure
235 os.remove( filepath )
237 raise BootManagerException, "Unable to remove file: %s" % filepath
243 # from: http://forums.devshed.com/archive/t-51149/
244 # Ethernet-card-address-Through-Python-or-C
247 return "%02x" % (ord(n))
249 def get_mac_from_interface(ifname):
251 given a device name, like eth0, return its mac_address.
252 return None if the device doesn't exist.
255 SIOCGIFHWADDR = 0x8927 # magic number
257 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
258 ifname = string.strip(ifname)
259 ifr = ifname + '\0'*(32-len(ifname))
262 r= fcntl.ioctl(s.fileno(),SIOCGIFHWADDR,ifr)
263 addr = map(hexy,r[18:24])
264 ret = (':'.join(map(str, addr)))
270 def check_file_hash(filename, hash_filename):
271 """Check the file's integrity with a given hash."""
272 return sha1_file(filename) == open(hash_filename).read().split()[0].strip()
274 def sha1_file(filename):
275 """Calculate sha1 hash of file."""
283 f = file(filename, 'rb')
285 # 256 KB seems ideal for speed/memory tradeoff
286 # It wont get much faster with bigger blocks, but
288 block = f.read(256 * 1024)
293 # Simple trick to keep total heap even lower
294 # Delete the previous block, so while next one is read
295 # we wont have two allocated blocks with same size
299 raise BootManagerException, "Cannot calculate SHA1 hash of %s" % filename