blob: ab8069a2a6aac7c8c27f77dc97d0f35124f52555 [file] [log] [blame]
mblighc86b0b42006-07-28 17:35:28 +00001"""Convenience functions for use by tests or whomever.
2"""
3
mblighff88e4e2006-05-25 19:34:52 +00004import os,os.path,shutil,urllib,sys,signal,commands,pickle
apwbc2867d2006-04-06 18:21:16 +00005from error import *
mbligh4e75b0d2006-08-29 15:22:44 +00006import re,string
mblighf4c35322006-03-13 01:01:10 +00007
8def grep(pattern, file):
mbligh7bdbfbd2006-09-30 16:47:01 +00009 """
10 This is mainly to fix the return code inversion from grep
11 Also handles compressed files.
12
13 returns 1 if the pattern is present in the file, 0 if not.
14 """
15 command = 'grep "%s" > /dev/null' % pattern
16 ret = cat_file_to_cmd(file, command, ignorestatus = 1)
17 return not ret
mblighf4c35322006-03-13 01:01:10 +000018
19
mblighc86b0b42006-07-28 17:35:28 +000020def difflist(list1, list2):
21 """returns items in list2 that are not in list1"""
mblighf4c35322006-03-13 01:01:10 +000022 diff = [];
23 for x in list2:
24 if x not in list1:
25 diff.append(x)
26 return diff
27
mblighc86b0b42006-07-28 17:35:28 +000028
mbligh7bdbfbd2006-09-30 16:47:01 +000029def cat_file_to_cmd(file, command, ignorestatus = 0):
30 """
31 equivalent to 'cat file | command' but knows to use
32 zcat or bzcat if appropriate
33 """
mbligh712cd142006-04-22 18:57:50 +000034 if not os.path.isfile(file):
35 raise NameError, 'invalid file %s to cat to command %s' % file, command
mblighf4c35322006-03-13 01:01:10 +000036 if file.endswith('.bz2'):
mbligh7bdbfbd2006-09-30 16:47:01 +000037 return system('bzcat ' + file + ' | ' + command, ignorestatus)
mbligh3d914912006-04-22 17:37:19 +000038 elif (file.endswith('.gz') or file.endswith('.tgz')):
mbligh7bdbfbd2006-09-30 16:47:01 +000039 return system('zcat ' + file + ' | ' + command, ignorestatus)
mblighf4c35322006-03-13 01:01:10 +000040 else:
mbligh7bdbfbd2006-09-30 16:47:01 +000041 return system('cat ' + file + ' | ' + command, ignorestatus)
mblighf4c35322006-03-13 01:01:10 +000042
mblighc86b0b42006-07-28 17:35:28 +000043
mbligh712cd142006-04-22 18:57:50 +000044def extract_tarball_to_dir(tarball, dir):
mblighc86b0b42006-07-28 17:35:28 +000045 """
46 Extract a tarball to a specified directory name instead of whatever
47 the top level of a tarball is - useful for versioned directory names, etc
48 """
mbligh712cd142006-04-22 18:57:50 +000049 if os.path.exists(dir):
50 raise NameError, 'target %s already exists' % dir
51 pwd = os.getcwd()
52 os.chdir(os.path.dirname(os.path.abspath(dir)))
53 newdir = extract_tarball(tarball)
54 os.rename(newdir, dir)
55 os.chdir(pwd)
56
57
mbligh712cd142006-04-22 18:57:50 +000058def extract_tarball(tarball):
mblighc86b0b42006-07-28 17:35:28 +000059 """Returns the first found newly created directory by the tarball extraction"""
mbligh712cd142006-04-22 18:57:50 +000060 oldlist = os.listdir('.')
61 cat_file_to_cmd(tarball, 'tar xf -')
62 newlist = os.listdir('.')
63 newfiles = difflist(oldlist, newlist) # what is new dir ?
64 new_dir = None
65 for newfile in newfiles:
66 if (os.path.isdir(newfile)):
67 return newfile
68 raise NameError, "extracting tarball produced no dir"
69
mblighcdf02a42006-04-23 02:22:49 +000070
mbligh78e17022006-09-13 19:58:12 +000071def update_version(srcdir, new_version, install, *args, **dargs):
mblighc86b0b42006-07-28 17:35:28 +000072 """Make sure srcdir is version new_version
73
74 If not, delete it and install() the new version
75 """
mbligh72905562006-05-25 01:30:49 +000076 versionfile = srcdir + '/.version'
mblighff88e4e2006-05-25 19:34:52 +000077 if os.path.exists(srcdir):
78 if os.path.exists(versionfile):
79 old_version = pickle.load(open(versionfile, 'r'))
80 if (old_version != new_version):
81 system('rm -rf ' + srcdir)
82 else:
mbligh72905562006-05-25 01:30:49 +000083 system('rm -rf ' + srcdir)
84 if not os.path.exists(srcdir):
mbligh78e17022006-09-13 19:58:12 +000085 install(*args, **dargs)
mbligh72905562006-05-25 01:30:49 +000086 if os.path.exists(srcdir):
87 pickle.dump(new_version, open(versionfile, 'w'))
88
89
mblighea30c8a2006-04-22 22:24:25 +000090def is_url(path):
mblighc86b0b42006-07-28 17:35:28 +000091 """true if path is a url
92 """
93 # should cope with other url types here, but we only handle http and ftp
mblighea30c8a2006-04-22 22:24:25 +000094 if (path.startswith('http://')) or (path.startswith('ftp://')):
mblighea30c8a2006-04-22 22:24:25 +000095 return 1
96 return 0
97
mblighcdf02a42006-04-23 02:22:49 +000098
mblighf4c35322006-03-13 01:01:10 +000099def get_file(src, dest):
mblighc86b0b42006-07-28 17:35:28 +0000100 """get a file, either from url or local"""
mbligh31186612006-04-22 21:55:56 +0000101 if (src == dest): # no-op here allows clean overrides in tests
102 return
mblighea30c8a2006-04-22 22:24:25 +0000103 if (is_url(src)):
mblighf4c35322006-03-13 01:01:10 +0000104 print 'PWD: ' + os.getcwd()
105 print 'Fetching \n\t', src, '\n\t->', dest
106 try:
107 urllib.urlretrieve(src, dest)
108 except IOError:
109 sys.stderr.write("Unable to retrieve %s (to %s)\n" % (src, dest))
110 sys.exit(1)
111 return dest
mblighf4c35322006-03-13 01:01:10 +0000112 shutil.copyfile(src, dest)
113 return dest
114
mblighea30c8a2006-04-22 22:24:25 +0000115
mbligh82641862006-04-23 06:21:36 +0000116def unmap_url(srcdir, src, destdir = '.'):
mbligh52508632006-09-30 18:29:55 +0000117 """
118 Receives either a path to a local file or a URL.
119 returns either the path to the local file, or the fetched URL
120
121 unmap_url('/usr/src', 'foo.tar', '/tmp')
122 = '/usr/src/foo.tar'
123 unmap_url('/usr/src', 'http://site/file', '/tmp')
124 = '/tmp/file'
125 (after retrieving it)
126 """
mblighea30c8a2006-04-22 22:24:25 +0000127 if is_url(src):
128 dest = destdir + '/' + os.path.basename(src)
129 get_file(src, dest)
130 return dest
mbligh82641862006-04-23 06:21:36 +0000131 else:
132 return srcdir + '/' + src
mblighea30c8a2006-04-22 22:24:25 +0000133
134
mblighf4c35322006-03-13 01:01:10 +0000135def basename(path):
136 i = path.rfind('/');
137 return path[i+1:]
138
139
140def force_copy(src, dest):
mblighc86b0b42006-07-28 17:35:28 +0000141 """Replace dest with a new copy of src, even if it exists"""
mblighf4c35322006-03-13 01:01:10 +0000142 if os.path.isfile(dest):
143 os.remove(dest)
144 return shutil.copyfile(src, dest)
145
146
mblighfdbcaec2006-10-01 23:28:57 +0000147def force_link(src, dest):
148 """Link src to dest, overwriting it if it exists"""
149 return system("ln -sf %s %s" % (src, dest))
150
151
mblighcdf02a42006-04-23 02:22:49 +0000152def file_contains_pattern(file, pattern):
mblighc86b0b42006-07-28 17:35:28 +0000153 """Return true if file contains the specified egrep pattern"""
mblighcdf02a42006-04-23 02:22:49 +0000154 if not os.path.isfile(file):
155 raise NameError, 'file %s does not exist' % file
mbligh5c1e26a2006-10-04 14:46:33 +0000156 return not system('egrep -q "' + pattern + '" ' + file, ignorestatus = 1)
mblighcdf02a42006-04-23 02:22:49 +0000157
158
159def list_grep(list, pattern):
mblighc86b0b42006-07-28 17:35:28 +0000160 """True if any item in list matches the specified pattern."""
mblighcdf02a42006-04-23 02:22:49 +0000161 compiled = re.compile(pattern)
162 for line in list:
163 match = compiled.search(line)
164 if (match):
165 return 1
166 return 0
167
mbligh42b81ca2006-09-30 22:10:01 +0000168def get_os_vendor():
169 """Try to guess what's the os vendor
170 """
171 issue = '/etc/issue'
172
173 if not os.path.isfile(issue):
174 return 'Unknown'
175
176 if file_contains_pattern(issue, 'Red Hat'):
177 return 'Red Hat'
178 elif file_contains_pattern(issue, 'Fedora Core'):
179 return 'Fedora Core'
180 elif file_contains_pattern(issue, 'SUSE'):
181 return 'SUSE'
182 elif file_contains_pattern(issue, 'Ubuntu'):
183 return 'Ubuntu'
184 else:
185 return 'Unknown'
186
mblighcdf02a42006-04-23 02:22:49 +0000187
mblighf49d5cf2006-04-23 02:24:42 +0000188def get_vmlinux():
mblighc86b0b42006-07-28 17:35:28 +0000189 """Return the full path to vmlinux
190
191 Ahem. This is crap. Pray harder. Bad Martin.
192 """
mblighad849ee2006-10-02 17:53:18 +0000193 vmlinux = '/boot/vmlinux-%s' % system_output('uname -r')
mbligh662a2a22006-10-01 17:01:14 +0000194 if os.path.isfile(vmlinux):
195 return vmlinux
mbligh17dbf052006-10-12 04:46:10 +0000196 vmlinux = '/lib/modules/%s/build/vmlinux' % system_output('uname -r')
197 if os.path.isfile(vmlinux):
198 return vmlinux
mbligh662a2a22006-10-01 17:01:14 +0000199 return None
mblighf49d5cf2006-04-23 02:24:42 +0000200
201
202def get_systemmap():
mblighc86b0b42006-07-28 17:35:28 +0000203 """Return the full path to System.map
204
205 Ahem. This is crap. Pray harder. Bad Martin.
206 """
mblighad849ee2006-10-02 17:53:18 +0000207 map = '/boot/System.map-%s' % system_output('uname -r')
mbligh662a2a22006-10-01 17:01:14 +0000208 if os.path.isfile(map):
209 return map
mbligh17dbf052006-10-12 04:46:10 +0000210 map = '/lib/modules/%s/build/System.map' % system_output('uname -r')
211 if os.path.isfile(map):
212 return map
mbligh662a2a22006-10-01 17:01:14 +0000213 return None
mbligh67b5ece2006-04-23 02:53:12 +0000214
215
216def get_modules_dir():
mblighc86b0b42006-07-28 17:35:28 +0000217 """Return the modules dir for the running kernel version"""
mbligh67b5ece2006-04-23 02:53:12 +0000218 kernel_version = system_output('uname -r')
219 return '/lib/modules/%s/kernel' % kernel_version
mblighf49d5cf2006-04-23 02:24:42 +0000220
221
mbligh5970cf02006-08-06 15:39:22 +0000222def get_cpu_arch():
mblighc86b0b42006-07-28 17:35:28 +0000223 """Work out which CPU architecture we're running on"""
mblighcdf02a42006-04-23 02:22:49 +0000224 f = open('/proc/cpuinfo', 'r')
225 cpuinfo = f.readlines()
226 f.close()
227 if list_grep(cpuinfo, '^cpu.*(RS64|POWER3|Broadband Engine)'):
228 return 'power'
229 elif list_grep(cpuinfo, '^cpu.*POWER4'):
230 return 'power4'
231 elif list_grep(cpuinfo, '^cpu.*POWER5'):
232 return 'power5'
233 elif list_grep(cpuinfo, '^cpu.*POWER6'):
234 return 'power6'
235 elif list_grep(cpuinfo, '^cpu.*PPC970'):
236 return 'power970'
237 elif list_grep(cpuinfo, 'Opteron'):
238 return 'x86_64'
239 elif list_grep(cpuinfo, 'GenuineIntel') and list_grep(cpuinfo, '48 bits virtual'):
mblighf4c35322006-03-13 01:01:10 +0000240 return 'x86_64'
241 else:
242 return 'i386'
243
244
mbligh548f29a2006-10-17 04:55:12 +0000245def get_current_kernel_arch():
246 """Get the machine architecture, now just a wrap of 'uname -m'."""
247 return os.popen('uname -m').read().rstrip()
mblighcdf02a42006-04-23 02:22:49 +0000248
249
mblighfdbcaec2006-10-01 23:28:57 +0000250def get_file_arch(filename):
251 # -L means follow symlinks
252 file_data = system_output('file -L ' + filename)
253 if file_data.count('80386'):
254 return 'i386'
255 return None
256
257
mbligh548f29a2006-10-17 04:55:12 +0000258def kernelexpand(kernel, args=None):
mblighf4c35322006-03-13 01:01:10 +0000259 # if not (kernel.startswith('http://') or kernel.startswith('ftp://') or os.path.isfile(kernel)):
mbligh5629af02006-09-15 01:54:23 +0000260 if kernel.find('/') < 0: # contains no path.
mbligh534015f2006-09-15 03:28:56 +0000261 autodir = os.environ['AUTODIR']
262 kernelexpand = os.path.join(autodir, 'tools/kernelexpand')
mbligh548f29a2006-10-17 04:55:12 +0000263 if args:
264 kernelexpand += ' ' + args
mbligh5629af02006-09-15 01:54:23 +0000265 w, r = os.popen2(kernelexpand + ' ' + kernel)
mblighf4c35322006-03-13 01:01:10 +0000266
267 kernel = r.readline().strip()
268 r.close()
269 w.close()
mbligh534015f2006-09-15 03:28:56 +0000270 return kernel.split()
mblighf4c35322006-03-13 01:01:10 +0000271
272
273def count_cpus():
mblighc86b0b42006-07-28 17:35:28 +0000274 """number of CPUs in the local machine according to /proc/cpuinfo"""
mblighf4c35322006-03-13 01:01:10 +0000275 f = file('/proc/cpuinfo', 'r')
276 cpus = 0
277 for line in f.readlines():
278 if line.startswith('processor'):
279 cpus += 1
280 return cpus
281
mbligha975fb62006-04-22 19:56:25 +0000282def system(cmd, ignorestatus = 0):
mblighc86b0b42006-07-28 17:35:28 +0000283 """os.system replacement
284
285 We have our own definition of system here, as the stock os.system doesn't
286 correctly handle sigpipe
287 (ie things like "yes | head" will hang because yes doesn't get the SIGPIPE).
288
289 Also the stock os.system didn't raise errors based on exit status, this
290 version does unless you explicitly specify ignorestatus=1
291 """
mblighf4c35322006-03-13 01:01:10 +0000292 signal.signal(signal.SIGPIPE, signal.SIG_DFL)
293 try:
apwbc2867d2006-04-06 18:21:16 +0000294 status = os.system(cmd)
mblighf4c35322006-03-13 01:01:10 +0000295 finally:
296 signal.signal(signal.SIGPIPE, signal.SIG_IGN)
mbligha975fb62006-04-22 19:56:25 +0000297
mbligh67b5ece2006-04-23 02:53:12 +0000298 if ((status != 0) and not ignorestatus):
apwbc2867d2006-04-06 18:21:16 +0000299 raise CmdError(cmd, status)
mbligha975fb62006-04-22 19:56:25 +0000300 return status
mbligh3d914912006-04-22 17:37:19 +0000301
302
mbligh67b5ece2006-04-23 02:53:12 +0000303def system_output(command, ignorestatus = 0):
mblighc86b0b42006-07-28 17:35:28 +0000304 """Run command and return its output
305
306 ignorestatus
307 whether to raise a CmdError if command has a nonzero exit status
308 """
mbligh67b5ece2006-04-23 02:53:12 +0000309 (result, data) = commands.getstatusoutput(command)
310 if ((result != 0) and not ignorestatus):
311 raise CmdError, 'command failed: ' + command
312 return data
313
314
mblighf4c35322006-03-13 01:01:10 +0000315def where_art_thy_filehandles():
mblighc86b0b42006-07-28 17:35:28 +0000316 """Dump the current list of filehandles"""
mblighf4c35322006-03-13 01:01:10 +0000317 os.system("ls -l /proc/%d/fd >> /dev/tty" % os.getpid())
318
319
320def print_to_tty(string):
mblighc86b0b42006-07-28 17:35:28 +0000321 """Output string straight to the tty"""
mblighf4c35322006-03-13 01:01:10 +0000322 os.system("echo " + string + " >> /dev/tty")
323
324
mblighb8a14e32006-05-06 00:17:35 +0000325def dump_object(object):
mblighc86b0b42006-07-28 17:35:28 +0000326 """Dump an object's attributes and methods
327
328 kind of like dir()
329 """
mblighb8a14e32006-05-06 00:17:35 +0000330 for item in object.__dict__.iteritems():
331 print item
332 try:
333 (key,value) = item
334 dump_object(value)
335 except:
336 continue
337
338
mbligh4b089662006-06-14 22:34:58 +0000339def environ(env_key):
mblighc86b0b42006-07-28 17:35:28 +0000340 """return the requested environment variable, or '' if unset"""
mbligh4b089662006-06-14 22:34:58 +0000341 if (os.environ.has_key(env_key)):
mblighd931a582006-10-01 00:30:12 +0000342 return os.environ[env_key]
mbligh4b089662006-06-14 22:34:58 +0000343 else:
344 return ''
345
346
347def prepend_path(newpath, oldpath):
mblighc86b0b42006-07-28 17:35:28 +0000348 """prepend newpath to oldpath"""
mbligh4b089662006-06-14 22:34:58 +0000349 if (oldpath):
350 return newpath + ':' + oldpath
351 else:
352 return newpath
353
354
355def append_path(oldpath, newpath):
mblighc86b0b42006-07-28 17:35:28 +0000356 """append newpath to oldpath"""
mbligh4b089662006-06-14 22:34:58 +0000357 if (oldpath):
358 return oldpath + ':' + newpath
359 else:
360 return newpath
361
362
mbligh4e75b0d2006-08-29 15:22:44 +0000363def avgtime_print(dir):
364 """ Calculate some benchmarking statistics.
365 Input is a directory containing a file called 'time'.
366 File contains one-per-line results of /usr/bin/time.
367 Output is average Elapsed, User, and System time in seconds,
368 and average CPU percentage.
369 """
370 f = open(dir + "/time")
371 user = system = elapsed = cpu = count = 0
372 r = re.compile('([\d\.]*)user ([\d\.]*)system (\d*):([\d\.]*)elapsed (\d*)%CPU')
373 for line in f.readlines():
374 try:
375 s = r.match(line);
mblighe1ee2672006-08-29 16:27:15 +0000376 user += float(s.group(1))
377 system += float(s.group(2))
378 elapsed += (float(s.group(3)) * 60) + float(s.group(4))
379 cpu += float(s.group(5))
mbligh4e75b0d2006-08-29 15:22:44 +0000380 count += 1
381 except:
382 raise ValueError("badly formatted times")
383
384 f.close()
385 return "Elapsed: %0.2fs User: %0.2fs System: %0.2fs CPU: %0.0f%%" % \
386 (elapsed/count, user/count, system/count, cpu/count)
387
388
mblighf06db0f2006-09-30 17:08:43 +0000389def running_config():
390 """
391 Return path of config file of the currently running kernel
392 """
393 for config in ('/proc/config.gz', \
394 '/boot/config-%s' % system_output('uname -r') ):
395 if os.path.isfile(config):
396 return config
397 return None
mbligh9ec8acc2006-10-05 06:52:33 +0000398
399
400def cpu_online_map():
401 """
402 Check out the available cpu online map
403 """
404 cpus = []
405 for line in open('/proc/cpuinfo', 'r').readlines():
406 if line.startswith('processor'):
407 cpus.append(line.split()[2]) # grab cpu number
408 return cpus
mbligh663e4f62006-10-11 05:03:40 +0000409
410
411def check_glibc_ver(ver):
412 glibc_ver = commands.getoutput('ldd --version').splitlines()[0]
mblighcabfdaf2006-10-11 14:07:48 +0000413 glibc_ver = re.search(r'(\d+\.\d+(\.\d+)?)', glibc_ver).group()
mblighea97ab82006-10-13 20:18:01 +0000414 if glibc_ver.split('.') < ver.split('.'):
415 raise "Glibc is too old (%s). Glibc >= %s is needed." % \
416 (glibc_ver, ver)
mbligh663e4f62006-10-11 05:03:40 +0000417
mblighea97ab82006-10-13 20:18:01 +0000418
419def check_python_version():
420 py_version = (sys.version).split(' ')[0]
421 version = py_version.split('.')[0:2]
422 if [int(x) for x in version] < [2, 4]:
apw25864da2006-10-17 08:19:26 +0000423 if os.path.exists("/usr/bin/python2.4"):
424 sys.argv.insert(0, "/usr/bin/python2.4")
425 os.execv(sys.argv[0], sys.argv)
mblighea97ab82006-10-13 20:18:01 +0000426 raise "Python 2.4 or newer is needed"