blob: b5dab8463ad4d7f341fec99be89dc35e1632bef9 [file] [log] [blame]
mblighc86b0b42006-07-28 17:35:28 +00001"""Convenience functions for use by tests or whomever.
2"""
3
mbligh8eca3a92007-02-03 20:59:39 +00004import os,os.path,shutil,urllib,sys,signal,commands,pickle,glob
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
mbligh8eca3a92007-02-03 20:59:39 +000099def get_file(src, dest, permissions = None):
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)
mbligh8eca3a92007-02-03 20:59:39 +0000111 else:
112 shutil.copyfile(src, dest)
113 if permissions:
114 os.chmod(permissions)
mblighf4c35322006-03-13 01:01:10 +0000115 return dest
116
mblighea30c8a2006-04-22 22:24:25 +0000117
mbligh82641862006-04-23 06:21:36 +0000118def unmap_url(srcdir, src, destdir = '.'):
mbligh52508632006-09-30 18:29:55 +0000119 """
120 Receives either a path to a local file or a URL.
121 returns either the path to the local file, or the fetched URL
122
123 unmap_url('/usr/src', 'foo.tar', '/tmp')
124 = '/usr/src/foo.tar'
125 unmap_url('/usr/src', 'http://site/file', '/tmp')
126 = '/tmp/file'
127 (after retrieving it)
128 """
mblighea30c8a2006-04-22 22:24:25 +0000129 if is_url(src):
130 dest = destdir + '/' + os.path.basename(src)
131 get_file(src, dest)
132 return dest
mbligh82641862006-04-23 06:21:36 +0000133 else:
134 return srcdir + '/' + src
mblighea30c8a2006-04-22 22:24:25 +0000135
136
mblighf4c35322006-03-13 01:01:10 +0000137def basename(path):
138 i = path.rfind('/');
139 return path[i+1:]
140
141
142def force_copy(src, dest):
mblighc86b0b42006-07-28 17:35:28 +0000143 """Replace dest with a new copy of src, even if it exists"""
mblighf4c35322006-03-13 01:01:10 +0000144 if os.path.isfile(dest):
145 os.remove(dest)
mbligh1e8858e2006-11-24 22:18:35 +0000146 if os.path.isdir(dest):
147 dest = os.path.join(dest, os.path.basename(src))
mblighf4c35322006-03-13 01:01:10 +0000148 return shutil.copyfile(src, dest)
149
150
mblighfdbcaec2006-10-01 23:28:57 +0000151def force_link(src, dest):
152 """Link src to dest, overwriting it if it exists"""
153 return system("ln -sf %s %s" % (src, dest))
154
155
mblighcdf02a42006-04-23 02:22:49 +0000156def file_contains_pattern(file, pattern):
mblighc86b0b42006-07-28 17:35:28 +0000157 """Return true if file contains the specified egrep pattern"""
mblighcdf02a42006-04-23 02:22:49 +0000158 if not os.path.isfile(file):
159 raise NameError, 'file %s does not exist' % file
mbligh5c1e26a2006-10-04 14:46:33 +0000160 return not system('egrep -q "' + pattern + '" ' + file, ignorestatus = 1)
mblighcdf02a42006-04-23 02:22:49 +0000161
162
163def list_grep(list, pattern):
mblighc86b0b42006-07-28 17:35:28 +0000164 """True if any item in list matches the specified pattern."""
mblighcdf02a42006-04-23 02:22:49 +0000165 compiled = re.compile(pattern)
166 for line in list:
167 match = compiled.search(line)
168 if (match):
169 return 1
170 return 0
171
mbligh42b81ca2006-09-30 22:10:01 +0000172def get_os_vendor():
173 """Try to guess what's the os vendor
174 """
175 issue = '/etc/issue'
176
177 if not os.path.isfile(issue):
178 return 'Unknown'
179
180 if file_contains_pattern(issue, 'Red Hat'):
181 return 'Red Hat'
182 elif file_contains_pattern(issue, 'Fedora Core'):
183 return 'Fedora Core'
184 elif file_contains_pattern(issue, 'SUSE'):
185 return 'SUSE'
186 elif file_contains_pattern(issue, 'Ubuntu'):
187 return 'Ubuntu'
188 else:
189 return 'Unknown'
190
mblighcdf02a42006-04-23 02:22:49 +0000191
mblighf49d5cf2006-04-23 02:24:42 +0000192def get_vmlinux():
mblighc86b0b42006-07-28 17:35:28 +0000193 """Return the full path to vmlinux
194
195 Ahem. This is crap. Pray harder. Bad Martin.
196 """
mblighad849ee2006-10-02 17:53:18 +0000197 vmlinux = '/boot/vmlinux-%s' % system_output('uname -r')
mbligh662a2a22006-10-01 17:01:14 +0000198 if os.path.isfile(vmlinux):
199 return vmlinux
mbligh17dbf052006-10-12 04:46:10 +0000200 vmlinux = '/lib/modules/%s/build/vmlinux' % system_output('uname -r')
201 if os.path.isfile(vmlinux):
202 return vmlinux
mbligh662a2a22006-10-01 17:01:14 +0000203 return None
mblighf49d5cf2006-04-23 02:24:42 +0000204
205
206def get_systemmap():
mblighc86b0b42006-07-28 17:35:28 +0000207 """Return the full path to System.map
208
209 Ahem. This is crap. Pray harder. Bad Martin.
210 """
mblighad849ee2006-10-02 17:53:18 +0000211 map = '/boot/System.map-%s' % system_output('uname -r')
mbligh662a2a22006-10-01 17:01:14 +0000212 if os.path.isfile(map):
213 return map
mbligh17dbf052006-10-12 04:46:10 +0000214 map = '/lib/modules/%s/build/System.map' % system_output('uname -r')
215 if os.path.isfile(map):
216 return map
mbligh662a2a22006-10-01 17:01:14 +0000217 return None
mbligh67b5ece2006-04-23 02:53:12 +0000218
219
220def get_modules_dir():
mblighc86b0b42006-07-28 17:35:28 +0000221 """Return the modules dir for the running kernel version"""
mbligh67b5ece2006-04-23 02:53:12 +0000222 kernel_version = system_output('uname -r')
223 return '/lib/modules/%s/kernel' % kernel_version
mblighf49d5cf2006-04-23 02:24:42 +0000224
225
mbligh5970cf02006-08-06 15:39:22 +0000226def get_cpu_arch():
mblighc86b0b42006-07-28 17:35:28 +0000227 """Work out which CPU architecture we're running on"""
mblighcdf02a42006-04-23 02:22:49 +0000228 f = open('/proc/cpuinfo', 'r')
229 cpuinfo = f.readlines()
230 f.close()
231 if list_grep(cpuinfo, '^cpu.*(RS64|POWER3|Broadband Engine)'):
232 return 'power'
233 elif list_grep(cpuinfo, '^cpu.*POWER4'):
234 return 'power4'
235 elif list_grep(cpuinfo, '^cpu.*POWER5'):
236 return 'power5'
237 elif list_grep(cpuinfo, '^cpu.*POWER6'):
238 return 'power6'
239 elif list_grep(cpuinfo, '^cpu.*PPC970'):
240 return 'power970'
241 elif list_grep(cpuinfo, 'Opteron'):
242 return 'x86_64'
243 elif list_grep(cpuinfo, 'GenuineIntel') and list_grep(cpuinfo, '48 bits virtual'):
mblighf4c35322006-03-13 01:01:10 +0000244 return 'x86_64'
245 else:
246 return 'i386'
247
248
mbligh548f29a2006-10-17 04:55:12 +0000249def get_current_kernel_arch():
250 """Get the machine architecture, now just a wrap of 'uname -m'."""
251 return os.popen('uname -m').read().rstrip()
mblighcdf02a42006-04-23 02:22:49 +0000252
253
mblighfdbcaec2006-10-01 23:28:57 +0000254def get_file_arch(filename):
255 # -L means follow symlinks
256 file_data = system_output('file -L ' + filename)
257 if file_data.count('80386'):
258 return 'i386'
259 return None
260
261
mbligh548f29a2006-10-17 04:55:12 +0000262def kernelexpand(kernel, args=None):
mblighf4c35322006-03-13 01:01:10 +0000263 # if not (kernel.startswith('http://') or kernel.startswith('ftp://') or os.path.isfile(kernel)):
mbligh5629af02006-09-15 01:54:23 +0000264 if kernel.find('/') < 0: # contains no path.
mbligh534015f2006-09-15 03:28:56 +0000265 autodir = os.environ['AUTODIR']
266 kernelexpand = os.path.join(autodir, 'tools/kernelexpand')
mbligh548f29a2006-10-17 04:55:12 +0000267 if args:
268 kernelexpand += ' ' + args
mbligh5629af02006-09-15 01:54:23 +0000269 w, r = os.popen2(kernelexpand + ' ' + kernel)
mblighf4c35322006-03-13 01:01:10 +0000270
271 kernel = r.readline().strip()
272 r.close()
273 w.close()
mbligh534015f2006-09-15 03:28:56 +0000274 return kernel.split()
mblighf4c35322006-03-13 01:01:10 +0000275
276
277def count_cpus():
mblighc86b0b42006-07-28 17:35:28 +0000278 """number of CPUs in the local machine according to /proc/cpuinfo"""
mblighf4c35322006-03-13 01:01:10 +0000279 f = file('/proc/cpuinfo', 'r')
280 cpus = 0
281 for line in f.readlines():
282 if line.startswith('processor'):
283 cpus += 1
284 return cpus
285
mblighe7a170f2006-12-05 07:48:18 +0000286
287# Returns total memory in kb
288def memtotal():
289 memtotal = system_output('grep MemTotal /proc/meminfo')
290 return int(re.search(r'\d+', memtotal).group(0))
291
292
mbligha975fb62006-04-22 19:56:25 +0000293def system(cmd, ignorestatus = 0):
mblighc86b0b42006-07-28 17:35:28 +0000294 """os.system replacement
295
296 We have our own definition of system here, as the stock os.system doesn't
297 correctly handle sigpipe
298 (ie things like "yes | head" will hang because yes doesn't get the SIGPIPE).
299
300 Also the stock os.system didn't raise errors based on exit status, this
301 version does unless you explicitly specify ignorestatus=1
302 """
mblighf4c35322006-03-13 01:01:10 +0000303 signal.signal(signal.SIGPIPE, signal.SIG_DFL)
304 try:
apwbc2867d2006-04-06 18:21:16 +0000305 status = os.system(cmd)
mblighf4c35322006-03-13 01:01:10 +0000306 finally:
307 signal.signal(signal.SIGPIPE, signal.SIG_IGN)
mbligha975fb62006-04-22 19:56:25 +0000308
mbligh67b5ece2006-04-23 02:53:12 +0000309 if ((status != 0) and not ignorestatus):
apwbc2867d2006-04-06 18:21:16 +0000310 raise CmdError(cmd, status)
mbligha975fb62006-04-22 19:56:25 +0000311 return status
mbligh3d914912006-04-22 17:37:19 +0000312
313
mbligh67b5ece2006-04-23 02:53:12 +0000314def system_output(command, ignorestatus = 0):
mblighc86b0b42006-07-28 17:35:28 +0000315 """Run command and return its output
316
317 ignorestatus
318 whether to raise a CmdError if command has a nonzero exit status
319 """
mbligh67b5ece2006-04-23 02:53:12 +0000320 (result, data) = commands.getstatusoutput(command)
321 if ((result != 0) and not ignorestatus):
322 raise CmdError, 'command failed: ' + command
323 return data
324
325
mblighf4c35322006-03-13 01:01:10 +0000326def where_art_thy_filehandles():
mblighc86b0b42006-07-28 17:35:28 +0000327 """Dump the current list of filehandles"""
mblighf4c35322006-03-13 01:01:10 +0000328 os.system("ls -l /proc/%d/fd >> /dev/tty" % os.getpid())
329
330
331def print_to_tty(string):
mblighc86b0b42006-07-28 17:35:28 +0000332 """Output string straight to the tty"""
mblighf4c35322006-03-13 01:01:10 +0000333 os.system("echo " + string + " >> /dev/tty")
334
335
mblighb8a14e32006-05-06 00:17:35 +0000336def dump_object(object):
mblighc86b0b42006-07-28 17:35:28 +0000337 """Dump an object's attributes and methods
338
339 kind of like dir()
340 """
mblighb8a14e32006-05-06 00:17:35 +0000341 for item in object.__dict__.iteritems():
342 print item
343 try:
344 (key,value) = item
345 dump_object(value)
346 except:
347 continue
348
349
mbligh4b089662006-06-14 22:34:58 +0000350def environ(env_key):
mblighc86b0b42006-07-28 17:35:28 +0000351 """return the requested environment variable, or '' if unset"""
mbligh4b089662006-06-14 22:34:58 +0000352 if (os.environ.has_key(env_key)):
mblighd931a582006-10-01 00:30:12 +0000353 return os.environ[env_key]
mbligh4b089662006-06-14 22:34:58 +0000354 else:
355 return ''
356
357
358def prepend_path(newpath, oldpath):
mblighc86b0b42006-07-28 17:35:28 +0000359 """prepend newpath to oldpath"""
mbligh4b089662006-06-14 22:34:58 +0000360 if (oldpath):
361 return newpath + ':' + oldpath
362 else:
363 return newpath
364
365
366def append_path(oldpath, newpath):
mblighc86b0b42006-07-28 17:35:28 +0000367 """append newpath to oldpath"""
mbligh4b089662006-06-14 22:34:58 +0000368 if (oldpath):
369 return oldpath + ':' + newpath
370 else:
371 return newpath
372
373
mbligh4e75b0d2006-08-29 15:22:44 +0000374def avgtime_print(dir):
375 """ Calculate some benchmarking statistics.
376 Input is a directory containing a file called 'time'.
377 File contains one-per-line results of /usr/bin/time.
378 Output is average Elapsed, User, and System time in seconds,
379 and average CPU percentage.
380 """
381 f = open(dir + "/time")
382 user = system = elapsed = cpu = count = 0
383 r = re.compile('([\d\.]*)user ([\d\.]*)system (\d*):([\d\.]*)elapsed (\d*)%CPU')
384 for line in f.readlines():
385 try:
386 s = r.match(line);
mblighe1ee2672006-08-29 16:27:15 +0000387 user += float(s.group(1))
388 system += float(s.group(2))
389 elapsed += (float(s.group(3)) * 60) + float(s.group(4))
390 cpu += float(s.group(5))
mbligh4e75b0d2006-08-29 15:22:44 +0000391 count += 1
392 except:
393 raise ValueError("badly formatted times")
394
395 f.close()
396 return "Elapsed: %0.2fs User: %0.2fs System: %0.2fs CPU: %0.0f%%" % \
397 (elapsed/count, user/count, system/count, cpu/count)
398
399
mblighf06db0f2006-09-30 17:08:43 +0000400def running_config():
401 """
402 Return path of config file of the currently running kernel
403 """
404 for config in ('/proc/config.gz', \
405 '/boot/config-%s' % system_output('uname -r') ):
406 if os.path.isfile(config):
407 return config
408 return None
mbligh9ec8acc2006-10-05 06:52:33 +0000409
410
411def cpu_online_map():
412 """
413 Check out the available cpu online map
414 """
415 cpus = []
416 for line in open('/proc/cpuinfo', 'r').readlines():
417 if line.startswith('processor'):
418 cpus.append(line.split()[2]) # grab cpu number
419 return cpus
mbligh663e4f62006-10-11 05:03:40 +0000420
421
422def check_glibc_ver(ver):
423 glibc_ver = commands.getoutput('ldd --version').splitlines()[0]
mblighcabfdaf2006-10-11 14:07:48 +0000424 glibc_ver = re.search(r'(\d+\.\d+(\.\d+)?)', glibc_ver).group()
mblighea97ab82006-10-13 20:18:01 +0000425 if glibc_ver.split('.') < ver.split('.'):
426 raise "Glibc is too old (%s). Glibc >= %s is needed." % \
427 (glibc_ver, ver)
mbligh9061a272006-12-28 21:20:51 +0000428
429def read_one_line(filename):
430 return open(filename, 'r').readline().strip()
431
432
433def write_one_line(filename, str):
434 str.rstrip()
435 open(filename, 'w').write(str.rstrip() + "\n")
mbligh264cd8f2007-02-02 23:57:43 +0000436
437
438def human_format(number):
439 # Convert number to kilo / mega / giga format.
440 if number < 1024:
441 return "%d" % number
442 kilo = float(number) / 1024.0
443 if kilo < 1024:
444 return "%.2fk" % kilo
445 meg = kilo / 1024.0
446 if meg < 1024:
447 return "%.2fM" % meg
448 gig = meg / 1024.0
449 return "%.2fG" % gig
450
mbligh8eca3a92007-02-03 20:59:39 +0000451
452def numa_nodes():
453 node_paths = glob.glob('/sys/devices/system/node/node*')
454 nodes = [int(re.sub(r'.*node(\d+)', r'\1', x)) for x in node_paths]
455 return (sorted(nodes))
456
457
458def node_size():
459 nodes = max(len(numa_nodes()), 1)
460 return ((memtotal() * 1024) / nodes)
461