blob: 2d4dd438c005a0ffeaa6997f6d7047721426bcc9 [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
mblighc69530b2007-03-25 20:20:21 +000071def update_version(srcdir, preserve_srcdir, new_version, install, *args, **dargs):
72 """
73 Make sure srcdir is version new_version
mblighc86b0b42006-07-28 17:35:28 +000074
mblighc69530b2007-03-25 20:20:21 +000075 If not, delete it and install() the new version.
76
77 In the preserve_srcdir case, we just check it's up to date,
78 and if not, we rerun install, without removing srcdir
mblighc86b0b42006-07-28 17:35:28 +000079 """
mbligh72905562006-05-25 01:30:49 +000080 versionfile = srcdir + '/.version'
mblighc69530b2007-03-25 20:20:21 +000081 install_needed = True
82
mblighff88e4e2006-05-25 19:34:52 +000083 if os.path.exists(srcdir):
84 if os.path.exists(versionfile):
85 old_version = pickle.load(open(versionfile, 'r'))
mblighc69530b2007-03-25 20:20:21 +000086 if (old_version == new_version):
87 install_needed = False
88
89 if install_needed:
90 if not preserve_srcdir:
mbligh72905562006-05-25 01:30:49 +000091 system('rm -rf ' + srcdir)
mbligh78e17022006-09-13 19:58:12 +000092 install(*args, **dargs)
mbligh72905562006-05-25 01:30:49 +000093 if os.path.exists(srcdir):
94 pickle.dump(new_version, open(versionfile, 'w'))
mblighdfe8cc62007-07-23 18:23:17 +000095
mbligh72905562006-05-25 01:30:49 +000096
mblighea30c8a2006-04-22 22:24:25 +000097def is_url(path):
mblighc86b0b42006-07-28 17:35:28 +000098 """true if path is a url
99 """
100 # should cope with other url types here, but we only handle http and ftp
mblighea30c8a2006-04-22 22:24:25 +0000101 if (path.startswith('http://')) or (path.startswith('ftp://')):
mblighea30c8a2006-04-22 22:24:25 +0000102 return 1
103 return 0
104
mblighcdf02a42006-04-23 02:22:49 +0000105
mbligh8eca3a92007-02-03 20:59:39 +0000106def get_file(src, dest, permissions = None):
mblighc86b0b42006-07-28 17:35:28 +0000107 """get a file, either from url or local"""
mbligh31186612006-04-22 21:55:56 +0000108 if (src == dest): # no-op here allows clean overrides in tests
109 return
mblighea30c8a2006-04-22 22:24:25 +0000110 if (is_url(src)):
mblighf4c35322006-03-13 01:01:10 +0000111 print 'PWD: ' + os.getcwd()
112 print 'Fetching \n\t', src, '\n\t->', dest
113 try:
114 urllib.urlretrieve(src, dest)
115 except IOError:
116 sys.stderr.write("Unable to retrieve %s (to %s)\n" % (src, dest))
117 sys.exit(1)
mbligh8eca3a92007-02-03 20:59:39 +0000118 else:
119 shutil.copyfile(src, dest)
120 if permissions:
121 os.chmod(permissions)
mblighf4c35322006-03-13 01:01:10 +0000122 return dest
123
mblighea30c8a2006-04-22 22:24:25 +0000124
mbligh82641862006-04-23 06:21:36 +0000125def unmap_url(srcdir, src, destdir = '.'):
mbligh52508632006-09-30 18:29:55 +0000126 """
127 Receives either a path to a local file or a URL.
128 returns either the path to the local file, or the fetched URL
129
130 unmap_url('/usr/src', 'foo.tar', '/tmp')
131 = '/usr/src/foo.tar'
132 unmap_url('/usr/src', 'http://site/file', '/tmp')
133 = '/tmp/file'
134 (after retrieving it)
135 """
mblighea30c8a2006-04-22 22:24:25 +0000136 if is_url(src):
137 dest = destdir + '/' + os.path.basename(src)
138 get_file(src, dest)
139 return dest
mbligh82641862006-04-23 06:21:36 +0000140 else:
141 return srcdir + '/' + src
mblighea30c8a2006-04-22 22:24:25 +0000142
143
mblighf4c35322006-03-13 01:01:10 +0000144def basename(path):
145 i = path.rfind('/');
146 return path[i+1:]
147
148
149def force_copy(src, dest):
mblighc86b0b42006-07-28 17:35:28 +0000150 """Replace dest with a new copy of src, even if it exists"""
mblighf4c35322006-03-13 01:01:10 +0000151 if os.path.isfile(dest):
152 os.remove(dest)
mbligh1e8858e2006-11-24 22:18:35 +0000153 if os.path.isdir(dest):
154 dest = os.path.join(dest, os.path.basename(src))
mblighf4c35322006-03-13 01:01:10 +0000155 return shutil.copyfile(src, dest)
156
157
mblighfdbcaec2006-10-01 23:28:57 +0000158def force_link(src, dest):
159 """Link src to dest, overwriting it if it exists"""
160 return system("ln -sf %s %s" % (src, dest))
161
162
mblighcdf02a42006-04-23 02:22:49 +0000163def file_contains_pattern(file, pattern):
mblighc86b0b42006-07-28 17:35:28 +0000164 """Return true if file contains the specified egrep pattern"""
mblighcdf02a42006-04-23 02:22:49 +0000165 if not os.path.isfile(file):
166 raise NameError, 'file %s does not exist' % file
mbligh5c1e26a2006-10-04 14:46:33 +0000167 return not system('egrep -q "' + pattern + '" ' + file, ignorestatus = 1)
mblighcdf02a42006-04-23 02:22:49 +0000168
169
170def list_grep(list, pattern):
mblighc86b0b42006-07-28 17:35:28 +0000171 """True if any item in list matches the specified pattern."""
mblighcdf02a42006-04-23 02:22:49 +0000172 compiled = re.compile(pattern)
173 for line in list:
174 match = compiled.search(line)
175 if (match):
176 return 1
177 return 0
178
mbligh42b81ca2006-09-30 22:10:01 +0000179def get_os_vendor():
180 """Try to guess what's the os vendor
181 """
182 issue = '/etc/issue'
183
184 if not os.path.isfile(issue):
185 return 'Unknown'
186
187 if file_contains_pattern(issue, 'Red Hat'):
188 return 'Red Hat'
189 elif file_contains_pattern(issue, 'Fedora Core'):
190 return 'Fedora Core'
191 elif file_contains_pattern(issue, 'SUSE'):
192 return 'SUSE'
193 elif file_contains_pattern(issue, 'Ubuntu'):
194 return 'Ubuntu'
apw39f9cac2007-02-28 15:26:05 +0000195 elif file_contains_pattern(issue, 'Debian'):
196 return 'Debian'
mbligh42b81ca2006-09-30 22:10:01 +0000197 else:
198 return 'Unknown'
199
mblighcdf02a42006-04-23 02:22:49 +0000200
mblighf49d5cf2006-04-23 02:24:42 +0000201def get_vmlinux():
mblighc86b0b42006-07-28 17:35:28 +0000202 """Return the full path to vmlinux
203
204 Ahem. This is crap. Pray harder. Bad Martin.
205 """
mblighad849ee2006-10-02 17:53:18 +0000206 vmlinux = '/boot/vmlinux-%s' % system_output('uname -r')
mbligh662a2a22006-10-01 17:01:14 +0000207 if os.path.isfile(vmlinux):
208 return vmlinux
mbligh17dbf052006-10-12 04:46:10 +0000209 vmlinux = '/lib/modules/%s/build/vmlinux' % system_output('uname -r')
210 if os.path.isfile(vmlinux):
211 return vmlinux
mbligh662a2a22006-10-01 17:01:14 +0000212 return None
mblighf49d5cf2006-04-23 02:24:42 +0000213
214
215def get_systemmap():
mblighc86b0b42006-07-28 17:35:28 +0000216 """Return the full path to System.map
217
218 Ahem. This is crap. Pray harder. Bad Martin.
219 """
mblighad849ee2006-10-02 17:53:18 +0000220 map = '/boot/System.map-%s' % system_output('uname -r')
mbligh662a2a22006-10-01 17:01:14 +0000221 if os.path.isfile(map):
222 return map
mbligh17dbf052006-10-12 04:46:10 +0000223 map = '/lib/modules/%s/build/System.map' % system_output('uname -r')
224 if os.path.isfile(map):
225 return map
mbligh662a2a22006-10-01 17:01:14 +0000226 return None
mbligh67b5ece2006-04-23 02:53:12 +0000227
228
229def get_modules_dir():
mblighc86b0b42006-07-28 17:35:28 +0000230 """Return the modules dir for the running kernel version"""
mbligh67b5ece2006-04-23 02:53:12 +0000231 kernel_version = system_output('uname -r')
232 return '/lib/modules/%s/kernel' % kernel_version
mblighf49d5cf2006-04-23 02:24:42 +0000233
234
mbligh5970cf02006-08-06 15:39:22 +0000235def get_cpu_arch():
mblighc86b0b42006-07-28 17:35:28 +0000236 """Work out which CPU architecture we're running on"""
mblighcdf02a42006-04-23 02:22:49 +0000237 f = open('/proc/cpuinfo', 'r')
238 cpuinfo = f.readlines()
239 f.close()
240 if list_grep(cpuinfo, '^cpu.*(RS64|POWER3|Broadband Engine)'):
241 return 'power'
242 elif list_grep(cpuinfo, '^cpu.*POWER4'):
243 return 'power4'
244 elif list_grep(cpuinfo, '^cpu.*POWER5'):
245 return 'power5'
246 elif list_grep(cpuinfo, '^cpu.*POWER6'):
247 return 'power6'
248 elif list_grep(cpuinfo, '^cpu.*PPC970'):
249 return 'power970'
250 elif list_grep(cpuinfo, 'Opteron'):
251 return 'x86_64'
252 elif list_grep(cpuinfo, 'GenuineIntel') and list_grep(cpuinfo, '48 bits virtual'):
mblighf4c35322006-03-13 01:01:10 +0000253 return 'x86_64'
254 else:
255 return 'i386'
256
257
mbligh548f29a2006-10-17 04:55:12 +0000258def get_current_kernel_arch():
259 """Get the machine architecture, now just a wrap of 'uname -m'."""
260 return os.popen('uname -m').read().rstrip()
mblighcdf02a42006-04-23 02:22:49 +0000261
262
mblighfdbcaec2006-10-01 23:28:57 +0000263def get_file_arch(filename):
264 # -L means follow symlinks
265 file_data = system_output('file -L ' + filename)
266 if file_data.count('80386'):
267 return 'i386'
268 return None
269
270
mbligh548f29a2006-10-17 04:55:12 +0000271def kernelexpand(kernel, args=None):
mblighf4c35322006-03-13 01:01:10 +0000272 # if not (kernel.startswith('http://') or kernel.startswith('ftp://') or os.path.isfile(kernel)):
mbligh5629af02006-09-15 01:54:23 +0000273 if kernel.find('/') < 0: # contains no path.
mbligh534015f2006-09-15 03:28:56 +0000274 autodir = os.environ['AUTODIR']
275 kernelexpand = os.path.join(autodir, 'tools/kernelexpand')
mbligh548f29a2006-10-17 04:55:12 +0000276 if args:
277 kernelexpand += ' ' + args
mbligh5629af02006-09-15 01:54:23 +0000278 w, r = os.popen2(kernelexpand + ' ' + kernel)
mblighf4c35322006-03-13 01:01:10 +0000279
280 kernel = r.readline().strip()
281 r.close()
282 w.close()
mbligh534015f2006-09-15 03:28:56 +0000283 return kernel.split()
mblighf4c35322006-03-13 01:01:10 +0000284
285
286def count_cpus():
mblighc86b0b42006-07-28 17:35:28 +0000287 """number of CPUs in the local machine according to /proc/cpuinfo"""
mblighf4c35322006-03-13 01:01:10 +0000288 f = file('/proc/cpuinfo', 'r')
289 cpus = 0
290 for line in f.readlines():
291 if line.startswith('processor'):
292 cpus += 1
293 return cpus
294
mblighe7a170f2006-12-05 07:48:18 +0000295
296# Returns total memory in kb
297def memtotal():
298 memtotal = system_output('grep MemTotal /proc/meminfo')
299 return int(re.search(r'\d+', memtotal).group(0))
300
301
mbligha975fb62006-04-22 19:56:25 +0000302def system(cmd, ignorestatus = 0):
mblighc86b0b42006-07-28 17:35:28 +0000303 """os.system replacement
304
305 We have our own definition of system here, as the stock os.system doesn't
306 correctly handle sigpipe
307 (ie things like "yes | head" will hang because yes doesn't get the SIGPIPE).
308
309 Also the stock os.system didn't raise errors based on exit status, this
310 version does unless you explicitly specify ignorestatus=1
311 """
mblighf4c35322006-03-13 01:01:10 +0000312 signal.signal(signal.SIGPIPE, signal.SIG_DFL)
313 try:
apwbc2867d2006-04-06 18:21:16 +0000314 status = os.system(cmd)
mblighf4c35322006-03-13 01:01:10 +0000315 finally:
316 signal.signal(signal.SIGPIPE, signal.SIG_IGN)
mbligha975fb62006-04-22 19:56:25 +0000317
mbligh67b5ece2006-04-23 02:53:12 +0000318 if ((status != 0) and not ignorestatus):
apwbc2867d2006-04-06 18:21:16 +0000319 raise CmdError(cmd, status)
mbligha975fb62006-04-22 19:56:25 +0000320 return status
mbligh3d914912006-04-22 17:37:19 +0000321
322
mbligh67b5ece2006-04-23 02:53:12 +0000323def system_output(command, ignorestatus = 0):
mblighc86b0b42006-07-28 17:35:28 +0000324 """Run command and return its output
325
326 ignorestatus
327 whether to raise a CmdError if command has a nonzero exit status
328 """
mbligh67b5ece2006-04-23 02:53:12 +0000329 (result, data) = commands.getstatusoutput(command)
330 if ((result != 0) and not ignorestatus):
331 raise CmdError, 'command failed: ' + command
332 return data
333
334
mblighf4c35322006-03-13 01:01:10 +0000335def where_art_thy_filehandles():
mblighc86b0b42006-07-28 17:35:28 +0000336 """Dump the current list of filehandles"""
mblighf4c35322006-03-13 01:01:10 +0000337 os.system("ls -l /proc/%d/fd >> /dev/tty" % os.getpid())
338
339
340def print_to_tty(string):
mblighc86b0b42006-07-28 17:35:28 +0000341 """Output string straight to the tty"""
mblighe80ff5a2007-02-26 02:37:30 +0000342 open('/dev/tty', 'w').write(string + '\n')
mblighf4c35322006-03-13 01:01:10 +0000343
344
mblighb8a14e32006-05-06 00:17:35 +0000345def dump_object(object):
mblighc86b0b42006-07-28 17:35:28 +0000346 """Dump an object's attributes and methods
347
348 kind of like dir()
349 """
mblighb8a14e32006-05-06 00:17:35 +0000350 for item in object.__dict__.iteritems():
351 print item
352 try:
353 (key,value) = item
354 dump_object(value)
355 except:
356 continue
357
358
mbligh4b089662006-06-14 22:34:58 +0000359def environ(env_key):
mblighc86b0b42006-07-28 17:35:28 +0000360 """return the requested environment variable, or '' if unset"""
mbligh4b089662006-06-14 22:34:58 +0000361 if (os.environ.has_key(env_key)):
mblighd931a582006-10-01 00:30:12 +0000362 return os.environ[env_key]
mbligh4b089662006-06-14 22:34:58 +0000363 else:
364 return ''
365
366
367def prepend_path(newpath, oldpath):
mblighc86b0b42006-07-28 17:35:28 +0000368 """prepend newpath to oldpath"""
mbligh4b089662006-06-14 22:34:58 +0000369 if (oldpath):
370 return newpath + ':' + oldpath
371 else:
372 return newpath
373
374
375def append_path(oldpath, newpath):
mblighc86b0b42006-07-28 17:35:28 +0000376 """append newpath to oldpath"""
mbligh4b089662006-06-14 22:34:58 +0000377 if (oldpath):
378 return oldpath + ':' + newpath
379 else:
380 return newpath
381
382
mbligh4e75b0d2006-08-29 15:22:44 +0000383def avgtime_print(dir):
384 """ Calculate some benchmarking statistics.
385 Input is a directory containing a file called 'time'.
386 File contains one-per-line results of /usr/bin/time.
387 Output is average Elapsed, User, and System time in seconds,
388 and average CPU percentage.
389 """
390 f = open(dir + "/time")
391 user = system = elapsed = cpu = count = 0
392 r = re.compile('([\d\.]*)user ([\d\.]*)system (\d*):([\d\.]*)elapsed (\d*)%CPU')
393 for line in f.readlines():
394 try:
395 s = r.match(line);
mblighe1ee2672006-08-29 16:27:15 +0000396 user += float(s.group(1))
397 system += float(s.group(2))
398 elapsed += (float(s.group(3)) * 60) + float(s.group(4))
399 cpu += float(s.group(5))
mbligh4e75b0d2006-08-29 15:22:44 +0000400 count += 1
401 except:
402 raise ValueError("badly formatted times")
403
404 f.close()
405 return "Elapsed: %0.2fs User: %0.2fs System: %0.2fs CPU: %0.0f%%" % \
406 (elapsed/count, user/count, system/count, cpu/count)
407
408
mblighf06db0f2006-09-30 17:08:43 +0000409def running_config():
410 """
411 Return path of config file of the currently running kernel
412 """
mbligha1bef1f2007-04-03 17:18:07 +0000413 version = system_output('uname -r')
mblighf06db0f2006-09-30 17:08:43 +0000414 for config in ('/proc/config.gz', \
mbligha1bef1f2007-04-03 17:18:07 +0000415 '/boot/config-%s' % version,
416 '/lib/modules/%s/build/.config' % version):
mblighf06db0f2006-09-30 17:08:43 +0000417 if os.path.isfile(config):
418 return config
419 return None
mbligh9ec8acc2006-10-05 06:52:33 +0000420
421
mbligha1bef1f2007-04-03 17:18:07 +0000422def check_for_kernel_feature(feature):
423 config = running_config()
424
425 if not config:
426 raise "Can't find kernel config file"
427
428 if config.endswith('.gz'):
429 grep = 'zgrep'
430 else:
431 grep = 'grep'
432 grep += ' ^CONFIG_%s= %s' % (feature, config)
433
434 if not system_output(grep, ignorestatus = 1):
435 raise "Kernel doesn't have a %s feature" % (feature)
436
437
mbligh9ec8acc2006-10-05 06:52:33 +0000438def cpu_online_map():
439 """
440 Check out the available cpu online map
441 """
442 cpus = []
443 for line in open('/proc/cpuinfo', 'r').readlines():
444 if line.startswith('processor'):
445 cpus.append(line.split()[2]) # grab cpu number
446 return cpus
mbligh663e4f62006-10-11 05:03:40 +0000447
448
449def check_glibc_ver(ver):
450 glibc_ver = commands.getoutput('ldd --version').splitlines()[0]
mblighcabfdaf2006-10-11 14:07:48 +0000451 glibc_ver = re.search(r'(\d+\.\d+(\.\d+)?)', glibc_ver).group()
mblighea97ab82006-10-13 20:18:01 +0000452 if glibc_ver.split('.') < ver.split('.'):
mbligh07635222007-07-09 21:29:00 +0000453 raise TestError("Glibc is too old (%s). Glibc >= %s is needed." % \
454 (glibc_ver, ver))
455
456def check_kernel_ver(ver):
457 kernel_ver = system_output('uname -r')
458 kv_tmp = re.split(r'[-]', kernel_ver)[0:3]
459 if kv_tmp[0].split('.') < ver.split('.'):
460 raise TestError("Kernel is too old (%s). Kernel > %s is needed." % \
461 (kernel_ver, ver))
462
mbligh9061a272006-12-28 21:20:51 +0000463
464def read_one_line(filename):
465 return open(filename, 'r').readline().strip()
466
467
468def write_one_line(filename, str):
469 str.rstrip()
470 open(filename, 'w').write(str.rstrip() + "\n")
mbligh264cd8f2007-02-02 23:57:43 +0000471
472
473def human_format(number):
474 # Convert number to kilo / mega / giga format.
475 if number < 1024:
476 return "%d" % number
477 kilo = float(number) / 1024.0
478 if kilo < 1024:
479 return "%.2fk" % kilo
480 meg = kilo / 1024.0
481 if meg < 1024:
482 return "%.2fM" % meg
483 gig = meg / 1024.0
484 return "%.2fG" % gig
485
mbligh8eca3a92007-02-03 20:59:39 +0000486
487def numa_nodes():
488 node_paths = glob.glob('/sys/devices/system/node/node*')
489 nodes = [int(re.sub(r'.*node(\d+)', r'\1', x)) for x in node_paths]
490 return (sorted(nodes))
491
492
493def node_size():
494 nodes = max(len(numa_nodes()), 1)
495 return ((memtotal() * 1024) / nodes)
496