blob: bf05ded5170ea6bec994caacdececa220450aa91 [file] [log] [blame]
mblighc86b0b42006-07-28 17:35:28 +00001"""Convenience functions for use by tests or whomever.
2"""
3
mbligh9fb37cb2008-06-03 14:57:35 +00004import os, shutil, sys, signal, commands, pickle, glob, statvfs
5import re, string, fnmatch
6from autotest_lib.client.common_lib import error, utils
mblighf4c35322006-03-13 01:01:10 +00007
mblighea397bb2008-02-02 19:17:51 +00008
9
mblighf4c35322006-03-13 01:01:10 +000010def grep(pattern, file):
jadmanski0afbb632008-06-06 21:10:57 +000011 """
12 This is mainly to fix the return code inversion from grep
13 Also handles compressed files.
mbligh7bdbfbd2006-09-30 16:47:01 +000014
jadmanski0afbb632008-06-06 21:10:57 +000015 returns 1 if the pattern is present in the file, 0 if not.
16 """
17 command = 'grep "%s" > /dev/null' % pattern
18 ret = cat_file_to_cmd(file, command, ignore_status=True)
19 return not ret
mblighaf4efc22008-01-25 16:33:59 +000020
21
mblighc86b0b42006-07-28 17:35:28 +000022def difflist(list1, list2):
jadmanski0afbb632008-06-06 21:10:57 +000023 """returns items in list2 that are not in list1"""
24 diff = [];
25 for x in list2:
26 if x not in list1:
27 diff.append(x)
28 return diff
mblighf4c35322006-03-13 01:01:10 +000029
mblighc86b0b42006-07-28 17:35:28 +000030
mbligh8ea61e22008-05-09 18:09:37 +000031def cat_file_to_cmd(file, command, ignore_status=0, return_output=False):
jadmanski0afbb632008-06-06 21:10:57 +000032 """
33 equivalent to 'cat file | command' but knows to use
34 zcat or bzcat if appropriate
35 """
36 if return_output:
37 run_cmd = utils.system_output
38 else:
39 run_cmd = utils.system
mbligh96ffb9b2008-03-28 14:35:42 +000040
jadmanski0afbb632008-06-06 21:10:57 +000041 if not os.path.isfile(file):
42 raise NameError('invalid file %s to cat to command %s'
43 % (file, command))
44 if file.endswith('.bz2'):
45 return run_cmd('bzcat ' + file + ' | ' + command, ignore_status)
46 elif (file.endswith('.gz') or file.endswith('.tgz')):
47 return run_cmd('zcat ' + file + ' | ' + command, ignore_status)
48 else:
49 return run_cmd('cat ' + file + ' | ' + command, ignore_status)
mblighf4c35322006-03-13 01:01:10 +000050
mblighc86b0b42006-07-28 17:35:28 +000051
mbligh712cd142006-04-22 18:57:50 +000052def extract_tarball_to_dir(tarball, dir):
jadmanski0afbb632008-06-06 21:10:57 +000053 """
54 Extract a tarball to a specified directory name instead of whatever
55 the top level of a tarball is - useful for versioned directory names, etc
56 """
57 if os.path.exists(dir):
58 raise NameError, 'target %s already exists' % dir
59 pwd = os.getcwd()
60 os.chdir(os.path.dirname(os.path.abspath(dir)))
61 newdir = extract_tarball(tarball)
62 os.rename(newdir, dir)
63 os.chdir(pwd)
mbligh712cd142006-04-22 18:57:50 +000064
65
mbligh712cd142006-04-22 18:57:50 +000066def extract_tarball(tarball):
jadmanski0afbb632008-06-06 21:10:57 +000067 """Returns the directory extracted by the tarball."""
68 extracted = cat_file_to_cmd(tarball, 'tar xvf - 2>/dev/null',
69 return_output=True).splitlines()
mbligh5d423ca2008-04-16 23:06:12 +000070
jadmanski0afbb632008-06-06 21:10:57 +000071 dir = None
mbligh5d423ca2008-04-16 23:06:12 +000072
jadmanski0afbb632008-06-06 21:10:57 +000073 for line in extracted:
74 line = re.sub(r'^./', '', line)
75 if not line or line == '.':
76 continue
77 topdir = line.split('/')[0]
78 if os.path.isdir(topdir):
79 if dir:
80 assert(dir == topdir)
81 else:
82 dir = topdir
83 if dir:
84 return dir
85 else:
86 raise NameError('extracting tarball produced no dir')
mbligh712cd142006-04-22 18:57:50 +000087
mblighcdf02a42006-04-23 02:22:49 +000088
mbligh60418bb2008-01-03 01:55:09 +000089def get_md5sum(file_path):
jadmanski0afbb632008-06-06 21:10:57 +000090 """Gets the md5sum of a file. You must provide a valid path to the file"""
91 if not os.path.isfile(file_path):
92 raise ValueError, 'invalid file %s to verify' % file_path
93 return utils.system_output("md5sum " + file_path + " | awk '{print $1}'")
mbligh60418bb2008-01-03 01:55:09 +000094
95
96def unmap_url_cache(cachedir, url, expected_md5):
jadmanski0afbb632008-06-06 21:10:57 +000097 """\
98 Downloads a file from a URL to a cache directory. If the file is already
99 at the expected position and has the expected md5 number, let's not
100 download it again.
101 """
102 # Let's convert cachedir to a canonical path, if it's not already
103 cachedir = os.path.realpath(cachedir)
104 if not os.path.isdir(cachedir):
105 try:
mbligh23955fc2008-06-12 17:41:18 +0000106 utils.system('mkdir -p ' + cachedir)
jadmanski0afbb632008-06-06 21:10:57 +0000107 except:
108 raise ValueError('Could not create cache directory %s' % cachedir)
109 file_from_url = os.path.basename(url)
110 file_local_path = os.path.join(cachedir, file_from_url)
111 if os.path.isfile(file_local_path):
112 file_md5 = get_md5sum(file_local_path)
113 if file_md5 == expected_md5:
114 # File is already at the expected position and ready to go
115 src = file_from_url
116 else:
117 # Let's download the package again, it's corrupted...
118 src = url
119 else:
120 # File is not there, let's download it
121 src = url
122 return utils.unmap_url(cachedir, src, cachedir)
mblighea30c8a2006-04-22 22:24:25 +0000123
124
mblighf4c35322006-03-13 01:01:10 +0000125def force_copy(src, dest):
jadmanski0afbb632008-06-06 21:10:57 +0000126 """Replace dest with a new copy of src, even if it exists"""
127 if os.path.isfile(dest):
128 os.remove(dest)
129 if os.path.isdir(dest):
130 dest = os.path.join(dest, os.path.basename(src))
131 shutil.copyfile(src, dest)
132 return dest
mblighf4c35322006-03-13 01:01:10 +0000133
134
mblighfdbcaec2006-10-01 23:28:57 +0000135def force_link(src, dest):
jadmanski0afbb632008-06-06 21:10:57 +0000136 """Link src to dest, overwriting it if it exists"""
137 return utils.system("ln -sf %s %s" % (src, dest))
mblighfdbcaec2006-10-01 23:28:57 +0000138
139
mblighcdf02a42006-04-23 02:22:49 +0000140def file_contains_pattern(file, pattern):
jadmanski0afbb632008-06-06 21:10:57 +0000141 """Return true if file contains the specified egrep pattern"""
142 if not os.path.isfile(file):
143 raise NameError('file %s does not exist' % file)
144 return not utils.system('egrep -q "' + pattern + '" ' + file, ignore_status=True)
mblighcdf02a42006-04-23 02:22:49 +0000145
146
147def list_grep(list, pattern):
jadmanski0afbb632008-06-06 21:10:57 +0000148 """True if any item in list matches the specified pattern."""
149 compiled = re.compile(pattern)
150 for line in list:
151 match = compiled.search(line)
152 if (match):
153 return 1
154 return 0
mblighcdf02a42006-04-23 02:22:49 +0000155
mbligh987071e2008-06-13 16:39:12 +0000156
mbligh42b81ca2006-09-30 22:10:01 +0000157def get_os_vendor():
jadmanski0afbb632008-06-06 21:10:57 +0000158 """Try to guess what's the os vendor
159 """
160 issue = '/etc/issue'
mblighaf4efc22008-01-25 16:33:59 +0000161
jadmanski0afbb632008-06-06 21:10:57 +0000162 if not os.path.isfile(issue):
163 return 'Unknown'
mblighaf4efc22008-01-25 16:33:59 +0000164
jadmanski0afbb632008-06-06 21:10:57 +0000165 if file_contains_pattern(issue, 'Red Hat'):
166 return 'Red Hat'
167 elif file_contains_pattern(issue, 'Fedora Core'):
168 return 'Fedora Core'
169 elif file_contains_pattern(issue, 'SUSE'):
170 return 'SUSE'
171 elif file_contains_pattern(issue, 'Ubuntu'):
172 return 'Ubuntu'
173 elif file_contains_pattern(issue, 'Debian'):
174 return 'Debian'
175 else:
176 return 'Unknown'
mblighaf4efc22008-01-25 16:33:59 +0000177
mblighcdf02a42006-04-23 02:22:49 +0000178
mblighf49d5cf2006-04-23 02:24:42 +0000179def get_vmlinux():
jadmanski0afbb632008-06-06 21:10:57 +0000180 """Return the full path to vmlinux
mblighc86b0b42006-07-28 17:35:28 +0000181
jadmanski0afbb632008-06-06 21:10:57 +0000182 Ahem. This is crap. Pray harder. Bad Martin.
183 """
184 vmlinux = '/boot/vmlinux-%s' % utils.system_output('uname -r')
185 if os.path.isfile(vmlinux):
186 return vmlinux
187 vmlinux = '/lib/modules/%s/build/vmlinux' % utils.system_output('uname -r')
188 if os.path.isfile(vmlinux):
189 return vmlinux
190 return None
mblighf49d5cf2006-04-23 02:24:42 +0000191
192
193def get_systemmap():
jadmanski0afbb632008-06-06 21:10:57 +0000194 """Return the full path to System.map
mblighc86b0b42006-07-28 17:35:28 +0000195
jadmanski0afbb632008-06-06 21:10:57 +0000196 Ahem. This is crap. Pray harder. Bad Martin.
197 """
198 map = '/boot/System.map-%s' % utils.system_output('uname -r')
199 if os.path.isfile(map):
200 return map
201 map = '/lib/modules/%s/build/System.map' % utils.system_output('uname -r')
202 if os.path.isfile(map):
203 return map
204 return None
mbligh67b5ece2006-04-23 02:53:12 +0000205
206
207def get_modules_dir():
jadmanski0afbb632008-06-06 21:10:57 +0000208 """Return the modules dir for the running kernel version"""
209 kernel_version = utils.system_output('uname -r')
210 return '/lib/modules/%s/kernel' % kernel_version
mblighf49d5cf2006-04-23 02:24:42 +0000211
212
mbligh5970cf02006-08-06 15:39:22 +0000213def get_cpu_arch():
jadmanski0afbb632008-06-06 21:10:57 +0000214 """Work out which CPU architecture we're running on"""
215 f = open('/proc/cpuinfo', 'r')
216 cpuinfo = f.readlines()
217 f.close()
218 if list_grep(cpuinfo, '^cpu.*(RS64|POWER3|Broadband Engine)'):
219 return 'power'
220 elif list_grep(cpuinfo, '^cpu.*POWER4'):
221 return 'power4'
222 elif list_grep(cpuinfo, '^cpu.*POWER5'):
223 return 'power5'
224 elif list_grep(cpuinfo, '^cpu.*POWER6'):
225 return 'power6'
226 elif list_grep(cpuinfo, '^cpu.*PPC970'):
227 return 'power970'
228 elif list_grep(cpuinfo, 'Opteron'):
229 return 'x86_64'
230 elif list_grep(cpuinfo, 'GenuineIntel') and list_grep(cpuinfo, '48 bits virtual'):
231 return 'x86_64'
232 else:
233 return 'i386'
mblighf4c35322006-03-13 01:01:10 +0000234
235
mbligh548f29a2006-10-17 04:55:12 +0000236def get_current_kernel_arch():
jadmanski0afbb632008-06-06 21:10:57 +0000237 """Get the machine architecture, now just a wrap of 'uname -m'."""
238 return os.popen('uname -m').read().rstrip()
mblighcdf02a42006-04-23 02:22:49 +0000239
240
mblighfdbcaec2006-10-01 23:28:57 +0000241def get_file_arch(filename):
jadmanski0afbb632008-06-06 21:10:57 +0000242 # -L means follow symlinks
243 file_data = utils.system_output('file -L ' + filename)
244 if file_data.count('80386'):
245 return 'i386'
246 return None
mblighfdbcaec2006-10-01 23:28:57 +0000247
248
mblighf4c35322006-03-13 01:01:10 +0000249def count_cpus():
jadmanski0afbb632008-06-06 21:10:57 +0000250 """number of CPUs in the local machine according to /proc/cpuinfo"""
251 f = file('/proc/cpuinfo', 'r')
252 cpus = 0
253 for line in f.readlines():
254 if line.startswith('processor'):
255 cpus += 1
256 return cpus
mblighf4c35322006-03-13 01:01:10 +0000257
mblighe7a170f2006-12-05 07:48:18 +0000258
259# Returns total memory in kb
mbligh558885e2008-04-01 20:41:38 +0000260def read_from_meminfo(key):
jadmanski0afbb632008-06-06 21:10:57 +0000261 meminfo = utils.system_output('grep %s /proc/meminfo' % key)
262 return int(re.search(r'\d+', meminfo).group(0))
mbligh558885e2008-04-01 20:41:38 +0000263
264
mblighe7a170f2006-12-05 07:48:18 +0000265def memtotal():
jadmanski0afbb632008-06-06 21:10:57 +0000266 return read_from_meminfo('MemTotal')
mbligh558885e2008-04-01 20:41:38 +0000267
268
269def freememtotal():
jadmanski0afbb632008-06-06 21:10:57 +0000270 return read_from_meminfo('MemFree')
mbligh558885e2008-04-01 20:41:38 +0000271
272
273def sysctl_kernel(key, value=None):
jadmanski0afbb632008-06-06 21:10:57 +0000274 """(Very) partial implementation of sysctl, for kernel params"""
275 if value:
276 # write
277 utils.write_one_line('/proc/sys/kernel/%s' % key, str(value))
278 else:
279 # read
280 out = utils.read_one_line('/proc/sys/kernel/%s' % key)
281 return int(re.search(r'\d+', out).group(0))
mblighe7a170f2006-12-05 07:48:18 +0000282
283
mbligh5285a2d2008-03-10 20:28:08 +0000284def _convert_exit_status(sts):
jadmanski0afbb632008-06-06 21:10:57 +0000285 if os.WIFSIGNALED(sts):
286 return -os.WTERMSIG(sts)
287 elif os.WIFEXITED(sts):
288 return os.WEXITSTATUS(sts)
289 else:
290 # impossible?
291 raise RuntimeError("Unknown exit status %d!" % sts)
mbligh5285a2d2008-03-10 20:28:08 +0000292
293
mblighf4c35322006-03-13 01:01:10 +0000294def where_art_thy_filehandles():
jadmanski0afbb632008-06-06 21:10:57 +0000295 """Dump the current list of filehandles"""
296 os.system("ls -l /proc/%d/fd >> /dev/tty" % os.getpid())
mblighf4c35322006-03-13 01:01:10 +0000297
298
299def print_to_tty(string):
jadmanski0afbb632008-06-06 21:10:57 +0000300 """Output string straight to the tty"""
301 open('/dev/tty', 'w').write(string + '\n')
mblighf4c35322006-03-13 01:01:10 +0000302
303
mblighb8a14e32006-05-06 00:17:35 +0000304def dump_object(object):
jadmanski0afbb632008-06-06 21:10:57 +0000305 """Dump an object's attributes and methods
mblighc86b0b42006-07-28 17:35:28 +0000306
jadmanski0afbb632008-06-06 21:10:57 +0000307 kind of like dir()
308 """
309 for item in object.__dict__.iteritems():
310 print item
311 try:
312 (key,value) = item
313 dump_object(value)
314 except:
315 continue
mblighb8a14e32006-05-06 00:17:35 +0000316
317
mbligh4b089662006-06-14 22:34:58 +0000318def environ(env_key):
jadmanski0afbb632008-06-06 21:10:57 +0000319 """return the requested environment variable, or '' if unset"""
320 if (os.environ.has_key(env_key)):
321 return os.environ[env_key]
322 else:
323 return ''
mbligh4b089662006-06-14 22:34:58 +0000324
325
326def prepend_path(newpath, oldpath):
jadmanski0afbb632008-06-06 21:10:57 +0000327 """prepend newpath to oldpath"""
328 if (oldpath):
329 return newpath + ':' + oldpath
330 else:
331 return newpath
mbligh4b089662006-06-14 22:34:58 +0000332
333
334def append_path(oldpath, newpath):
jadmanski0afbb632008-06-06 21:10:57 +0000335 """append newpath to oldpath"""
336 if (oldpath):
337 return oldpath + ':' + newpath
338 else:
339 return newpath
mbligh4b089662006-06-14 22:34:58 +0000340
341
mbligh4e75b0d2006-08-29 15:22:44 +0000342def avgtime_print(dir):
jadmanski0afbb632008-06-06 21:10:57 +0000343 """ Calculate some benchmarking statistics.
344 Input is a directory containing a file called 'time'.
345 File contains one-per-line results of /usr/bin/time.
346 Output is average Elapsed, User, and System time in seconds,
347 and average CPU percentage.
348 """
349 f = open(dir + "/time")
350 user = system = elapsed = cpu = count = 0
351 r = re.compile('([\d\.]*)user ([\d\.]*)system (\d*):([\d\.]*)elapsed (\d*)%CPU')
352 for line in f.readlines():
353 try:
354 s = r.match(line);
355 user += float(s.group(1))
356 system += float(s.group(2))
357 elapsed += (float(s.group(3)) * 60) + float(s.group(4))
358 cpu += float(s.group(5))
359 count += 1
360 except:
361 raise ValueError("badly formatted times")
mblighaf4efc22008-01-25 16:33:59 +0000362
jadmanski0afbb632008-06-06 21:10:57 +0000363 f.close()
364 return "Elapsed: %0.2fs User: %0.2fs System: %0.2fs CPU: %0.0f%%" % \
365 (elapsed/count, user/count, system/count, cpu/count)
mbligh4e75b0d2006-08-29 15:22:44 +0000366
367
mblighf06db0f2006-09-30 17:08:43 +0000368def running_config():
jadmanski0afbb632008-06-06 21:10:57 +0000369 """
370 Return path of config file of the currently running kernel
371 """
372 version = utils.system_output('uname -r')
373 for config in ('/proc/config.gz', \
374 '/boot/config-%s' % version,
375 '/lib/modules/%s/build/.config' % version):
376 if os.path.isfile(config):
377 return config
378 return None
mbligh9ec8acc2006-10-05 06:52:33 +0000379
380
mbligha1bef1f2007-04-03 17:18:07 +0000381def check_for_kernel_feature(feature):
jadmanski0afbb632008-06-06 21:10:57 +0000382 config = running_config()
mbligha1bef1f2007-04-03 17:18:07 +0000383
jadmanski0afbb632008-06-06 21:10:57 +0000384 if not config:
385 raise TypeError("Can't find kernel config file")
mbligha1bef1f2007-04-03 17:18:07 +0000386
jadmanski0afbb632008-06-06 21:10:57 +0000387 if config.endswith('.gz'):
388 grep = 'zgrep'
389 else:
390 grep = 'grep'
391 grep += ' ^CONFIG_%s= %s' % (feature, config)
mbligha1bef1f2007-04-03 17:18:07 +0000392
jadmanski0afbb632008-06-06 21:10:57 +0000393 if not utils.system_output(grep, ignore_status=True):
394 raise ValueError("Kernel doesn't have a %s feature" % (feature))
mbligha1bef1f2007-04-03 17:18:07 +0000395
396
mbligh9ec8acc2006-10-05 06:52:33 +0000397def cpu_online_map():
jadmanski0afbb632008-06-06 21:10:57 +0000398 """
399 Check out the available cpu online map
400 """
401 cpus = []
402 for line in open('/proc/cpuinfo', 'r').readlines():
403 if line.startswith('processor'):
404 cpus.append(line.split()[2]) # grab cpu number
405 return cpus
mbligh663e4f62006-10-11 05:03:40 +0000406
407
408def check_glibc_ver(ver):
jadmanski0afbb632008-06-06 21:10:57 +0000409 glibc_ver = commands.getoutput('ldd --version').splitlines()[0]
410 glibc_ver = re.search(r'(\d+\.\d+(\.\d+)?)', glibc_ver).group()
411 if glibc_ver.split('.') < ver.split('.'):
mblighbd8f9982008-06-06 23:20:35 +0000412 raise error.TestError("Glibc too old (%s). Glibc >= %s is needed." % \
jadmanski0afbb632008-06-06 21:10:57 +0000413 (glibc_ver, ver))
mbligh07635222007-07-09 21:29:00 +0000414
415def check_kernel_ver(ver):
jadmanski0afbb632008-06-06 21:10:57 +0000416 kernel_ver = utils.system_output('uname -r')
417 kv_tmp = re.split(r'[-]', kernel_ver)[0:3]
418 if kv_tmp[0].split('.') < ver.split('.'):
mblighbd8f9982008-06-06 23:20:35 +0000419 raise error.TestError("Kernel too old (%s). Kernel > %s is needed." % \
jadmanski0afbb632008-06-06 21:10:57 +0000420 (kernel_ver, ver))
mbligh60418bb2008-01-03 01:55:09 +0000421
mbligh9061a272006-12-28 21:20:51 +0000422
mbligh264cd8f2007-02-02 23:57:43 +0000423def human_format(number):
jadmanski0afbb632008-06-06 21:10:57 +0000424 # Convert number to kilo / mega / giga format.
425 if number < 1024:
426 return "%d" % number
427 kilo = float(number) / 1024.0
428 if kilo < 1024:
429 return "%.2fk" % kilo
430 meg = kilo / 1024.0
431 if meg < 1024:
432 return "%.2fM" % meg
433 gig = meg / 1024.0
434 return "%.2fG" % gig
mbligh264cd8f2007-02-02 23:57:43 +0000435
mbligh8eca3a92007-02-03 20:59:39 +0000436
437def numa_nodes():
jadmanski0afbb632008-06-06 21:10:57 +0000438 node_paths = glob.glob('/sys/devices/system/node/node*')
439 nodes = [int(re.sub(r'.*node(\d+)', r'\1', x)) for x in node_paths]
440 return (sorted(nodes))
mbligh8eca3a92007-02-03 20:59:39 +0000441
442
443def node_size():
jadmanski0afbb632008-06-06 21:10:57 +0000444 nodes = max(len(numa_nodes()), 1)
445 return ((memtotal() * 1024) / nodes)
mbligh8eca3a92007-02-03 20:59:39 +0000446
mbligh32bcff32007-07-25 16:37:32 +0000447
448def to_seconds(time_string):
jadmanski0afbb632008-06-06 21:10:57 +0000449 """Converts a string in M+:SS.SS format to S+.SS"""
450 elts = time_string.split(':')
451 if len(elts) == 1:
452 return time_string
453 return str(int(elts[0]) * 60 + float(elts[1]))
mbligh32bcff32007-07-25 16:37:32 +0000454
455
456def extract_all_time_results(results_string):
jadmanski0afbb632008-06-06 21:10:57 +0000457 """Extract user, system, and elapsed times into a list of tuples"""
458 pattern = re.compile(r"(.*?)user (.*?)system (.*?)elapsed")
459 results = []
460 for result in pattern.findall(results_string):
461 results.append(tuple([to_seconds(elt) for elt in result]))
462 return results
mblighc4211642007-08-02 21:00:51 +0000463
464
465def pickle_load(filename):
jadmanski0afbb632008-06-06 21:10:57 +0000466 return pickle.load(open(filename, 'r'))
mblighc4211642007-08-02 21:00:51 +0000467
mbligh237bed32007-09-05 13:05:57 +0000468
469# Return the kernel version and build timestamp.
470def running_os_release():
jadmanski0afbb632008-06-06 21:10:57 +0000471 return os.uname()[2:4]
mbligh237bed32007-09-05 13:05:57 +0000472
473
474def running_os_ident():
jadmanski0afbb632008-06-06 21:10:57 +0000475 (version, timestamp) = running_os_release()
476 return version + '::' + timestamp
mblighb830e282007-10-02 16:35:03 +0000477
478
mbligh523a19b2007-12-04 22:50:14 +0000479# much like find . -name 'pattern'
480def locate(pattern, root=os.getcwd()):
jadmanski0afbb632008-06-06 21:10:57 +0000481 for path, dirs, files in os.walk(root):
mbligh987071e2008-06-13 16:39:12 +0000482 for f in files:
483 if fnmatch.fnmatch(f, pattern):
mbligh7076b192008-06-13 17:53:49 +0000484 yield os.path.abspath(os.path.join(path, f))
mbligh523a19b2007-12-04 22:50:14 +0000485
486
mbligh25bb1e12007-10-12 23:57:47 +0000487def freespace(path):
jadmanski0afbb632008-06-06 21:10:57 +0000488 """Return the disk free space, in bytes"""
489 s = os.statvfs(path)
490 return s.f_bavail * s.f_bsize
jadmanski8415f962008-05-06 20:38:53 +0000491
492
493def disk_block_size(path):
jadmanski0afbb632008-06-06 21:10:57 +0000494 """Return the disk block size, in bytes"""
495 return os.statvfs(path).f_bsize
mbligh6de9cdf2007-11-24 19:35:28 +0000496
497
498def get_cpu_family():
jadmanski0afbb632008-06-06 21:10:57 +0000499 procinfo = utils.system_output('cat /proc/cpuinfo')
500 CPU_FAMILY_RE = re.compile(r'^cpu family\s+:\s+(\S+)', re.M)
501 matches = CPU_FAMILY_RE.findall(procinfo)
502 if matches:
503 return int(matches[0])
504 else:
505 raise error.TestError('Could not get valid cpu family data')
mbligh6de9cdf2007-11-24 19:35:28 +0000506
mbligh3e9062e2007-11-29 15:57:02 +0000507
mbligh2316e522007-11-24 19:39:52 +0000508def get_disks():
jadmanski0afbb632008-06-06 21:10:57 +0000509 df_output = utils.system_output('df')
510 disk_re = re.compile(r'^(/dev/hd[a-z]+)3', re.M)
511 return disk_re.findall(df_output)
mbligh6de9cdf2007-11-24 19:35:28 +0000512
mbligh3e9062e2007-11-29 15:57:02 +0000513
514def load_module(module_name):
jadmanski0afbb632008-06-06 21:10:57 +0000515 # Checks if a module has already been loaded
516 if module_is_loaded(module_name):
517 return False
mblighaf4efc22008-01-25 16:33:59 +0000518
jadmanski0afbb632008-06-06 21:10:57 +0000519 utils.system('/sbin/modprobe ' + module_name)
520 return True
mbligh3e9062e2007-11-29 15:57:02 +0000521
522
523def unload_module(module_name):
jadmanski0afbb632008-06-06 21:10:57 +0000524 utils.system('/sbin/rmmod ' + module_name)
mbligh3e9062e2007-11-29 15:57:02 +0000525
526
527def module_is_loaded(module_name):
jadmanski0afbb632008-06-06 21:10:57 +0000528 module_name = module_name.replace('-', '_')
529 modules = utils.system_output('/sbin/lsmod').splitlines()
530 for module in modules:
531 if module.startswith(module_name) and module[len(module_name)] == ' ':
532 return True
533 return False
mbligh3e9062e2007-11-29 15:57:02 +0000534
535
mbligh6b34c4c2008-01-10 16:32:04 +0000536def get_loaded_modules():
jadmanski0afbb632008-06-06 21:10:57 +0000537 lsmod_output = utils.system_output('/sbin/lsmod').splitlines()[1:]
538 return [line.split(None, 1)[0] for line in lsmod_output]
mbligh6b34c4c2008-01-10 16:32:04 +0000539
540
mbligh3e9062e2007-11-29 15:57:02 +0000541def get_huge_page_size():
jadmanski0afbb632008-06-06 21:10:57 +0000542 output = utils.system_output('grep Hugepagesize /proc/meminfo')
543 return int(output.split()[1]) # Assumes units always in kB. :(
mbligh3e9062e2007-11-29 15:57:02 +0000544
545
546def get_num_huge_pages():
jadmanski0afbb632008-06-06 21:10:57 +0000547 raw_hugepages = utils.system_output('/sbin/sysctl vm.nr_hugepages')
548 return int(raw_hugepages.split()[2])
mbligh3e9062e2007-11-29 15:57:02 +0000549
550
551def set_num_huge_pages(num):
jadmanski0afbb632008-06-06 21:10:57 +0000552 utils.system('/sbin/sysctl vm.nr_hugepages=%d' % num)
mbligh3e9062e2007-11-29 15:57:02 +0000553
554
555def get_system_nodes():
jadmanski0afbb632008-06-06 21:10:57 +0000556 nodes = os.listdir('/sys/devices/system/node')
557 nodes.sort()
558 return nodes
mbligh3e9062e2007-11-29 15:57:02 +0000559
560
mbligh6b34c4c2008-01-10 16:32:04 +0000561def get_cpu_vendor():
jadmanski0afbb632008-06-06 21:10:57 +0000562 cpuinfo = open('/proc/cpuinfo').read()
563 vendors = re.findall(r'(?m)^vendor_id\s*:\s*(\S+)\s*$', cpuinfo)
564 for i in xrange(1, len(vendors)):
565 if vendors[i] != vendors[0]:
566 raise error.TestError('multiple cpu vendors found: ' + str(vendors))
567 return vendors[0]
mbligh6b34c4c2008-01-10 16:32:04 +0000568
569
570def probe_cpus():
jadmanski0afbb632008-06-06 21:10:57 +0000571 """
572 This routine returns a list of cpu devices found under /sys/devices/system/cpu.
573 """
574 output = utils.system_output(
575 'find /sys/devices/system/cpu/ -maxdepth 1 -type d -name cpu*')
576 return output.splitlines()
mbligh6b34c4c2008-01-10 16:32:04 +0000577
578
mbligh70c50ad2008-02-12 20:56:13 +0000579def ping_default_gateway():
jadmanski0afbb632008-06-06 21:10:57 +0000580 """Ping the default gateway."""
mbligh70c50ad2008-02-12 20:56:13 +0000581
jadmanski0afbb632008-06-06 21:10:57 +0000582 network = open('/etc/sysconfig/network')
583 m = re.search('GATEWAY=(\S+)', network.read())
584
585 if m:
586 gw = m.group(1)
587 cmd = 'ping %s -c 5 > /dev/null' % gw
588 return utils.system(cmd, ignore_status=True)
589
590 raise error.TestError('Unable to find default gateway')
mbligh70c50ad2008-02-12 20:56:13 +0000591
592
jadmanski115feb22008-07-23 21:36:22 +0000593def drop_caches():
594 """Writes back all dirty pages to disk and clears all the caches."""
595 utils.system("sync")
596 utils.system("sync")
597 # We ignore failures here as this will fail on 2.6.11 kernels.
598 utils.system("echo 3 > /proc/sys/vm/drop_caches", ignore_status=True)
599
600
mbligh6de9cdf2007-11-24 19:35:28 +0000601try:
jadmanski0afbb632008-06-06 21:10:57 +0000602 from site_utils import *
mbligh6de9cdf2007-11-24 19:35:28 +0000603except ImportError:
jadmanski0afbb632008-06-06 21:10:57 +0000604 pass