remove svn keywords and use %{SCMURL} in spec file
[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
121 def sysexec( cmd, log= None, fsck = False ):
122     """
123     execute a system command, output the results to the logger
124     if log <> None
125
126     return 1 if command completed (return code of non-zero),
127     0 if failed. A BootManagerException is raised if the command
128     was unable to execute or was interrupted by the user with Ctrl+C
129     """
130     if VERBOSE_MODE:
131         print ("sysexec >>> %s" % cmd)
132
133     try:
134         if cmd.__contains__(">"):
135             prog = subprocess.Popen(cmd, shell=True)
136         else:
137             prog = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
138     except OSError:
139         raise BootManagerException, \
140               "Unable to create instance of subprocess.Popen " \
141               "for command: %s" % cmd
142     try:
143         (stdoutdata, stderrdata) = prog.communicate()
144     except KeyboardInterrupt:
145         raise BootManagerException, "Interrupted by user"
146
147     if log is not None:
148         if stdoutdata is not None:
149             log.write(stdoutdata)
150
151     returncode = prog.wait()
152
153     if fsck:
154        # The exit code returned by fsck is the sum of the following conditions:
155        #      0    - No errors
156        #      1    - File system errors corrected
157        #      2    - System should be rebooted
158        #      4    - File system errors left uncorrected
159        #      8    - Operational error
160        #      16   - Usage or syntax error
161        #      32   - Fsck canceled by user request
162        #      128  - Shared library error
163        if returncode != 0 and returncode != 1:
164             raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode)
165     else:
166         if returncode != 0:
167             raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode)
168
169     prog = None
170     return 1
171
172
173 def sysexec_chroot( path, cmd, log= None ):
174     """
175     same as sysexec, but inside a chroot
176     """
177     preload = ""
178     release = os.uname()[2]
179     # 2.6.12 kernels need this
180     if release[:5] == "2.6.1":
181         library = "%s/lib/libc-opendir-hack.so" % path
182         if not os.path.exists(library):
183             shutil.copy("./libc-opendir-hack.so", library)
184         preload = "/bin/env LD_PRELOAD=/lib/libc-opendir-hack.so"
185     sysexec("chroot %s %s %s" % (path, preload, cmd), log)
186
187
188 def sysexec_chroot_noerr( path, cmd, log= None ):
189     """
190     same as sysexec_chroot, but capture boot manager exceptions
191     """
192     try:
193         rc= 0
194         rc= syexec_chroot( cmd, log )
195     except BootManagerException, e:
196         pass
197
198     return rc
199
200
201 def sysexec_noerr( cmd, log= None ):
202     """
203     same as sysexec, but capture boot manager exceptions
204     """
205     try:
206         rc= 0
207         rc= sysexec( cmd, log )
208     except BootManagerException, e:
209         pass
210
211     return rc
212
213
214
215 def chdir( dir ):
216     """
217     change to a directory, return 1 if successful, a BootManagerException if failure
218     """
219     try:
220         os.chdir( dir )
221     except OSError:
222         raise BootManagerException, "Unable to change to directory: %s" % dir
223
224     return 1
225
226
227
228 def removefile( filepath ):
229     """
230     removes a file, return 1 if successful, 0 if failure
231     """
232     try:
233         os.remove( filepath )
234     except OSError:
235         raise BootManagerException, "Unable to remove file: %s" % filepath
236
237     return 1
238
239
240
241 # from: http://forums.devshed.com/archive/t-51149/
242 #              Ethernet-card-address-Through-Python-or-C
243
244 def hexy(n):
245     return "%02x" % (ord(n))
246
247 def get_mac_from_interface(ifname):
248     """
249     given a device name, like eth0, return its mac_address.
250     return None if the device doesn't exist.
251     """
252     
253     SIOCGIFHWADDR = 0x8927 # magic number
254
255     s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
256     ifname = string.strip(ifname)
257     ifr = ifname + '\0'*(32-len(ifname))
258
259     try:
260         r= fcntl.ioctl(s.fileno(),SIOCGIFHWADDR,ifr)
261         addr = map(hexy,r[18:24])
262         ret = (':'.join(map(str, addr)))
263     except IOError, e:
264         ret = None
265         
266     return ret
267
268 def check_file_hash(filename, hash_filename):
269     """Check the file's integrity with a given hash."""
270     return sha1_file(filename) == open(hash_filename).read().split()[0].strip()
271
272 def sha1_file(filename):
273     """Calculate sha1 hash of file."""
274     try:
275         try:
276             import hashlib
277             m = hashlib.sha1()
278         except:
279             import sha
280             m=sha.new()
281         f = file(filename, 'rb')
282         while True:
283             # 256 KB seems ideal for speed/memory tradeoff
284             # It wont get much faster with bigger blocks, but
285             # heap peak grows
286             block = f.read(256 * 1024)
287             if len(block) == 0:
288                 # end of file
289                 break
290             m.update(block)
291             # Simple trick to keep total heap even lower
292             # Delete the previous block, so while next one is read
293             # we wont have two allocated blocks with same size
294             del block
295         return m.hexdigest()
296     except IOError:
297         raise BootManagerException, "Cannot calculate SHA1 hash of %s" % filename