rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
print 'Error: copying old client:', err
logging.error('Copying old client: %s', err)
def install_completed_client(compiled_dir, project_client): """Remove old client directory if it exists, move installed client to the old directory and move newly compield client to the installed client dir. @param compiled_dir: Where the new client was compiled @param project_client: project.client pair e.g. autotest...
print 'Error: Compiled directory is gone, something went wrong'
logging.error('Compiled directory is gone, something went wrong')
def install_completed_client(compiled_dir, project_client): """Remove old client directory if it exists, move installed client to the old directory and move newly compield client to the installed client dir. @param compiled_dir: Where the new client was compiled @param project_client: project.client pair e.g. autotest...
print 'Compiling client %s' % project_client
logging.info('Compiling client %s', project_client)
def compile_and_install_client(project_client, extra_args='', install_client=True): """Compile the client into a temporary directory, if successful call install_completed_client to install the new client. @param project_client: project.client pair e.g. autotest.AfeClient @param install_client: Boolean, if True install ...
print 'Error compiling %s, leaving old client' % project_client
logging.info('Error compiling %s, leaving old client', project_client)
def compile_and_install_client(project_client, extra_args='', install_client=True): """Compile the client into a temporary directory, if successful call install_completed_client to install the new client. @param project_client: project.client pair e.g. autotest.AfeClient @param install_client: Boolean, if True install ...
print 'Projects that can be compiled:'
logging.info('Projects that can be compiled:')
def print_projects(): print 'Projects that can be compiled:' for project,clients in enumerate_projects().iteritems(): for client in clients: print '%s.%s' % (project, client)
print '%s.%s' % (project, client)
logging.info('%s.%s', project, client)
def print_projects(): print 'Projects that can be compiled:' for project,clients in enumerate_projects().iteritems(): for client in clients: print '%s.%s' % (project, client)
print '-c and -a are mutually exclusive'
logging.error('Options -c and -a are mutually exclusive')
def main(): parser = optparse.OptionParser() parser.add_option('-l', '--list-projects', action='store_true', dest='list_projects', default=False, help='List all projects and clients that can be compiled') parser.add_option('-a', '--compile-all', action='store_true', dest='compile_all', default=False, help='Compile all ...
print ('Error: The following clients failed: %s' % '\n'.join(failed_clients))
logging.error('The following clients failed: %s', '\n'.join(failed_clients))
def main(): parser = optparse.OptionParser() parser.add_option('-l', '--list-projects', action='store_true', dest='list_projects', default=False, help='List all projects and clients that can be compiled') parser.add_option('-a', '--compile-all', action='store_true', dest='compile_all', default=False, help='Compile all ...
uuid = utils.system_output('blkid -s UUID -o value %s' % p.device)
uuid = utils.system_output('blkid -p -s UUID -o value %s' % p.device)
def get_mount_info(partition_list): """ Picks up mount point information about the machine mounts. By default, we try to associate mount points with UUIDs, because in newer distros the partitions are uniquely identified using them. """ mount_info = set() for p in partition_list: try: uuid = utils.system_output('blkid -...
error_dict[f.name] = str(e.message)
error_dict[f.name] = str(e)
def _validate(self): """ First coerces all fields on this instance to their proper Python types. Then runs validation on every field. Returns a dictionary of field_name -> error_list.
os.symlink(dest, self.symlink_name)
symlink_path = os.path.join( install_dir, GwtPackage.name, self.symlink_name) if os.path.exists(symlink_path): os.remove(symlink_path) os.symlink(dest, symlink_path)
def _build_and_install(self, install_dir): dest = os.path.join(install_dir, GwtPackage.name, self.local_filename) shutil.copyfile(self.verified_package, dest) os.symlink(dest, self.symlink_name) return True
if options['keyvals'] is not None:
if options.get('keyvals'):
def create(cls, owner, options, hosts): """\ Creates a job by taking some information (the listed args) and filling in the rest of the necessary information. """ AclGroup.check_for_acl_violation_hosts(hosts)
self._ut.fail('\n'.join(self.errors))
if self._ut: self._ut.fail('\n'.join(self.errors))
def check_playback(self): """ Report any errors that were encounterd during calls to __method_playback(). """ if len(self.errors) > 0: if self._debug: print '\nPlayback errors:' for error in self.errors: print >> sys.__stdout__, error self._ut.fail('\n'.join(self.errors)) raise CheckPlaybackError elif len(self.recordin...
self._ut.fail('\n'.join(errors))
if self._ut: self._ut.fail('\n'.join(errors))
def check_playback(self): """ Report any errors that were encounterd during calls to __method_playback(). """ if len(self.errors) > 0: if self._debug: print '\nPlayback errors:' for error in self.errors: print >> sys.__stdout__, error self._ut.fail('\n'.join(self.errors)) raise CheckPlaybackError elif len(self.recordin...
repo_url_list = [repo.url for repo in repositories]
def fetch_pkg(self, pkg_name, dest_path, repo_url=None, use_checksum=False): ''' Fetch the package into dest_dir from repo_url. By default repo_url is None and the package is looked in all the repostories specified. Otherwise it fetches it from the specific repo_url. pkg_name : name of the package (ex: test-sleepte...
body += "Job Name: %s\n" % self.job.name
body += "Job name: %s\n" % self.job.name
def _get_status_email_contents(self, status, summary=None, hostname=None): """ Gather info for the status notification e-mails.
body += "Execution Time (HH:MM:SS): %s\n" % job_stats['execution_time'] body += "Tests Executed: %s\n" % job_stats['total_executed'] body += "Tests Passed: %s\n" % job_stats['total_passed'] body += "Tests Failed: %s\n" % job_stats['total_failed'] body += "Success Rate: %.2f %%\n" % job_stats['success_rate'] body += "Fa...
body += "Execution time (HH:MM:SS): %s\n" % job_stats['execution_time'] if int(job_stats['total_executed']) > 0: body += "User tests executed: %s\n" % job_stats['total_executed'] body += "User tests passed: %s\n" % job_stats['total_passed'] body += "User tests failed: %s\n" % job_stats['total_failed'] body += ("User te...
def _get_status_email_contents(self, status, summary=None, hostname=None): """ Gather info for the status notification e-mails.
if total_executed <= 2: total_executed = 0 total_failed = 0
job_failure_count = 0 for r in failed_rows: test_name = r[0] job_test_pattern = re.compile('SERVER|CLIENT\\_JOB\.[\d]') if job_test_pattern.match(test_name): job_failure_count += 1 total_executed -= job_failure_count total_failed = len(failed_rows) - job_failure_count if total_executed > 0: success_rate = 100 - ((...
def get_execution_details(self): """ Get test execution details for this job.
else: total_executed -= 2 total_failed = len(failed_rows) success_rate = 100 - ((total_failed / float(total_executed)) * 100)
def get_execution_details(self): """ Get test execution details for this job.
WHERE afe_job_id = %s;
WHERE afe_job_id = %s
def get_execution_details(self): """ Get test execution details for this job.
tko_kernel = models.kernel('tubes', tko_patches, '1234567')
tko_kernel = models.kernel('My Computer', tko_patches, '1234567')
def setUp(self): tko_patches = [] tko_patches.append(models.patch('New spec!', 'Reference?', 123456))
tko_job = models.job('/tmp/', 'darrenkuo', 'test', 'My Computer',
tko_job = models.job('/tmp/', 'root', 'test', 'My Computer',
def setUp(self): tko_patches = [] tko_patches.append(models.patch('New spec!', 'Reference?', 123456))
f = open('qa-job.serialize', 'wb') f.write(self.pb_job.SerializeToString()) f.close()
def setUp(self): super(ReadBackGetterTest, self).setUp()
error_msgs = {}
def fetch_pkg(self, pkg_name, dest_path, repo_url=None, use_checksum=False): ''' Fetch the package into dest_dir from repo_url. By default repo_url is None and the package is looked in all the repostories specified. Otherwise it fetches it from the specific repo_url. pkg_name : name of the package (ex: test-sleepte...
logging.error('%s could not be fetched from %s', pkg_name,
logging.debug('%s could not be fetched from %s', pkg_name,
def fetch_pkg(self, pkg_name, dest_path, repo_url=None, use_checksum=False): ''' Fetch the package into dest_dir from repo_url. By default repo_url is None and the package is looked in all the repostories specified. Otherwise it fetches it from the specific repo_url. pkg_name : name of the package (ex: test-sleepte...
raise error.PackageFetchError("%s could not be fetched from any of" " the repos %s : %s " % (pkg_name, repo_url_list, error_msgs))
raise error.PackageFetchError(message)
def fetch_pkg(self, pkg_name, dest_path, repo_url=None, use_checksum=False): ''' Fetch the package into dest_dir from repo_url. By default repo_url is None and the package is looked in all the repostories specified. Otherwise it fetches it from the specific repo_url. pkg_name : name of the package (ex: test-sleepte...
except ImportError: pass
except ImportError, e: if re.search(test_name, str(e)): pass else: logging.warning("%s import error: %s. Skipping %s" \ % (test_name, e, test_name))
def load_all_client_tests(options): """ Load and instantiate all client tests. This function is inspired from runtest() on client/common_lib/test.py. @param options: an object passed in from command line OptionParser. See all options defined on client/bin/autotest. @return a tuple containing the list of all instanti...
def mount(self, mountpoint, fstype=None, args='', record=True):
def mount(self, mountpoint=None, fstype=None, args='', record=True):
def mount(self, mountpoint, fstype=None, args='', record=True): """ Mount this partition to a mount point
db.delete('iteration_result', where) db.delete('iteration_attributes', where) db.delete('test_attributes', where) db.delete('test_labels_tests', {'test_id': test_idx}) db.delete('tests', where)
db.delete('tko_iteration_result', where) db.delete('tko_iteration_attributes', where) db.delete('tko_test_attributes', where) db.delete('tko_test_labels_tests', {'test_id': test_idx}) db.delete('tko_tests', where)
def parse_one(db, jobname, path, reparse, mail_on_failure): """ Parse a single job. Optionally send email on failure. """ tko_utils.dprint("\nScanning %s (%s)" % (jobname, path)) old_job_idx = db.find_job(jobname) # old tests is a dict from tuple (test_name, subdir) to test_idx old_tests = {} if old_job_idx is not None...
task_func = lambda: task[0](*task[1:])
def task_func(): base_record_prefix = self._record_prefix proc_local = self._job_state.property_factory( '_state', '_record_prefix.%d' % os.getpid(), base_record_prefix, namespace='client') self.__class__._record_prefix = proc_local task[0](*task[1:])
def parallel(self, *tasklist): """Run tasks in parallel"""
branch = [b.lstrip('* ') for b in gitlog.stdout.split('\n')
branch = [b[2:] for b in gitlog.stdout.split('\n')
def get_branch(self, all=False, remote_tracking=False): """ Show the branches.
def __init__(self, repodir, giturl, weburl):
def __init__(self, repodir, giturl, weburl=None):
def __init__(self, repodir, giturl, weburl): super(installable_object.InstallableObject, self).__init__() if repodir is None: e_msg = 'You must provide a directory to hold the git repository' raise ValueError(e_msg) self.repodir = utils.sh_escape(repodir) if giturl is None: raise ValueError('You must provide a git URL ...
if weburl is None: raise ValueError('You must provide a http URL to the repository') self.weburl = weburl
if weburl is not None: warnings.warn("Param weburl: You are no longer required to provide " "a web URL for your git repos", DeprecationWarning)
def __init__(self, repodir, giturl, weburl): super(installable_object.InstallableObject, self).__init__() if repodir is None: e_msg = 'You must provide a directory to hold the git repository' raise ValueError(e_msg) self.repodir = utils.sh_escape(repodir) if giturl is None: raise ValueError('You must provide a git URL ...
self.gitcmdbase = 'git --git-dir=%s' % self.gitpath
self.gitcmdbase = '%s --git-dir=%s' % (git_base_cmd, self.gitpath)
def __init__(self, repodir, giturl, weburl): super(installable_object.InstallableObject, self).__init__() if repodir is None: e_msg = 'You must provide a directory to hold the git repository' raise ValueError(e_msg) self.repodir = utils.sh_escape(repodir) if giturl is None: raise ValueError('You must provide a git URL ...
return self.run('%s %s'%(self.gitcmdbase, cmd), ignore_status=ignore_status)
cmd = '%s %s' % (self.gitcmdbase, cmd) return self.run(cmd, ignore_status=ignore_status)
def gitcmd(self, cmd, ignore_status=False): return self.run('%s %s'%(self.gitcmdbase, cmd), ignore_status=ignore_status)
cmd = 'log --max-count=1' gitlog = self.gitcmd(cmd).stdout return str(gitlog.split('\n')[0]).split()[1]
cmd = 'log --pretty=format:"%H" -1' l_head_cmd = self.gitcmd(cmd) return l_head_cmd.stdout
def get_local_head(self): cmd = 'log --max-count=1' gitlog = self.gitcmd(cmd).stdout
def __needs_refresh(lines): tag = '<meta http-equiv="refresh" content="0"/>' if len(filter(lambda x: x.startswith(tag), lines)) > 0: return True return False gitwebaction=';a=commit;h=HEAD' url = self.weburl+gitwebaction max_refresh = 4 r = 0 print 'checking %s for changes' %(url) u = utils.urlopen(url) lines = u....
cmd1 = 'remote show' origin_name_cmd = self.gitcmd(cmd1) cmd2 = 'log --pretty=format:"%H" -1 ' + origin_name_cmd.stdout r_head_cmd = self.gitcmd(cmd2) return r_head_cmd.stdout
def __needs_refresh(lines): tag = '<meta http-equiv="refresh" content="0"/>' if len(filter(lambda x: x.startswith(tag), lines)) > 0: return True
self.use_rsync = self._check_rsync() if not self.use_rsync:
self._use_rsync = self._check_rsync() if not self._use_rsync:
def _initialize(self, hostname, user="root", port=22, password="", *args, **dargs): super(AbstractSSHHost, self)._initialize(hostname=hostname, *args, **dargs) self.ip = socket.getaddrinfo(self.hostname, None)[0][4][0] self.user = user self.port = port self.password = password
try_scp = not self.use_rsync if self.use_rsync:
try_scp = True if self.use_rsync():
def get_file(self, source, dest, delete_dest=False, preserve_perm=True, preserve_symlinks=False): """ Copy files from the remote host to a local path.
try_scp = True
def get_file(self, source, dest, delete_dest=False, preserve_perm=True, preserve_symlinks=False): """ Copy files from the remote host to a local path.
try_scp = not self.use_rsync if self.use_rsync:
try_scp = True if self.use_rsync():
def send_file(self, source, dest, delete_dest=False, preserve_symlinks=False): """ Copy files from a local path to the remote host.
try_scp = True
def send_file(self, source, dest, delete_dest=False, preserve_symlinks=False): """ Copy files from a local path to the remote host.
if os.path.isfile('/tmp/iptable-rules'):
if self.path_exists('/tmp/iptable-rules'):
def enable_ipfilters(self): """Re-enable the IP filters disabled from disable_ipfilters()""" if os.path.isfile('/tmp/iptable-rules'): self.run('iptables-restore < /tmp/iptable-rules')
if value:
if value is not None:
def sysctl_kernel(key, value=None): """(Very) partial implementation of sysctl, for kernel params""" if value: # write utils.write_one_line('/proc/sys/kernel/%s' % key, str(value)) else: # read out = utils.read_one_line('/proc/sys/kernel/%s' % key) return int(re.search(r'\d+', out).group(0))
running_job = test.parse_partial_test(self.job, None, job_name, "", current_kernel, started_time)
running_client = test.parse_partial_test(self.job, None, job_name, "", current_kernel, started_time)
def state_iterator(self, buffer): line = None new_tests = [] job_count, boot_count = 0, 0 min_stack_size = 0 stack = status_lib.status_stack() current_kernel = kernel("", []) # UNKNOWN current_status = status_lib.statuses[-1] current_reason = None started_time_stack = [None] subdir_stack = [None] running_test = None r...
msg %= (running_job.status, running_job.testname)
msg %= (running_client.status, running_client.testname)
def state_iterator(self, buffer): line = None new_tests = [] job_count, boot_count = 0, 0 min_stack_size = 0 stack = status_lib.status_stack() current_kernel = kernel("", []) # UNKNOWN current_status = status_lib.statuses[-1] current_reason = None started_time_stack = [None] subdir_stack = [None] running_test = None r...
new_tests.append(running_job)
new_tests.append(running_client)
def state_iterator(self, buffer): line = None new_tests = [] job_count, boot_count = 0, 0 min_stack_size = 0 stack = status_lib.status_stack() current_kernel = kernel("", []) # UNKNOWN current_status = status_lib.statuses[-1] current_reason = None started_time_stack = [None] subdir_stack = [None] running_test = None r...
if utils.compare_versions(glibc_ver, ver) == 1: raise error.TestError("Glibc too old (%s). Glibc >= %s is needed." % \ (glibc_ver, ver))
if utils.compare_versions(glibc_ver, ver) == -1: raise error.TestError("Glibc too old (%s). Glibc >= %s is needed." % (glibc_ver, ver))
def check_glibc_ver(ver): glibc_ver = commands.getoutput('ldd --version').splitlines()[0] glibc_ver = re.search(r'(\d+\.\d+(\.\d+)?)', glibc_ver).group() if utils.compare_versions(glibc_ver, ver) == 1: raise error.TestError("Glibc too old (%s). Glibc >= %s is needed." % \ (glibc_ver, ver))
if 'debugfs' in e:
if 'debugfs' in str(e):
def initialize(self): """ Gets path of kvm_stat and verifies if debugfs needs to be mounted. """ self.stat_path = os_dep.command('kvm_stat') try: utils.system_output("%s --batch" % self.stat_path) except error.CmdError, e: if 'debugfs' in e: utils.system('mount -t debugfs debugfs /sys/kernel/debug') else: raise error.A...
'unknown reason: %s' % e)
'unknown reason: %s' % str(e))
def initialize(self): """ Gets path of kvm_stat and verifies if debugfs needs to be mounted. """ self.stat_path = os_dep.command('kvm_stat') try: utils.system_output("%s --batch" % self.stat_path) except error.CmdError, e: if 'debugfs' in e: utils.system('mount -t debugfs debugfs /sys/kernel/debug') else: raise error.A...
git.GitRepo.__init__(self, repodir, giturl, weburl)
super(GitKernel, self).__init__(repodir, giturl, weburl)
def __init__(self, repodir, giturl, weburl): git.GitRepo.__init__(self, repodir, giturl, weburl) self._patches = [] self._config = None self._build = None self._branch = None self._revision = None
remote_source_material= os.path.join(self._build, os.path.basename(self.source_material))
def install(self, host, build=True, builddir=None, revision=None): """ Install the git tree in a host.
sk = source_kernel.SourceKernel(remote_source_material)
sk = source_kernel.SourceKernel(self._build)
def install(self, host, build=True, builddir=None, revision=None): """ Install the git tree in a host.
t_begin, t_end = time_row[0] delta = t_end - t_begin minutes, seconds = divmod(delta.seconds, 60) hours, minutes = divmod(minutes, 60) stats['execution_time'] = "%02d:%02d:%02d" % (hours, minutes, seconds)
if time_row: t_begin, t_end = time_row[0] delta = t_end - t_begin minutes, seconds = divmod(delta.seconds, 60) hours, minutes = divmod(minutes, 60) stats['execution_time'] = "%02d:%02d:%02d" % ( hours, minutes, seconds) else: stats['execution_time'] = '(none)'
def get_execution_details(self): """ Get test execution details for this job.
print >>sys.stderr, error_msg
logging.error(error_msg)
def main(): """ Find all ExternalPackage classes defined in this file and ask them to fetch, build and install themselves. """ logging_manager.configure_logging(BuildExternalsLoggingConfig(), verbose=True) os.umask(022) top_of_tree = external_packages.find_top_of_autotest_tree() package_dir = os.path.join(top_of_tree,...
msg = '!!! Unable to download %s' % package.name print msg
msg = 'Unable to download %s' % package.name logging.error(msg)
def fetch_necessary_packages(dest_dir, install_dir): """ Fetches all ExternalPackages into dest_dir. @param dest_dir: Directory the packages should be fetched into. @param install_dir: Directory where packages will later installed. @returns A tuple containing two lists: * A list of ExternalPackage instances that were...
msg = '!!! Unable to build and install %s' % package.name print msg
msg = 'Unable to build and install %s' % package.name logging.error(msg)
def build_and_install_packages(packages, install_dir): """ Builds and installs all packages into install_dir. @param packages - A list of already fetched ExternalPackage instances. @param install_dir - Directory the packages should be installed into. @returns A list of error messages for any installs that failed. """...
os.kill(self.pid, 15)
try: os.kill(self.pid, 15) except OSError: pass
def stop(self, test): """ Stops profiler execution by sending a SIGTERM to kvm_stat process.
self.builddir = os.path.join(self.bindir, 'build') if not os.path.isdir(self.builddir): os.makedirs(self.builddir)
def setup(self, tarball='trace-cmd.tar.bz2', **kwargs): """ Build and install trace-cmd from source.
self.trace_cmd = os.path.join(self.builddir, 'bin', 'trace-cmd') utils.system('%s reset' % self.trace_cmd)
def setup(self, tarball='trace-cmd.tar.bz2', **kwargs): """ Build and install trace-cmd from source.
logging.debug('Replacing in-memory state with on-disk state ' 'from %s', file_path)
def read_from_file(self, file_path, merge=True): """Read in any state from the file at file_path.
logging.debug('Persistent state flushed to %s', file_path)
def write_to_file(self, file_path): """Write out the current state to the given path.
logging.error("unable to import site symbol '%s', using non-site "
logging.debug("unable to import site symbol '%s', using non-site "
def import_site_symbol(path, module, name, dummy=None, modulefile=None): """ Try to import site specific symbol from site specific file if it exists @param path full filename of the source file calling this (ie __file__) @param module full module name @param name symbol name to be imported from the site file @param du...
self._increment_running_processes()
if self._process_started(): self._increment_running_processes()
def _try_starting_process(self): if not self._can_run_new_process(): return
ps = utils.system_output('ps -p %s | tail +2' % pid)
ps = utils.system_output('ps -p %s | sed 1d' % pid)
def unmount_force(self): """ Kill all other jobs accessing this partition. Use fuser and ps to find all mounts on this mountpoint and unmount them.
(self.loop, e))
(self.img, self.loop, e))
def _detach_img_loop(self): """ Detaches the image file from the loopback device. """ logging.debug('Detaching image %s from loop device %s', self.img, self.loop) try: cmd = 'losetup -d %s' % self.loop utils.system(cmd) except error.CmdError, e: e_msg = ('Error detaching image %s from loop device %s: %s' % (self.loop, ...
os.symlink( utils.get_relative_path(reboot_dir, os.path.dirname(symlink_dest)), symlink_dest)
symlink_src = utils.get_relative_path(reboot_dir, os.path.dirname(symlink_dest)) try: os.symlink(symlink_src, symlink_dest) except Exception, e: raise Exception, '%s: whilst linking %s to %s' % (e, symlink_src, symlink_dest)
def log_after_each_test(self, test): """ Logging hook called after a test finishs. """ test_sysinfodir = self._get_sysinfodir(test.outputdir)
data = None
headers, content = httplib2.Http().request(url, 'GET')
def gwt_forward(request, forward_addr): if len(request.POST) == 0: data = None else: data = request.raw_post_data url_response = urllib2.urlopen(GWT_SERVER + forward_addr, data=data) http_response = HttpResponse(url_response.read()) for header, value in url_response.info().items(): if header not in ('connection',): htt...
data = request.raw_post_data url_response = urllib2.urlopen(GWT_SERVER + forward_addr, data=data) http_response = HttpResponse(url_response.read()) for header, value in url_response.info().items():
headers, content = httplib2.Http().request(url, 'POST', body=request.raw_post_data) http_response = HttpResponse(content) for header, value in headers.iteritems():
def gwt_forward(request, forward_addr): if len(request.POST) == 0: data = None else: data = request.raw_post_data url_response = urllib2.urlopen(GWT_SERVER + forward_addr, data=data) http_response = HttpResponse(url_response.read()) for header, value in url_response.info().items(): if header not in ('connection',): htt...
self.failure(str(err), item=item,
error_parts = [str(err)] if self.debug: error_parts.append(err.read()) self.failure('\n\n'.join(error_parts), item=item,
def execute_rpc(self, op, item='', **data): retry = 2 while retry: try: return self.afe.run(op, **data) except urllib2.URLError, err: if hasattr(err, 'reason'): if 'timed out' not in err.reason: self.invalid_syntax('Invalid server name %s: %s' % (self.afe.web_server, err)) if hasattr(err, 'code'): self.failure(str(err)...
if line.startswith('processor'):
if line.lower().startswith('processor'):
def count_cpus(): """number of CPUs in the local machine according to /proc/cpuinfo""" f = file('/proc/cpuinfo', 'r') cpus = 0 for line in f.readlines(): if line.startswith('processor'): cpus += 1 return cpus
raise pickle.load(file(ename, 'r'))
e = pickle.load(file(ename, 'r')) i = 0 while True: pename = ename + ('-%d' % i) i += 1 if not os.path.exists(pename): break os.rename(ename, pename) raise e
def _check_for_subprocess_exception(temp_dir, pid): ename = temp_dir + "/debug/error-%d" % pid if os.path.exists(ename): raise pickle.load(file(ename, 'r'))
user = cls.objects.get_or_create(login=cls.AUTOTEST_SYSTEM)
user, _ = cls.objects.get_or_create(login=cls.AUTOTEST_SYSTEM)
def current_user(cls): user = thread_local.get_user() if user is None: user = cls.objects.get_or_create(login=cls.AUTOTEST_SYSTEM) user.access_level = cls.ACCESS_ROOT user.save() return user
def grade_from_status(status):
def grade_from_status(status_idx, status):
def grade_from_status(status): # % of goodness # GOOD (6) -> 1 # TEST_NA (8) is not counted # ## If the test doesn't PASS, it FAILS # else -> 0 if status == 6: return 1.0 else: return 0.0
if status == 6:
if status == status_idx['GOOD']:
def grade_from_status(status): # % of goodness # GOOD (6) -> 1 # TEST_NA (8) is not counted # ## If the test doesn't PASS, it FAILS # else -> 0 if status == 6: return 1.0 else: return 0.0
def average_grade_from_status_count(status_count):
def average_grade_from_status_count(status_idx, status_count):
def average_grade_from_status_count(status_count): average_grade = 0 total_count = 0 for key in status_count.keys(): if key not in (8, 9): # TEST_NA, RUNNING average_grade += (grade_from_status(key) * status_count[key]) total_count += status_count[key] if total_count != 0: average_grade = average_grade / total_count el...
if key not in (8, 9): average_grade += (grade_from_status(key)
if key not in (status_idx['TEST_NA'], status_idx['RUNNING']): average_grade += (grade_from_status(status_idx, key)
def average_grade_from_status_count(status_count): average_grade = 0 total_count = 0 for key in status_count.keys(): if key not in (8, 9): # TEST_NA, RUNNING average_grade += (grade_from_status(key) * status_count[key]) total_count += status_count[key] if total_count != 0: average_grade = average_grade / total_count el...
def shade_from_status_count(status_count):
def shade_from_status_count(status_idx, status_count):
def shade_from_status_count(status_count): if not status_count: return None ## average_grade defines a shade of the box ## 0 -> violet ## 0.76 -> red ## 0.88-> yellow ## 1.0 -> green average_grade = average_grade_from_status_count(status_count) ## find appropiate keyword from color_map if average_grade<0.01: shade = ...
average_grade = average_grade_from_status_count(status_count)
average_grade = average_grade_from_status_count(status_idx, status_count)
def shade_from_status_count(status_count): if not status_count: return None ## average_grade defines a shade of the box ## 0 -> violet ## 0.76 -> red ## 0.88-> yellow ## 1.0 -> green average_grade = average_grade_from_status_count(status_count) ## find appropiate keyword from color_map if average_grade<0.01: shade = ...
html = "%d&nbsp;/&nbsp;%d " % (status_count_subset.get(6, 0),
html = "%d&nbsp;/&nbsp;%d " % (status_count_subset.get(good, 0),
def status_html(db, box_data, shade): """ status_count: dict mapping from status (integer key) to count eg. { 'GOOD' : 4, 'FAIL' : 1 } """ status_count_subset = box_data.status_count.copy() test_na = db.status_idx['TEST_NA'] running = db.status_idx['RUNNING'] status_count_subset[test_na] = 0 # Don't count TEST_NA sta...
shade = shade_from_status_count(status_count)
shade = shade_from_status_count(db.status_idx, status_count)
def status_precounted_box(db, box_data, link = None, x_label = None, y_label = None): """ Display a ratio of total number of GOOD tests to total number of all tests in the group of tests. More info (e.g. 10 GOOD, 2 WARN, 3 FAIL) is in tooltips """ status_count = box_data.status_count if not status_count: return box(Non...
self._process_warnings(self.last_line, self.logs, warnings)
self._process_warnings(self.last_line, self.logs, old_warnings)
def write(self, data): # first check for any new console warnings self.server_warnings = self.job._read_warnings() + self.server_warnings warnings = self.server_warnings warnings.sort() # sort into timestamp order # now start processing the existng buffer and the new data data = self.leftover + data lines = data.split...
status_count_subset[8] = 0 status_count_subset[9] = 0
test_na = db.status_idx['TEST_NA'] running = db.status_idx['RUNNING'] status_count_subset[test_na] = 0 status_count_subset[running] = 0
def status_html(db, box_data, shade): """ status_count: dict mapping from status (integer key) to count eg. { 'GOOD' : 4, 'FAIL' : 1 } """ status_count_subset = box_data.status_count.copy() status_count_subset[8] = 0 # Don't count TEST_NA status_count_subset[9] = 0 # Don't count RUNNING html = "%d&nbsp;/&nbsp;%d " % ...
if 8 in box_data.status_count.keys(): html += ' (%d&nbsp;N/A)' % box_data.status_count[8] if 9 in box_data.status_count.keys(): html += ' (%d&nbsp;running)' % box_data.status_count[9]
if test_na in box_data.status_count.keys(): html += ' (%d&nbsp;N/A)' % box_data.status_count[test_na] if running in box_data.status_count.keys(): html += ' (%d&nbsp;running)' % box_data.status_count[running]
def status_html(db, box_data, shade): """ status_count: dict mapping from status (integer key) to count eg. { 'GOOD' : 4, 'FAIL' : 1 } """ status_count_subset = box_data.status_count.copy() status_count_subset[8] = 0 # Don't count TEST_NA status_count_subset[9] = 0 # Don't count RUNNING html = "%d&nbsp;/&nbsp;%d " % ...
file_checker = FileChecker(modified_file) file_checker.report()
if os.path.isfile(modified_file): file_checker = FileChecker(modified_file) file_checker.report()
def _check_files_modified_patch(self): untracked_files_after = self.vcs.get_unknown_files() modified_files_after = self.vcs.get_modified_files() add_to_vcs = [] for untracked_file in untracked_files_after: if untracked_file not in self.untracked_files_before: add_to_vcs.append(untracked_file)
tarball = os.path.join(self.src_dir, os.path.basename(base_tree))
tarball = os.path.join(self.src_dir, os.path.basename(base_tree.split(';')[0]))
def get_kernel_tree(self, base_tree): """Extract/link base_tree to self.build_dir"""
raise NotImplemented
raise NotImplementedError
def _keyval_path(self): """Subclasses must override this""" raise NotImplemented
assert (self.TASK_TYPE is not None, 'self.TASK_TYPE must be overridden')
assert self.TASK_TYPE is not None, 'self.TASK_TYPE must be overridden'
def __init__(self, task, extra_command_args): super(SpecialAgentTask, self).__init__()
@param header: Optional tuple with header elements to be displayed. """
@param header: Optional tuple or list with header elements to be displayed. """ if type(header) is list: header = tuple(header)
def matrix_to_string(matrix, header=None): """ Return a pretty, aligned string representation of a nxm matrix. This representation can be used to print any tabular data, such as database results. It works by scanning the lengths of each element in each column, and determining the format string dynamically. @param mat...
os.mkdir(group_dir)
os.makedirs(group_dir)
def _installtest(job, url): (group, name) = job.pkgmgr.get_package_name(url, 'test') # Bail if the test is already installed group_dir = os.path.join(job.testdir, "download", group) if os.path.exists(os.path.join(group_dir, name)): return (group, name) # If the group directory is missing create it and add # an empty ...
if utils.compare_versions(kv_tmp[0], ver) == 1: raise error.TestError("Kernel too old (%s). Kernel > %s is needed." % \ (kernel_ver, ver))
if utils.compare_versions(kv_tmp[0], ver) == -1: raise error.TestError("Kernel too old (%s). Kernel > %s is needed." % (kernel_ver, ver))
def check_kernel_ver(ver): kernel_ver = utils.system_output('uname -r') kv_tmp = re.split(r'[-]', kernel_ver)[0:3] if utils.compare_versions(kv_tmp[0], ver) == 1: raise error.TestError("Kernel too old (%s). Kernel > %s is needed." % \ (kernel_ver, ver))
logging.warn('System python is too old, crash handling disabled')
logging.warning('System python is too old, crash handling disabled')
def configure_crash_handler(self): """ Configure the crash handler by: * Setting up core size to unlimited * Putting an appropriate crash handler on /proc/sys/kernel/core_pattern * Create files that the crash handler will use to figure which tests are active at a given moment
logging.error('Crash handling system disabled: %s' % e)
logging.warning('Crash handling disabled: %s', e)
def configure_crash_handler(self): """ Configure the crash handler by: * Setting up core size to unlimited * Putting an appropriate crash handler on /proc/sys/kernel/core_pattern * Create files that the crash handler will use to figure which tests are active at a given moment
logging.debug('Crash handling system enabled')
try: os_dep.command('gdb') except ValueError: logging.warning('Could not find GDB installed. Crash handling ' 'will operate with limited functionality') logging.debug('Crash handling enabled')
def configure_crash_handler(self): """ Configure the crash handler by: * Setting up core size to unlimited * Putting an appropriate crash handler on /proc/sys/kernel/core_pattern * Create files that the crash handler will use to figure which tests are active at a given moment
core_dirs = glob.glob('%s/crash.*' % self.debugdir) if core_dirs: logging.warning('Programs crashed during test execution:') for dir in core_dirs: logging.warning('Please verify %s for more info', dir)
def crash_handler_report(self): """ If core dumps are found on the debugdir after the execution of the test, let the user know. """ if self.crash_handling_enabled: core_dirs = glob.glob('%s/crash.*' % self.debugdir) if core_dirs: logging.warning('Programs crashed during test execution:') for dir in core_dirs: logging.w...
base_command = ("/usr/bin/ssh -a -x %s -o StrictHostKeyChecking=no "
base_command = ("/usr/bin/ssh -a -q -x %s -o StrictHostKeyChecking=no "
def make_ssh_command(user="root", port=22, opts='', connect_timeout=30, alive_interval=300): base_command = ("/usr/bin/ssh -a -x %s -o StrictHostKeyChecking=no " "-o UserKnownHostsFile=/dev/null -o BatchMode=yes " "-o ConnectTimeout=%d -o ServerAliveInterval=%d " "-l %s -p %d") assert isinstance(connect_timeout, (int, ...
'Inconsistent abort state', 'Queue entries have inconsistent abort state: ' + ', '.join('%s (%s)' % (queue_entry, queue_entry.aborted)))
'Inconsistent abort state', 'Queue entries have inconsistent abort state:\n' + '\n'.join(entries))
def _job_was_aborted(self): was_aborted = None for queue_entry in self.queue_entries: queue_entry.update_from_database() if was_aborted is None: # first queue entry was_aborted = bool(queue_entry.aborted) elif was_aborted != bool(queue_entry.aborted): # subsequent entries email_manager.manager.enqueue_notify_email( 'In...
self.img = self.__create_disk_img(file_img, file_size) self.loop = self.__attach_img_loop(self.img) self.__create_single_partition(self.loop) self.device = self.__create_entries_partition(self.loop)
self.img = self._create_disk_img(file_img, file_size) self.loop = self._attach_img_loop(self.img) self._create_single_partition(self.loop) self.device = self._create_entries_partition(self.loop)
def __init__(self, file_img, file_size): """ Creates a virtual partition, keeping record of the device created under /dev/mapper (device attribute) so test writers can use it on their filesystem tests.
self.__remove_entries_partition() self.__detach_img_loop() self.__remove_disk_img() def __create_disk_img(self, img_path, size):
self._remove_entries_partition() self._detach_img_loop() self._remove_disk_img() def _create_disk_img(self, img_path, size):
def destroy(self): """ Removes the virtual partition from /dev/mapper, detaches the image file from the loopback device and removes the image file. """ logging.debug('Removing virtual partition - device %s', self.device) self.__remove_entries_partition() self.__detach_img_loop() self.__remove_disk_img()
def __attach_img_loop(self, img_path):
def _attach_img_loop(self, img_path):
def __attach_img_loop(self, img_path): """ Attaches a file image to a loopback device using losetup.