only look at /etc/modprobe.d/{blacklist,blacklist-compat,blacklist-firewire}
[bootmanager.git] / source / utils.py
1 #!/usr/bin/python2
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 popen2
12 import socket
13 import fcntl
14 import string
15 import exceptions
16
17 from Exceptions import *
18
19 ### handling breakpoints in the startup process
20 import select, sys, string
21
22 ### global debug settings
23 # NOTE. when BREAKPOINT_MODE turns out enabled,
24 # you have to attend the boot phase, that would hang otherwise 
25
26 # enabling this will cause the node to ask for breakpoint-mode at startup
27 # production code should read False/False
28 PROMPT_MODE=False
29 # default for when prompt is turned off, or it's on but the timeout triggers
30 BREAKPOINT_MODE=False
31 VERBOSE_MODE=False
32 VERBOSE_MODE=True
33 # in seconds : if no input, proceed
34 PROMPT_TIMEOUT=5
35
36 def prompt_for_breakpoint_mode ():
37
38     global BREAKPOINT_MODE
39     if PROMPT_MODE:
40         default_answer=BREAKPOINT_MODE
41         answer=''
42         if BREAKPOINT_MODE:
43             display="[y]/n"
44         else:
45             display="y/[n]"
46         sys.stdout.write ("Want to run in breakpoint mode ? %s "%display)
47         sys.stdout.flush()
48         r,w,e = select.select ([sys.stdin],[],[],PROMPT_TIMEOUT)
49         if r:
50             answer = string.strip(sys.stdin.readline())
51         else:
52             sys.stdout.write("\nTimed-out (%d s)"%PROMPT_TIMEOUT)
53         if answer:
54             BREAKPOINT_MODE = ( answer == "y" or answer == "Y")
55         else:
56             BREAKPOINT_MODE = default_answer
57     label="Off"
58     if BREAKPOINT_MODE:
59         label="On"
60     sys.stdout.write("\nCurrent BREAKPOINT_MODE is %s\n"%label)
61
62 def breakpoint (message, cmd = None):
63
64     if BREAKPOINT_MODE:
65
66         if cmd is None:
67             cmd="/bin/sh"
68             message=message+" -- Entering bash - type ^D to proceed"
69
70         print message
71         os.system(cmd)
72
73 ##############################
74 def makedirs( path ):
75     """
76     from python docs for os.makedirs:
77     Throws an error exception if the leaf directory
78     already exists or cannot be created.
79
80     That is real useful. Instead, we'll create the directory, then use a
81     separate function to test for its existance.
82
83     Return 1 if the directory exists and/or has been created, a BootManagerException
84     otherwise. Does not test the writability of said directory.
85     """
86     try:
87         os.makedirs( path )
88     except OSError:
89         pass
90     try:
91         os.listdir( path )
92     except OSError:
93         raise BootManagerException, "Unable to create directory tree: %s" % path
94     
95     return 1
96
97
98
99 def removedir( path ):
100     """
101     remove a directory tree, return 1 if successful, a BootManagerException
102     if failure.
103     """
104     try:
105         os.listdir( path )
106     except OSError:
107         return 1
108
109     try:
110         shutil.rmtree( path )
111     except OSError, desc:
112         raise BootManagerException, "Unable to remove directory tree: %s" % path
113     
114     return 1
115
116
117
118 def sysexec( cmd, log= None ):
119     """
120     execute a system command, output the results to the logger
121     if log <> None
122
123     return 1 if command completed (return code of non-zero),
124     0 if failed. A BootManagerException is raised if the command
125     was unable to execute or was interrupted by the user with Ctrl+C
126     """
127     if VERBOSE_MODE:
128         print ("sysexec >>> %s" % cmd)
129     prog= popen2.Popen4( cmd, 0 )
130     if prog is None:
131         raise BootManagerException, \
132               "Unable to create instance of popen2.Popen4 " \
133               "for command: %s" % cmd
134
135     if log is not None:
136         try:
137             for line in prog.fromchild:
138                 log.write( line )
139         except KeyboardInterrupt:
140             raise BootManagerException, "Interrupted by user"
141
142     returncode= prog.wait()
143     if returncode != 0:
144         raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode)
145
146     prog= None
147     return 1
148
149
150 globals()['_chroot_lib_copied'] = False
151 def sysexec_chroot( path, cmd, log= None ):
152     """
153     same as sysexec, but inside a chroot
154     """
155     preload = ""
156     release = os.uname()[2]
157     # 2.6.12 kernels need this
158     if release[:5] == "2.6.1":
159         library = "/lib/libc-opendir-hack.so"
160         if not globals()['_chroot_lib_copied']:
161             shutil.copy("./libc-opendir-hack.so", "%s%s" % (path, library))
162             globals()['_chroot_lib_copied'] = True
163         preload = "/bin/env LD_PRELOAD=%s" % library
164     return sysexec("chroot %s %s %s" % (path, preload, cmd), log)
165
166
167 def sysexec_chroot_noerr( path, cmd, log= None ):
168     """
169     same as sysexec_chroot, but capture boot manager exceptions
170     """
171     try:
172         rc= 0
173         rc= sysexec_chroot( cmd, log )
174     except BootManagerException, e:
175         pass
176
177     return rc
178
179
180 def sysexec_noerr( cmd, log= None ):
181     """
182     same as sysexec, but capture boot manager exceptions
183     """
184     try:
185         rc= 0
186         rc= sysexec( cmd, log )
187     except BootManagerException, e:
188         pass
189
190     return rc
191
192
193
194 def chdir( dir ):
195     """
196     change to a directory, return 1 if successful, a BootManagerException if failure
197     """
198     try:
199         os.chdir( dir )
200     except OSError:
201         raise BootManagerException, "Unable to change to directory: %s" % dir
202
203     return 1
204
205
206
207 def removefile( filepath ):
208     """
209     removes a file, return 1 if successful, 0 if failure
210     """
211     try:
212         os.remove( filepath )
213     except OSError:
214         raise BootManagerException, "Unable to remove file: %s" % filepath
215
216     return 1
217
218
219
220 # from: http://forums.devshed.com/archive/t-51149/
221 #              Ethernet-card-address-Through-Python-or-C
222
223 def hexy(n):
224     return "%02x" % (ord(n))
225
226 def get_mac_from_interface(ifname):
227     """
228     given a device name, like eth0, return its mac_address.
229     return None if the device doesn't exist.
230     """
231     
232     SIOCGIFHWADDR = 0x8927 # magic number
233
234     s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
235     ifname = string.strip(ifname)
236     ifr = ifname + '\0'*(32-len(ifname))
237
238     try:
239         r= fcntl.ioctl(s.fileno(),SIOCGIFHWADDR,ifr)
240         addr = map(hexy,r[18:24])
241         ret = (':'.join(map(str, addr)))
242     except IOError, e:
243         ret = None
244         
245     return ret
246