Copyright notice for both Intel and Princeton
[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
20 def makedirs( path ):
21     """
22     from python docs for os.makedirs:
23     Throws an error exception if the leaf directory
24     already exists or cannot be created.
25
26     That is real useful. Instead, we'll create the directory, then use a
27     separate function to test for its existance.
28
29     Return 1 if the directory exists and/or has been created, a BootManagerException
30     otherwise. Does not test the writability of said directory.
31     """
32     try:
33         os.makedirs( path )
34     except OSError:
35         pass
36     try:
37         os.listdir( path )
38     except OSError:
39         raise BootManagerException, "Unable to create directory tree: %s" % path
40     
41     return 1
42
43
44
45 def removedir( path ):
46     """
47     remove a directory tree, return 1 if successful, a BootManagerException
48     if failure.
49     """
50     try:
51         os.listdir( path )
52     except OSError:
53         return 1
54
55     try:
56         shutil.rmtree( path )
57     except OSError, desc:
58         raise BootManagerException, "Unable to remove directory tree: %s" % path
59     
60     return 1
61
62
63
64 def sysexec( cmd, log= None ):
65     """
66     execute a system command, output the results to the logger
67     if log <> None
68
69     return 1 if command completed (return code of non-zero),
70     0 if failed. A BootManagerException is raised if the command
71     was unable to execute or was interrupted by the user with Ctrl+C
72     """
73     prog= popen2.Popen4( cmd, 0 )
74     if prog is None:
75         raise BootManagerException, \
76               "Unable to create instance of popen2.Popen3 " \
77               "for command: %s" % cmd
78
79     if log is not None:
80         try:
81             for line in prog.fromchild:
82                 log.write( line )
83         except KeyboardInterrupt:
84             raise BootManagerException, "Interrupted by user"
85
86     returncode= prog.wait()
87     if returncode != 0:
88         raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode)
89
90     prog= None
91     return 1
92
93
94 def sysexec_noerr( cmd, log= None ):
95     """
96     same as sysexec, but capture boot manager exceptions
97     """
98     try:
99         rc= 0
100         rc= sysexec( cmd, log )
101     except BootManagerException, e:
102         pass
103
104     return rc
105
106
107
108 def chdir( dir ):
109     """
110     change to a directory, return 1 if successful, a BootManagerException if failure
111     """
112     try:
113         os.chdir( dir )
114     except OSError:
115         raise BootManagerException, "Unable to change to directory: %s" % dir
116
117     return 1
118
119
120
121 def removefile( filepath ):
122     """
123     removes a file, return 1 if successful, 0 if failure
124     """
125     try:
126         os.remove( filepath )
127     except OSError:
128         raise BootManagerException, "Unable to remove file: %s" % filepath
129
130     return 1
131
132
133
134 # from: http://forums.devshed.com/archive/t-51149/
135 #              Ethernet-card-address-Through-Python-or-C
136
137 def hexy(n):
138     return "%02x" % (ord(n))
139
140 def get_mac_from_interface(ifname):
141     """
142     given a device name, like eth0, return its mac_address.
143     return None if the device doesn't exist.
144     """
145     
146     SIOCGIFHWADDR = 0x8927 # magic number
147
148     s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
149     ifname = string.strip(ifname)
150     ifr = ifname + '\0'*(32-len(ifname))
151
152     try:
153         r= fcntl.ioctl(s.fileno(),SIOCGIFHWADDR,ifr)
154         addr = map(hexy,r[18:24])
155         ret = (':'.join(map(str, addr)))
156     except IOError, e:
157         ret = None
158         
159     return ret
160