3c6c2251ad9066f48efed6390e2e3ebe56d2f45f
[bootmanager.git] / source / utils.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2003 Intel Corporation
4 # All rights reserved.
5 #
6 # Copyright (c) 2004-2006 The Trustees of Princeton University
7 # All rights reserved.
8 # expected /proc/partitions format
9
10 import os, sys, shutil
11 import subprocess
12 import shlex
13 import socket
14 import fcntl
15 import string
16 import exceptions
17
18 from Exceptions import *
19
20 ####################
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
25 # ./BootManager.py
26 ####################
27
28 ### handling breakpoints in the startup process
29 import select, sys, string
30
31 ### global debugging settings
32
33 # enabling this will cause the node to ask for breakpoint-mode at startup
34 # production code should read False/False
35 PROMPT_MODE=False
36 # default for when prompt is turned off, or it's on but the timeout triggers
37 BREAKPOINT_MODE=False
38
39 # verbose mode is just fine
40 VERBOSE_MODE=True
41 # in seconds : if no input, proceed
42 PROMPT_TIMEOUT=5
43
44 def prompt_for_breakpoint_mode ():
45
46     global BREAKPOINT_MODE
47     if PROMPT_MODE:
48         default_answer=BREAKPOINT_MODE
49         answer=''
50         if BREAKPOINT_MODE:
51             display="[y]/n"
52         else:
53             display="y/[n]"
54         sys.stdout.write ("Want to run in breakpoint mode ? %s "%display)
55         sys.stdout.flush()
56         r,w,e = select.select ([sys.stdin],[],[],PROMPT_TIMEOUT)
57         if r:
58             answer = string.strip(sys.stdin.readline())
59         else:
60             sys.stdout.write("\nTimed-out (%d s)"%PROMPT_TIMEOUT)
61         if answer:
62             BREAKPOINT_MODE = ( answer == "y" or answer == "Y")
63         else:
64             BREAKPOINT_MODE = default_answer
65     label="Off"
66     if BREAKPOINT_MODE:
67         label="On"
68     sys.stdout.write("\nCurrent BREAKPOINT_MODE is %s\n"%label)
69
70 def breakpoint (message, cmd = None):
71
72     if BREAKPOINT_MODE:
73
74         if cmd is None:
75             cmd="/bin/sh"
76             message=message+" -- Entering bash - type ^D to proceed"
77
78         print message
79         os.system(cmd)
80
81
82 ########################################
83 def makedirs( path ):
84     """
85     from python docs for os.makedirs:
86     Throws an error exception if the leaf directory
87     already exists or cannot be created.
88
89     That is real useful. Instead, we'll create the directory, then use a
90     separate function to test for its existance.
91
92     Return 1 if the directory exists and/or has been created, a BootManagerException
93     otherwise. Does not test the writability of said directory.
94     """
95     try:
96         os.makedirs( path )
97     except OSError:
98         pass
99     try:
100         os.listdir( path )
101     except OSError:
102         raise BootManagerException, "Unable to create directory tree: %s" % path
103     
104     return 1
105
106
107
108 def removedir( path ):
109     """
110     remove a directory tree, return 1 if successful, a BootManagerException
111     if failure.
112     """
113     try:
114         os.listdir( path )
115     except OSError:
116         return 1
117
118     try:
119         shutil.rmtree( path )
120     except OSError, desc:
121         raise BootManagerException, "Unable to remove directory tree: %s" % path
122     
123     return 1
124
125
126 def sysexec( cmd, log=None, fsck=False, shell=False ):
127     """
128     execute a system command, output the results to the logger
129     if log <> None
130
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
134     """
135     try:
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)
142             if log is not None:
143                 log.write("sysexec (shell mode) >>> %s" % cmd)
144             if VERBOSE_MODE:
145                 print "sysexec (shell mode) >>> %s" % cmd
146         else:
147             prog = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
148             if log is not None:
149                 log.write("sysexec >>> %s\n" % cmd)
150             if VERBOSE_MODE:
151                 print "sysexec >>> %s" % cmd
152     except OSError:
153         raise BootManagerException, \
154               "Unable to create instance of subprocess.Popen " \
155               "for command: %s" % cmd
156     try:
157         (stdoutdata, stderrdata) = prog.communicate()
158     except KeyboardInterrupt:
159         raise BootManagerException, "Interrupted by user"
160
161     # log stdout & stderr
162     if log is not None:
163         if stdoutdata:
164             log.write("==========stdout\n"+stdoutdata)
165         if stderrdata:
166             log.write("==========stderr\n"+stderrdata)
167
168     returncode = prog.wait()
169
170     if fsck:
171        # The exit code returned by fsck is the sum of the following conditions:
172        #      0    - No errors
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 %s failed (rc=%d)" % (cmd,returncode)
182     else:
183         if returncode != 0:
184             raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode)
185
186     prog = None
187     return 1
188
189
190 def sysexec_chroot( path, cmd, log=None, shell=False):
191     """
192     same as sysexec, but inside a chroot
193     """
194     preload = ""
195     release = os.uname()[2]
196     # 2.6.12 kernels need this
197     if release[:5] == "2.6.1":
198         library = "%s/lib/libc-opendir-hack.so" % 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 %s %s %s" % (path, preload, cmd), log, shell=shell)
203
204
205 def sysexec_chroot_noerr( path, cmd, log=None, shell=False ):
206     """
207     same as sysexec_chroot, but capture boot manager exceptions
208     """
209     try:
210         rc= 0
211         rc= sysexec_chroot( cmd, log, shell=shell )
212     except BootManagerException, e:
213         pass
214
215     return rc
216
217
218 def sysexec_noerr( cmd, log=None, shell=False ):
219     """
220     same as sysexec, but capture boot manager exceptions
221     """
222     try:
223         rc= 0
224         rc= sysexec( cmd, log, shell=shell )
225     except BootManagerException, e:
226         pass
227
228     return rc
229
230
231
232 def chdir( dir ):
233     """
234     change to a directory, return 1 if successful, a BootManagerException if failure
235     """
236     try:
237         os.chdir( dir )
238     except OSError:
239         raise BootManagerException, "Unable to change to directory: %s" % dir
240
241     return 1
242
243
244
245 def removefile( filepath ):
246     """
247     removes a file, return 1 if successful, 0 if failure
248     """
249     try:
250         os.remove( filepath )
251     except OSError:
252         raise BootManagerException, "Unable to remove file: %s" % filepath
253
254     return 1
255
256
257
258 # from: http://forums.devshed.com/archive/t-51149/
259 #              Ethernet-card-address-Through-Python-or-C
260
261 def hexy(n):
262     return "%02x" % (ord(n))
263
264 def get_mac_from_interface(ifname):
265     """
266     given a device name, like eth0, return its mac_address.
267     return None if the device doesn't exist.
268     """
269     
270     SIOCGIFHWADDR = 0x8927 # magic number
271
272     s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
273     ifname = string.strip(ifname)
274     ifr = ifname + '\0'*(32-len(ifname))
275
276     try:
277         r= fcntl.ioctl(s.fileno(),SIOCGIFHWADDR,ifr)
278         addr = map(hexy,r[18:24])
279         ret = (':'.join(map(str, addr)))
280     except IOError, e:
281         ret = None
282         
283     return ret
284
285 def check_file_hash(filename, hash_filename):
286     """Check the file's integrity with a given hash."""
287     return sha1_file(filename) == open(hash_filename).read().split()[0].strip()
288
289 def sha1_file(filename):
290     """Calculate sha1 hash of file."""
291     try:
292         try:
293             import hashlib
294             m = hashlib.sha1()
295         except:
296             import sha
297             m=sha.new()
298         f = file(filename, 'rb')
299         while True:
300             # 256 KB seems ideal for speed/memory tradeoff
301             # It wont get much faster with bigger blocks, but
302             # heap peak grows
303             block = f.read(256 * 1024)
304             if len(block) == 0:
305                 # end of file
306                 break
307             m.update(block)
308             # Simple trick to keep total heap even lower
309             # Delete the previous block, so while next one is read
310             # we wont have two allocated blocks with same size
311             del block
312         return m.hexdigest()
313     except IOError:
314         raise BootManagerException, "Cannot calculate SHA1 hash of %s" % filename