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 ### handling breakpoints in the startup process
22 import select, sys, string
24 ### global debug settings
25 # NOTE. when BREAKPOINT_MODE turns out enabled,
26 # you have to attend the boot phase, that would hang otherwise
28 # enabling this will cause the node to ask for breakpoint-mode at startup
29 # production code should read False/False
31 # default for when prompt is turned off, or it's on but the timeout triggers
35 # in seconds : if no input, proceed
38 def prompt_for_breakpoint_mode ():
40 global BREAKPOINT_MODE
42 default_answer=BREAKPOINT_MODE
48 sys.stdout.write ("Want to run in breakpoint mode ? %s "%display)
50 r,w,e = select.select ([sys.stdin],[],[],PROMPT_TIMEOUT)
52 answer = string.strip(sys.stdin.readline())
54 sys.stdout.write("\nTimed-out (%d s)"%PROMPT_TIMEOUT)
56 BREAKPOINT_MODE = ( answer == "y" or answer == "Y")
58 BREAKPOINT_MODE = default_answer
62 sys.stdout.write("\nCurrent BREAKPOINT_MODE is %s\n"%label)
64 def breakpoint (message, cmd = None):
70 message=message+" -- Entering bash - type ^D to proceed"
76 ########################################
79 from python docs for os.makedirs:
80 Throws an error exception if the leaf directory
81 already exists or cannot be created.
83 That is real useful. Instead, we'll create the directory, then use a
84 separate function to test for its existance.
86 Return 1 if the directory exists and/or has been created, a BootManagerException
87 otherwise. Does not test the writability of said directory.
96 raise BootManagerException, "Unable to create directory tree: %s" % path
102 def removedir( path ):
104 remove a directory tree, return 1 if successful, a BootManagerException
113 shutil.rmtree( path )
114 except OSError, desc:
115 raise BootManagerException, "Unable to remove directory tree: %s" % path
120 def sysexec( cmd, log=None, fsck=False, shell=False ):
122 execute a system command, output the results to the logger
125 return 1 if command completed (return code of non-zero),
126 0 if failed. A BootManagerException is raised if the command
127 was unable to execute or was interrupted by the user with Ctrl+C
130 # Thierry - Jan. 6 2011
131 # would probably make sense to look for | here as well
132 # however this is fragile and hard to test thoroughly
133 # let the caller set 'shell' when that is desirable
134 if shell or cmd.__contains__(">"):
135 prog = subprocess.Popen(cmd, shell=True)
137 print ("sysexec (shell mode) >>> %s" % cmd)
139 prog = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
141 print ("sysexec >>> %s" % cmd)
143 raise BootManagerException, \
144 "Unable to create instance of subprocess.Popen " \
145 "for command: %s" % cmd
147 (stdoutdata, stderrdata) = prog.communicate()
148 except KeyboardInterrupt:
149 raise BootManagerException, "Interrupted by user"
152 if stdoutdata is not None:
153 log.write(stdoutdata)
155 returncode = prog.wait()
158 # The exit code returned by fsck is the sum of the following conditions:
160 # 1 - File system errors corrected
161 # 2 - System should be rebooted
162 # 4 - File system errors left uncorrected
163 # 8 - Operational error
164 # 16 - Usage or syntax error
165 # 32 - Fsck canceled by user request
166 # 128 - Shared library error
167 if returncode != 0 and returncode != 1:
168 raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode)
171 raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode)
177 def sysexec_chroot( path, cmd, log=None, shell=False):
179 same as sysexec, but inside a chroot
182 release = os.uname()[2]
183 # 2.6.12 kernels need this
184 if release[:5] == "2.6.1":
185 library = "%s/lib/libc-opendir-hack.so" % path
186 if not os.path.exists(library):
187 shutil.copy("./libc-opendir-hack.so", library)
188 preload = "/bin/env LD_PRELOAD=/lib/libc-opendir-hack.so"
189 sysexec("chroot %s %s %s" % (path, preload, cmd), log, shell=shell)
192 def sysexec_chroot_noerr( path, cmd, log=None, shell=False ):
194 same as sysexec_chroot, but capture boot manager exceptions
198 rc= sysexec_chroot( cmd, log, shell=shell )
199 except BootManagerException, e:
205 def sysexec_noerr( cmd, log=None, shell=False ):
207 same as sysexec, but capture boot manager exceptions
211 rc= sysexec( cmd, log, shell=shell )
212 except BootManagerException, e:
221 change to a directory, return 1 if successful, a BootManagerException if failure
226 raise BootManagerException, "Unable to change to directory: %s" % dir
232 def removefile( filepath ):
234 removes a file, return 1 if successful, 0 if failure
237 os.remove( filepath )
239 raise BootManagerException, "Unable to remove file: %s" % filepath
245 # from: http://forums.devshed.com/archive/t-51149/
246 # Ethernet-card-address-Through-Python-or-C
249 return "%02x" % (ord(n))
251 def get_mac_from_interface(ifname):
253 given a device name, like eth0, return its mac_address.
254 return None if the device doesn't exist.
257 SIOCGIFHWADDR = 0x8927 # magic number
259 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
260 ifname = string.strip(ifname)
261 ifr = ifname + '\0'*(32-len(ifname))
264 r= fcntl.ioctl(s.fileno(),SIOCGIFHWADDR,ifr)
265 addr = map(hexy,r[18:24])
266 ret = (':'.join(map(str, addr)))
272 def check_file_hash(filename, hash_filename):
273 """Check the file's integrity with a given hash."""
274 return sha1_file(filename) == open(hash_filename).read().split()[0].strip()
276 def sha1_file(filename):
277 """Calculate sha1 hash of file."""
285 f = file(filename, 'rb')
287 # 256 KB seems ideal for speed/memory tradeoff
288 # It wont get much faster with bigger blocks, but
290 block = f.read(256 * 1024)
295 # Simple trick to keep total heap even lower
296 # Delete the previous block, so while next one is read
297 # we wont have two allocated blocks with same size
301 raise BootManagerException, "Cannot calculate SHA1 hash of %s" % filename