58c8e480f69b041427f19b474dc9017247e8bb91
[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 ### handling breakpoints in the startup process
22 import select, sys, string
23
24 ### global debug settings
25 # NOTE. when BREAKPOINT_MODE turns out enabled,
26 # you have to attend the boot phase, that would hang otherwise 
27
28 # enabling this will cause the node to ask for breakpoint-mode at startup
29 # production code should read False/False
30 PROMPT_MODE=False
31 # default for when prompt is turned off, or it's on but the timeout triggers
32 BREAKPOINT_MODE=False
33 VERBOSE_MODE=False
34 VERBOSE_MODE=True
35 # in seconds : if no input, proceed
36 PROMPT_TIMEOUT=5
37
38 def prompt_for_breakpoint_mode ():
39
40     global BREAKPOINT_MODE
41     if PROMPT_MODE:
42         default_answer=BREAKPOINT_MODE
43         answer=''
44         if BREAKPOINT_MODE:
45             display="[y]/n"
46         else:
47             display="y/[n]"
48         sys.stdout.write ("Want to run in breakpoint mode ? %s "%display)
49         sys.stdout.flush()
50         r,w,e = select.select ([sys.stdin],[],[],PROMPT_TIMEOUT)
51         if r:
52             answer = string.strip(sys.stdin.readline())
53         else:
54             sys.stdout.write("\nTimed-out (%d s)"%PROMPT_TIMEOUT)
55         if answer:
56             BREAKPOINT_MODE = ( answer == "y" or answer == "Y")
57         else:
58             BREAKPOINT_MODE = default_answer
59     label="Off"
60     if BREAKPOINT_MODE:
61         label="On"
62     sys.stdout.write("\nCurrent BREAKPOINT_MODE is %s\n"%label)
63
64 def breakpoint (message, cmd = None):
65
66     if BREAKPOINT_MODE:
67
68         if cmd is None:
69             cmd="/bin/sh"
70             message=message+" -- Entering bash - type ^D to proceed"
71
72         print message
73         os.system(cmd)
74
75
76 ########################################
77 def makedirs( path ):
78     """
79     from python docs for os.makedirs:
80     Throws an error exception if the leaf directory
81     already exists or cannot be created.
82
83     That is real useful. Instead, we'll create the directory, then use a
84     separate function to test for its existance.
85
86     Return 1 if the directory exists and/or has been created, a BootManagerException
87     otherwise. Does not test the writability of said directory.
88     """
89     try:
90         os.makedirs( path )
91     except OSError:
92         pass
93     try:
94         os.listdir( path )
95     except OSError:
96         raise BootManagerException, "Unable to create directory tree: %s" % path
97     
98     return 1
99
100
101
102 def removedir( path ):
103     """
104     remove a directory tree, return 1 if successful, a BootManagerException
105     if failure.
106     """
107     try:
108         os.listdir( path )
109     except OSError:
110         return 1
111
112     try:
113         shutil.rmtree( path )
114     except OSError, desc:
115         raise BootManagerException, "Unable to remove directory tree: %s" % path
116     
117     return 1
118
119
120 def sysexec( cmd, log=None, fsck=False, shell=False ):
121     """
122     execute a system command, output the results to the logger
123     if log <> None
124
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
128     """
129     try:
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)
136             if VERBOSE_MODE:
137                 print ("sysexec (shell mode) >>> %s" % cmd)
138         else:
139             prog = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
140             if VERBOSE_MODE:
141                 print ("sysexec >>> %s" % cmd)
142     except OSError:
143         raise BootManagerException, \
144               "Unable to create instance of subprocess.Popen " \
145               "for command: %s" % cmd
146     try:
147         (stdoutdata, stderrdata) = prog.communicate()
148     except KeyboardInterrupt:
149         raise BootManagerException, "Interrupted by user"
150
151     if log is not None:
152         if stdoutdata is not None:
153             log.write(stdoutdata)
154
155     returncode = prog.wait()
156
157     if fsck:
158        # The exit code returned by fsck is the sum of the following conditions:
159        #      0    - No errors
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)
169     else:
170         if returncode != 0:
171             raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode)
172
173     prog = None
174     return 1
175
176
177 def sysexec_chroot( path, cmd, log=None, shell=False):
178     """
179     same as sysexec, but inside a chroot
180     """
181     preload = ""
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)
190
191
192 def sysexec_chroot_noerr( path, cmd, log=None, shell=False ):
193     """
194     same as sysexec_chroot, but capture boot manager exceptions
195     """
196     try:
197         rc= 0
198         rc= sysexec_chroot( cmd, log, shell=shell )
199     except BootManagerException, e:
200         pass
201
202     return rc
203
204
205 def sysexec_noerr( cmd, log=None, shell=False ):
206     """
207     same as sysexec, but capture boot manager exceptions
208     """
209     try:
210         rc= 0
211         rc= sysexec( cmd, log, shell=shell )
212     except BootManagerException, e:
213         pass
214
215     return rc
216
217
218
219 def chdir( dir ):
220     """
221     change to a directory, return 1 if successful, a BootManagerException if failure
222     """
223     try:
224         os.chdir( dir )
225     except OSError:
226         raise BootManagerException, "Unable to change to directory: %s" % dir
227
228     return 1
229
230
231
232 def removefile( filepath ):
233     """
234     removes a file, return 1 if successful, 0 if failure
235     """
236     try:
237         os.remove( filepath )
238     except OSError:
239         raise BootManagerException, "Unable to remove file: %s" % filepath
240
241     return 1
242
243
244
245 # from: http://forums.devshed.com/archive/t-51149/
246 #              Ethernet-card-address-Through-Python-or-C
247
248 def hexy(n):
249     return "%02x" % (ord(n))
250
251 def get_mac_from_interface(ifname):
252     """
253     given a device name, like eth0, return its mac_address.
254     return None if the device doesn't exist.
255     """
256     
257     SIOCGIFHWADDR = 0x8927 # magic number
258
259     s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
260     ifname = string.strip(ifname)
261     ifr = ifname + '\0'*(32-len(ifname))
262
263     try:
264         r= fcntl.ioctl(s.fileno(),SIOCGIFHWADDR,ifr)
265         addr = map(hexy,r[18:24])
266         ret = (':'.join(map(str, addr)))
267     except IOError, e:
268         ret = None
269         
270     return ret
271
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()
275
276 def sha1_file(filename):
277     """Calculate sha1 hash of file."""
278     try:
279         try:
280             import hashlib
281             m = hashlib.sha1()
282         except:
283             import sha
284             m=sha.new()
285         f = file(filename, 'rb')
286         while True:
287             # 256 KB seems ideal for speed/memory tradeoff
288             # It wont get much faster with bigger blocks, but
289             # heap peak grows
290             block = f.read(256 * 1024)
291             if len(block) == 0:
292                 # end of file
293                 break
294             m.update(block)
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
298             del block
299         return m.hexdigest()
300     except IOError:
301         raise BootManagerException, "Cannot calculate SHA1 hash of %s" % filename