run.py revision 412db4e993a383395d7ff1add4bb97f97ca3d433
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source. A copy of the CDDL is also available via the Internet at
#
#
# Copyright (c) 2012, 2015 by Delphix. All rights reserved.
#
import ConfigParser
import os
import logging
from optparse import OptionParser
from subprocess import PIPE
from subprocess import Popen
BASEDIR = '/var/tmp/test_results'
# Custom class to reopen the log file in case it is forcibly closed by a test.
"""Watch files, including closed files.
Similar to (and inherits from) logging.handler.WatchedFileHandler,
except that IOErrors are handled by reopening the stream and retrying.
This will be retried up to a configurable number of times before
giving up, default 5.
"""
while True:
try:
return
raise
total = 0
self.returncode = None
"""
Finalize the results of this Cmd.
"""
if killed:
"""
This class is a slightly modified version of the 'Stream' class found
here: http://goo.gl/aSGfv
"""
"""
Read from the file descriptor. If 'drain' set, read until EOF.
"""
if not drain:
break
"""
Read up to 4k of data from this output stream. Collect the output
up to the last newline, and append it to any leftover data from a
previous call. The lines are stored as a (timestamp, data) tuple
"""
if not buf:
return None
if '\n' not in buf:
return []
verified_users = []
return "Pathname: %s\nOutputdir: %s\nTimeout: %s\nUser: %s\n" % (
"""
Kill a running command due to timeout, or ^C from the keyboard. If
sudo is required, this user was verified previously.
"""
signal = '-TERM'
if not do_sudo:
del cmd[0]
try:
except:
pass
"""
If a user has been specified to run this Cmd and we're not already
running as that user, prepend the appropriate sudo command to run
as that user.
"""
return cmd
"""
process is no longer running. Return the lines from the stdout and
stderr Output objects.
"""
res = []
while proc.returncode is None:
"""
This is the main function that runs each individual test.
Determine whether or not the command requires sudo, and modify it
if needed. Run the command, and update the result object.
"""
print self
return
try:
except OSError, e:
fail('%s' % e)
try:
t.start()
except KeyboardInterrupt:
fail('\nRun terminated at user request.')
finally:
t.cancel()
"""
Initialize enough of the test result that we can log a skipped
command.
"""
"""
This function is responsible for writing all output. This includes
the console output, the logfile of all results (with timestamped
merged stdout and stderr), and for each test, the unmodified
"""
if logger is None:
return
# If -q is specified, only print a line for tests that didn't pass.
# This means passing tests need to be logged as DEBUG, or the one
# line summary will only be printed in the logfile for failures.
else:
'post_user']
return "Pathname: %s\nOutputdir: %s\nTimeout: %s\nPre: %s%s\nPost: " \
"""
run if there are any problems.
"""
if not verify_file(f):
" it failed verification." % f)
return False
return False
return True
"""
doesn't pass, skip this Test. Run the post script regardless.
"""
if cont:
else:
tests=None):
return "Pathname: %s\nOutputdir: %s\nTests: %s\nTimeout: %s\n" \
"""
the TestGroup entirely, or simply delete the relevant tests in the
group, if that's all that's required.
"""
# If the pre or post scripts are relative pathnames, convert to
# absolute, so they stand a chance of passing verification.
"Auxiliary script '%s' exists in a different "
return False
if not verify_file(f):
"Auxiliary script '%s' failed verification." %
return False
return False
# If one of the tests is invalid, delete it, log it, and drive on.
"because it failed verification." % (test,
"""
doesn't pass, skip all the tests in this TestGroup. Run the post
script regardless.
"""
if cont:
else:
self.testgroups = {}
('outputdir', BASEDIR),
('quiet', False),
('timeout', 60),
('user', ''),
('pre', ''),
('pre_user', ''),
('post', ''),
('post_user', '')
]
s += 'TESTS:\n'
s += 'TESTGROUPS:\n'
return s
"""
Create a new Test, and apply any properties that were passed in
from the command line. If it passes verification, add it to the
TestRun.
"""
"""
Create a new TestGroup, and apply any properties that were passed
in from the command line. If it passes verification, add it to the
TestRun.
"""
if f in filenames:
"""
Read in the specified runfile, and apply the TestRun properties
listed in the 'DEFAULT' section to our TestRun. Then read each
section, and apply the appropriate properties to the Test or
TestGroup. Properties from individual sections override those set
in the 'DEFAULT' section. If the Test or TestGroup passes
verification, add it to the TestRun.
"""
try:
except ConfigParser.NoOptionError:
pass
# Repopulate tests using eval to convert the string to a list
else:
try:
except ConfigParser.NoOptionError:
pass
"""
Create a configuration file for editing and later use. The
'DEFAULT' section of the config file is created from the
properties that were specified on the command line. Tests are
simply added as sections that inherit everything from the
'DEFAULT' section. TestGroups are the same, except they get an
option including all the tests to run in that directory.
"""
try:
except IOError:
"""
Collect all the pathnames for Tests, and TestGroups. Work
backwards one pathname component at a time, to create a unique
directory name in which to deposit test output. Tests will be able
to write output files directly in the newly modified outputdir.
TestGroups will be able to create one subdirectory per test in the
outputdir, and are guaranteed uniqueness because a group can only
contain files in one directory. Pre and post tests will create a
directory rooted at the outputdir of the Test or TestGroup in
question for their output.
"""
components = 0
while not done:
l = []
components -= 1
if not uniq in l:
else:
break
"""
Two loggers are set up here. The first is for the logfile which
will contain one line summarizing the test, including the test
name, result, and running time. This logger will also capture the
timestamped combined stdout and stderr of each run. The second
logger is optional console output, which will contain only the one
line summary. The loggers are initialized at two different levels
to facilitate segregating the output.
"""
return
try:
except OSError, e:
fail('%s' % e)
return testlogger
"""
Walk through all the Tests and TestGroups, calling run().
"""
try:
except OSError:
return
print '\nResults Summary'
h, m = divmod(m, 60)
print '\nRunning Time:\t%02d:%02d:%02d' % (h, m, s)
def verify_file(pathname):
"""
Verify that the supplied pathname is an executable regular file.
"""
return False
return True
return False
"""
Verify that the specified user exists on this system, and can execute
sudo without being prompted for a password.
"""
return True
try:
except KeyError:
return False
p.wait()
if p.returncode is not 0:
return False
else:
return True
"""
For the given list of pathnames, add files as Tests. For directories,
if do_groups is True, add the directory as a TestGroup. If False,
recursively search for executable files.
"""
else:
else:
fail('-c and -w are mutually exclusive.')
def parse_args():
parser = OptionParser()
help='Specify tests to run via config file.')
help='Dry run. Print tests, but take no other action.')
help='Silence on the console during a test run.')
help='Timeout (in seconds) for an individual test.')
help='Specify a different user name to run as.')
help='Specify a user to execute the pre script.')
help='Specify a user to execute the post script.')
fail('Extraneous arguments.')
return options
options = parse_args()
exit(0)
else:
fail('Unknown command specified')
exit(0)
if __name__ == '__main__':