blob: 1d480f68053578e208a0906114a05cc054eff5fb [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'
apw39f9cac2007-02-28 15:26:05 +0000188 elif file_contains_pattern(issue, 'Debian'):
189 return 'Debian'
mbligh42b81ca2006-09-30 22:10:01 +0000190 else:
191 return 'Unknown'
192
mblighcdf02a42006-04-23 02:22:49 +0000193
mblighf49d5cf2006-04-23 02:24:42 +0000194def get_vmlinux():
mblighc86b0b42006-07-28 17:35:28 +0000195 """Return the full path to vmlinux
196
197 Ahem. This is crap. Pray harder. Bad Martin.
198 """
mblighad849ee2006-10-02 17:53:18 +0000199 vmlinux = '/boot/vmlinux-%s' % system_output('uname -r')
mbligh662a2a22006-10-01 17:01:14 +0000200 if os.path.isfile(vmlinux):
201 return vmlinux
mbligh17dbf052006-10-12 04:46:10 +0000202 vmlinux = '/lib/modules/%s/build/vmlinux' % system_output('uname -r')
203 if os.path.isfile(vmlinux):
204 return vmlinux
mbligh662a2a22006-10-01 17:01:14 +0000205 return None
mblighf49d5cf2006-04-23 02:24:42 +0000206
207
208def get_systemmap():
mblighc86b0b42006-07-28 17:35:28 +0000209 """Return the full path to System.map
210
211 Ahem. This is crap. Pray harder. Bad Martin.
212 """
mblighad849ee2006-10-02 17:53:18 +0000213 map = '/boot/System.map-%s' % system_output('uname -r')
mbligh662a2a22006-10-01 17:01:14 +0000214 if os.path.isfile(map):
215 return map
mbligh17dbf052006-10-12 04:46:10 +0000216 map = '/lib/modules/%s/build/System.map' % system_output('uname -r')
217 if os.path.isfile(map):
218 return map
mbligh662a2a22006-10-01 17:01:14 +0000219 return None
mbligh67b5ece2006-04-23 02:53:12 +0000220
221
222def get_modules_dir():
mblighc86b0b42006-07-28 17:35:28 +0000223 """Return the modules dir for the running kernel version"""
mbligh67b5ece2006-04-23 02:53:12 +0000224 kernel_version = system_output('uname -r')
225 return '/lib/modules/%s/kernel' % kernel_version
mblighf49d5cf2006-04-23 02:24:42 +0000226
227
mbligh5970cf02006-08-06 15:39:22 +0000228def get_cpu_arch():
mblighc86b0b42006-07-28 17:35:28 +0000229 """Work out which CPU architecture we're running on"""
mblighcdf02a42006-04-23 02:22:49 +0000230 f = open('/proc/cpuinfo', 'r')
231 cpuinfo = f.readlines()
232 f.close()
233 if list_grep(cpuinfo, '^cpu.*(RS64|POWER3|Broadband Engine)'):
234 return 'power'
235 elif list_grep(cpuinfo, '^cpu.*POWER4'):
236 return 'power4'
237 elif list_grep(cpuinfo, '^cpu.*POWER5'):
238 return 'power5'
239 elif list_grep(cpuinfo, '^cpu.*POWER6'):
240 return 'power6'
241 elif list_grep(cpuinfo, '^cpu.*PPC970'):
242 return 'power970'
243 elif list_grep(cpuinfo, 'Opteron'):
244 return 'x86_64'
245 elif list_grep(cpuinfo, 'GenuineIntel') and list_grep(cpuinfo, '48 bits virtual'):
mblighf4c35322006-03-13 01:01:10 +0000246 return 'x86_64'
247 else:
248 return 'i386'
249
250
mbligh548f29a2006-10-17 04:55:12 +0000251def get_current_kernel_arch():
252 """Get the machine architecture, now just a wrap of 'uname -m'."""
253 return os.popen('uname -m').read().rstrip()
mblighcdf02a42006-04-23 02:22:49 +0000254
255
mblighfdbcaec2006-10-01 23:28:57 +0000256def get_file_arch(filename):
257 # -L means follow symlinks
258 file_data = system_output('file -L ' + filename)
259 if file_data.count('80386'):
260 return 'i386'
261 return None
262
263
mbligh548f29a2006-10-17 04:55:12 +0000264def kernelexpand(kernel, args=None):
mblighf4c35322006-03-13 01:01:10 +0000265 # if not (kernel.startswith('http://') or kernel.startswith('ftp://') or os.path.isfile(kernel)):
mbligh5629af02006-09-15 01:54:23 +0000266 if kernel.find('/') < 0: # contains no path.
mbligh534015f2006-09-15 03:28:56 +0000267 autodir = os.environ['AUTODIR']
268 kernelexpand = os.path.join(autodir, 'tools/kernelexpand')
mbligh548f29a2006-10-17 04:55:12 +0000269 if args:
270 kernelexpand += ' ' + args
mbligh5629af02006-09-15 01:54:23 +0000271 w, r = os.popen2(kernelexpand + ' ' + kernel)
mblighf4c35322006-03-13 01:01:10 +0000272
273 kernel = r.readline().strip()
274 r.close()
275 w.close()
mbligh534015f2006-09-15 03:28:56 +0000276 return kernel.split()
mblighf4c35322006-03-13 01:01:10 +0000277
278
279def count_cpus():
mblighc86b0b42006-07-28 17:35:28 +0000280 """number of CPUs in the local machine according to /proc/cpuinfo"""
mblighf4c35322006-03-13 01:01:10 +0000281 f = file('/proc/cpuinfo', 'r')
282 cpus = 0
283 for line in f.readlines():
284 if line.startswith('processor'):
285 cpus += 1
286 return cpus
287
mblighe7a170f2006-12-05 07:48:18 +0000288
289# Returns total memory in kb
290def memtotal():
291 memtotal = system_output('grep MemTotal /proc/meminfo')
292 return int(re.search(r'\d+', memtotal).group(0))
293
294
mbligha975fb62006-04-22 19:56:25 +0000295def system(cmd, ignorestatus = 0):
mblighc86b0b42006-07-28 17:35:28 +0000296 """os.system replacement
297
298 We have our own definition of system here, as the stock os.system doesn't
299 correctly handle sigpipe
300 (ie things like "yes | head" will hang because yes doesn't get the SIGPIPE).
301
302 Also the stock os.system didn't raise errors based on exit status, this
303 version does unless you explicitly specify ignorestatus=1
304 """
mblighf4c35322006-03-13 01:01:10 +0000305 signal.signal(signal.SIGPIPE, signal.SIG_DFL)
306 try:
apwbc2867d2006-04-06 18:21:16 +0000307 status = os.system(cmd)
mblighf4c35322006-03-13 01:01:10 +0000308 finally:
309 signal.signal(signal.SIGPIPE, signal.SIG_IGN)
mbligha975fb62006-04-22 19:56:25 +0000310
mbligh67b5ece2006-04-23 02:53:12 +0000311 if ((status != 0) and not ignorestatus):
apwbc2867d2006-04-06 18:21:16 +0000312 raise CmdError(cmd, status)
mbligha975fb62006-04-22 19:56:25 +0000313 return status
mbligh3d914912006-04-22 17:37:19 +0000314
315
mbligh67b5ece2006-04-23 02:53:12 +0000316def system_output(command, ignorestatus = 0):
mblighc86b0b42006-07-28 17:35:28 +0000317 """Run command and return its output
318
319 ignorestatus
320 whether to raise a CmdError if command has a nonzero exit status
321 """
mbligh67b5ece2006-04-23 02:53:12 +0000322 (result, data) = commands.getstatusoutput(command)
323 if ((result != 0) and not ignorestatus):
324 raise CmdError, 'command failed: ' + command
325 return data
326
327
mblighf4c35322006-03-13 01:01:10 +0000328def where_art_thy_filehandles():
mblighc86b0b42006-07-28 17:35:28 +0000329 """Dump the current list of filehandles"""
mblighf4c35322006-03-13 01:01:10 +0000330 os.system("ls -l /proc/%d/fd >> /dev/tty" % os.getpid())
331
332
333def print_to_tty(string):
mblighc86b0b42006-07-28 17:35:28 +0000334 """Output string straight to the tty"""
mblighe80ff5a2007-02-26 02:37:30 +0000335 open('/dev/tty', 'w').write(string + '\n')
mblighf4c35322006-03-13 01:01:10 +0000336
337
mblighb8a14e32006-05-06 00:17:35 +0000338def dump_object(object):
mblighc86b0b42006-07-28 17:35:28 +0000339 """Dump an object's attributes and methods
340
341 kind of like dir()
342 """
mblighb8a14e32006-05-06 00:17:35 +0000343 for item in object.__dict__.iteritems():
344 print item
345 try:
346 (key,value) = item
347 dump_object(value)
348 except:
349 continue
350
351
mbligh4b089662006-06-14 22:34:58 +0000352def environ(env_key):
mblighc86b0b42006-07-28 17:35:28 +0000353 """return the requested environment variable, or '' if unset"""
mbligh4b089662006-06-14 22:34:58 +0000354 if (os.environ.has_key(env_key)):
mblighd931a582006-10-01 00:30:12 +0000355 return os.environ[env_key]
mbligh4b089662006-06-14 22:34:58 +0000356 else:
357 return ''
358
359
360def prepend_path(newpath, oldpath):
mblighc86b0b42006-07-28 17:35:28 +0000361 """prepend newpath to oldpath"""
mbligh4b089662006-06-14 22:34:58 +0000362 if (oldpath):
363 return newpath + ':' + oldpath
364 else:
365 return newpath
366
367
368def append_path(oldpath, newpath):
mblighc86b0b42006-07-28 17:35:28 +0000369 """append newpath to oldpath"""
mbligh4b089662006-06-14 22:34:58 +0000370 if (oldpath):
371 return oldpath + ':' + newpath
372 else:
373 return newpath
374
375
mbligh4e75b0d2006-08-29 15:22:44 +0000376def avgtime_print(dir):
377 """ Calculate some benchmarking statistics.
378 Input is a directory containing a file called 'time'.
379 File contains one-per-line results of /usr/bin/time.
380 Output is average Elapsed, User, and System time in seconds,
381 and average CPU percentage.
382 """
383 f = open(dir + "/time")
384 user = system = elapsed = cpu = count = 0
385 r = re.compile('([\d\.]*)user ([\d\.]*)system (\d*):([\d\.]*)elapsed (\d*)%CPU')
386 for line in f.readlines():
387 try:
388 s = r.match(line);
mblighe1ee2672006-08-29 16:27:15 +0000389 user += float(s.group(1))
390 system += float(s.group(2))
391 elapsed += (float(s.group(3)) * 60) + float(s.group(4))
392 cpu += float(s.group(5))
mbligh4e75b0d2006-08-29 15:22:44 +0000393 count += 1
394 except:
395 raise ValueError("badly formatted times")
396
397 f.close()
398 return "Elapsed: %0.2fs User: %0.2fs System: %0.2fs CPU: %0.0f%%" % \
399 (elapsed/count, user/count, system/count, cpu/count)
400
401
mblighf06db0f2006-09-30 17:08:43 +0000402def running_config():
403 """
404 Return path of config file of the currently running kernel
405 """
406 for config in ('/proc/config.gz', \
407 '/boot/config-%s' % system_output('uname -r') ):
408 if os.path.isfile(config):
409 return config
410 return None
mbligh9ec8acc2006-10-05 06:52:33 +0000411
412
413def cpu_online_map():
414 """
415 Check out the available cpu online map
416 """
417 cpus = []
418 for line in open('/proc/cpuinfo', 'r').readlines():
419 if line.startswith('processor'):
420 cpus.append(line.split()[2]) # grab cpu number
421 return cpus
mbligh663e4f62006-10-11 05:03:40 +0000422
423
424def check_glibc_ver(ver):
425 glibc_ver = commands.getoutput('ldd --version').splitlines()[0]
mblighcabfdaf2006-10-11 14:07:48 +0000426 glibc_ver = re.search(r'(\d+\.\d+(\.\d+)?)', glibc_ver).group()
mblighea97ab82006-10-13 20:18:01 +0000427 if glibc_ver.split('.') < ver.split('.'):
428 raise "Glibc is too old (%s). Glibc >= %s is needed." % \
429 (glibc_ver, ver)
mbligh9061a272006-12-28 21:20:51 +0000430
431def read_one_line(filename):
432 return open(filename, 'r').readline().strip()
433
434
435def write_one_line(filename, str):
436 str.rstrip()
437 open(filename, 'w').write(str.rstrip() + "\n")
mbligh264cd8f2007-02-02 23:57:43 +0000438
439
440def human_format(number):
441 # Convert number to kilo / mega / giga format.
442 if number < 1024:
443 return "%d" % number
444 kilo = float(number) / 1024.0
445 if kilo < 1024:
446 return "%.2fk" % kilo
447 meg = kilo / 1024.0
448 if meg < 1024:
449 return "%.2fM" % meg
450 gig = meg / 1024.0
451 return "%.2fG" % gig
452
mbligh8eca3a92007-02-03 20:59:39 +0000453
454def numa_nodes():
455 node_paths = glob.glob('/sys/devices/system/node/node*')
456 nodes = [int(re.sub(r'.*node(\d+)', r'\1', x)) for x in node_paths]
457 return (sorted(nodes))
458
459
460def node_size():
461 nodes = max(len(numa_nodes()), 1)
462 return ((memtotal() * 1024) / nodes)
463