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