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