deckard.py 16.1 KB
Newer Older
1
#!/usr/bin/env python
2 3
import argparse
from datetime import datetime
4
import logging
5
import logging.config
Marek Vavruša's avatar
Marek Vavruša committed
6 7 8
import os
import shutil
import socket
9 10 11
import subprocess
import sys
import tempfile
Marek Vavruša's avatar
Marek Vavruša committed
12
import time
13

Marek Vavruša's avatar
Marek Vavruša committed
14
import jinja2
15
import yaml
Marek Vavruša's avatar
Marek Vavruša committed
16

17 18
from pydnstest import scenario, testserver, test

19

20 21
# path to Deckard files
INSTALLDIR = os.path.dirname(os.path.abspath(__file__))
22

Marek Vavruša's avatar
Marek Vavruša committed
23

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
class IfaceManager(object):
    """
    Network interface allocation manager

    Keeps mapping between 'name', interface number, and IP address.
    """
    def __init__(self, sockfamily):
        """
        Parameters:
            sockfamily Address family used in given test scenatio
                       (a constant from socket module)
        """
        if sockfamily not in {socket.AF_INET, socket.AF_INET6}:
            raise NotImplementedError("address family not supported '%i'" % sockfamily)
        self.sockfamily = sockfamily
        self.free = list(range(40, 10, -1))  # range accepted by libswrap
        self.name2iface = {}

    def allocate(self, name):
        """
        Map name to a free interface number.
        """
        if name in self.name2iface:
            raise ValueError('duplicate interface name %s' % name)
        iface = str(self.free.pop())
        self.name2iface[name] = iface
        return iface

    def getiface(self, name):
        """
        Map name to allocated interface number.

        Returns:
            Interface number as string (so it can be assigned to os.environ)
        """
        return self.name2iface[name]

    def getipaddr(self, name):
        """
        Get default IP address assigned to interface allocated to given name.

        Returns:
            Address from address family specified during IfaceManager init.
        """
        iface = self.getiface(name)
        if self.sockfamily == socket.AF_INET:
            addr_local_pattern = "127.0.0.{}"
        elif self.sockfamily == socket.AF_INET6:
            addr_local_pattern = "fd00::5357:5f{:02X}"
        return addr_local_pattern.format(int(iface))

    def getalladdrs(self):
        """
        Get mapping from all names to all IP addresses.

        Returns:
            {name: IP address}
        """
        return {name: self.getipaddr(name)
                for name in self.name2iface}
Marek Vavruša's avatar
Marek Vavruša committed
84

Marek Vavrusa's avatar
Marek Vavrusa committed
85

Marek Vavruša's avatar
Marek Vavruša committed
86 87 88 89 90 91 92 93 94 95 96
def find_objects(path):
    """ Recursively scan file/directory for scenarios. """
    result = []
    if os.path.isdir(path):
        for e in os.listdir(path):
            result += find_objects(os.path.join(path, e))
    elif os.path.isfile(path):
        if path.endswith('.rpl'):
            result.append(path)
    return result

97

Marek Vavruša's avatar
Marek Vavruša committed
98 99
def write_timestamp_file(path, tst):
    time_file = open(path, 'w')
100 101
    time_file.write(datetime.fromtimestamp(tst).strftime('@%Y-%m-%d %H:%M:%S'))
    time_file.flush()
Marek Vavruša's avatar
Marek Vavruša committed
102 103
    time_file.close()

104

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
def setup_common_env(ctx):
    """
    Setup environment shared between Deckard and binaries under test.

    Environment for child processes must be based on on.environ as modified
    by this function.

    Returns:
        path to working directory
    """
    # working directory
    if "SOCKET_WRAPPER_DIR" in os.environ:
        tmpdir = os.environ["SOCKET_WRAPPER_DIR"]
        if os.path.lexists(tmpdir):
            raise ValueError('SOCKET_WRAPPER_DIR "%s" must not exist' % tmpdir)
    else:
        tmpdir = tempfile.mkdtemp(suffix='', prefix='tmpdeckard')

Marek Vavruša's avatar
Marek Vavruša committed
123 124
    # Set up libfaketime
    os.environ["FAKETIME_NO_CACHE"] = "1"
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    os.environ["FAKETIME_TIMESTAMP_FILE"] = '%s/.time' % tmpdir
    # fake initial time
    write_timestamp_file(os.environ["FAKETIME_TIMESTAMP_FILE"],
                         ctx.get('_OVERRIDE_TIMESTAMP', time.time()))

    # Set up socket_wrapper
    os.environ["SOCKET_WRAPPER_DIR"] = tmpdir
    os.environ["SOCKET_WRAPPER_PCAP_FILE"] = '%s/deckard.pcap' % tmpdir

    return tmpdir


def setup_daemon_env(prog_cfg, tmpdir):
    """ Set up test environment and config """
    name = prog_cfg['name']
    log = logging.getLogger('deckard.daemon.%s.setup_env' % name)
    # Set up child process env() to use socket wrapper interface
    child_env = os.environ.copy()
    child_env['SOCKET_WRAPPER_DEFAULT_IFACE'] = prog_cfg['iface']
    prog_cfg['dir'] = os.path.join(tmpdir, name)
    log.debug('directory: %s', prog_cfg['dir'])
    child_env['SOCKET_WRAPPER_PCAP_FILE'] = '%s/pcap' % prog_cfg['dir']

    return child_env


def setup_network(sockfamily, prog_cfgs):
    """Allocate fake interfaces and IP addresses to all entities.

    Returns:
    - SOCKET_WRAPPER_DEFAULT_IFACE will be set in os.environ
    - Dict suitable for usage in Jinja2 templates will be returned
        {
         ROOT_ADDR: <DeckardIP>,
         IPADDRS: {name: <IPaddress>}
        }
    """
    net_config = {}
    # assign interfaces and IP addresses to all involved programs
    ifacemgr = IfaceManager(sockfamily)
    # fake interface for Deckard itself
    deckard_iface = ifacemgr.allocate('deckard')
    os.environ['SOCKET_WRAPPER_DEFAULT_IFACE'] = deckard_iface
    net_config['ROOT_ADDR'] = ifacemgr.getipaddr('deckard')

    for prog_cfg in prog_cfgs['programs']:
        prog_cfg['iface'] = ifacemgr.allocate(prog_cfg['name'])
        prog_cfg['ipaddr'] = ifacemgr.getipaddr(prog_cfg['name'])
    net_config['IPADDRS'] = ifacemgr.getalladdrs()

    return net_config


def _fixme_prebind_hack(sockfamily, childaddr):
    """
    Prebind to sockets to create necessary files

    @TODO: this is probably a workaround for socket_wrapper bug
    """
184 185
    if 'NOPRELOAD' not in os.environ:
        for sock_type in (socket.SOCK_STREAM, socket.SOCK_DGRAM):
186 187
            sock = socket.socket(sockfamily, sock_type)
            sock.setsockopt(sockfamily, socket.SO_REUSEADDR, 1)
188
            sock.bind((childaddr, 53))
189
            if sock_type & socket.SOCK_STREAM:
190
                sock.listen(5)
Marek Vavruša's avatar
Marek Vavruša committed
191

192

193
def setup_daemon_files(prog_cfg, template_ctx):
194 195 196 197
    name = prog_cfg['name']
    # add program-specific variables
    subst = template_ctx.copy()
    subst['DAEMON_NAME'] = name
Marek Vavruša's avatar
Marek Vavruša committed
198

199 200
    subst['WORKING_DIR'] = prog_cfg['dir']
    os.mkdir(prog_cfg['dir'])
Marek Vavruša's avatar
Marek Vavruša committed
201

202
    subst['SELF_ADDR'] = prog_cfg['ipaddr']
203

204 205 206 207
    # generate configuration files
    j2template_loader = jinja2.FileSystemLoader(
        searchpath=os.path.dirname(os.path.abspath(__file__)))
    j2template_env = jinja2.Environment(loader=j2template_loader)
208
    logging.getLogger('deckard.daemon.%s.template' % name).debug(subst)
209

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    assert len(prog_cfg['templates']) == len(prog_cfg['configs'])
    for template_name, config_name in zip(prog_cfg['templates'], prog_cfg['configs']):
        j2template = j2template_env.get_template(template_name)
        cfg_rendered = j2template.render(subst)
        with open(os.path.join(prog_cfg['dir'], config_name), 'w') as output:
            output.write(cfg_rendered)

    _fixme_prebind_hack(template_ctx['_SOCKET_FAMILY'], subst['SELF_ADDR'])


def run_daemon(cfg, environ):
    """Start binary and return its process object"""
    name = cfg['name']
    proc = None
    cfg['log'] = os.path.join(cfg['dir'], 'server.log')
    daemon_log_file = open(cfg['log'], 'w')
    cfg['args'] = args = [cfg['binary']] + cfg['additional']
    logging.getLogger('deckard.daemon.%s.env' % name).debug('%s', environ)
    logging.getLogger('deckard.daemon.%s.argv' % name).debug('%s', args)
229
    try:
230 231 232 233 234 235 236 237 238 239 240 241
        proc = subprocess.Popen(args, stdout=daemon_log_file, stderr=subprocess.STDOUT,
                                cwd=cfg['dir'], preexec_fn=os.setsid, env=environ)
    except subprocess.CalledProcessError:
        logger = logging.getLogger('deckard.daemon_log.%s' % name)
        logger.exception("Can't start '%s'", args)
        raise
    return proc


def conncheck_daemon(process, cfg, sockfamily):
    """Wait until the server accepts TCP clients"""
    sock = socket.socket(sockfamily, socket.SOCK_STREAM)
Marek Vavruša's avatar
Marek Vavruša committed
242
    while True:
243
        time.sleep(0.1)
244 245 246 247 248 249
        if process.poll():
            msg = 'process died "%s", logs in "%s"' % (cfg['name'], cfg['dir'])
            logger = logging.getLogger('deckard.daemon_log.%s' % cfg['name'])
            logger.critical(msg)
            logger.error(open(cfg['log']).read())
            raise subprocess.CalledProcessError(process.returncode, cfg['args'], msg)
Marek Vavruša's avatar
Marek Vavruša committed
250
        try:
251
            sock.connect((cfg['ipaddr'], 53))
252
        except socket.error:
253
            continue
Marek Vavruša's avatar
Marek Vavruša committed
254
        break
255 256
    sock.close()

257

258 259
def process_file(path, args, prog_cfgs):
    """Parse scenario from a file object and create workdir."""
260
    # Parse scenario
261
    case, cfg_text = scenario.parse_file(os.path.realpath(path))
262 263 264 265
    cfg_ctx = scenario.parse_config(cfg_text, args.qmin, INSTALLDIR)
    template_ctx = setup_network(cfg_ctx['_SOCKET_FAMILY'], prog_cfgs)
    # merge variables from scenario with generated network variables (scenario has priority)
    template_ctx.update(cfg_ctx)
266 267 268
    # Deckard will communicate with first program
    prog_under_test = prog_cfgs['programs'][0]['name']
    prog_under_test_ip = template_ctx['IPADDRS'][prog_under_test]
269

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    # get working directory and environment variables
    tmpdir = setup_common_env(cfg_ctx)
    try:
        daemons = setup_daemons(tmpdir, prog_cfgs, template_ctx)
        run_testcase(daemons,
                     case,
                     template_ctx['ROOT_ADDR'],
                     template_ctx['_SOCKET_FAMILY'],
                     prog_under_test_ip)
        shutil.rmtree(tmpdir)
    except:
        logging.getLogger('deckard.hint').info(
            'test failed, inspect working directory %s', tmpdir)
        raise


def setup_daemons(tmpdir, prog_cfgs, template_ctx):
    """Configure daemons and run the test"""
288 289 290 291
    # Setup daemon environment
    daemons = []
    for prog_cfg in prog_cfgs['programs']:
        daemon_env = setup_daemon_env(prog_cfg, tmpdir)
292
        setup_daemon_files(prog_cfg, template_ctx)
293 294 295
        daemon_proc = run_daemon(prog_cfg, daemon_env)
        daemons.append({'proc': daemon_proc, 'cfg': prog_cfg})
        conncheck_daemon(daemon_proc, prog_cfg, template_ctx['_SOCKET_FAMILY'])
296
    return daemons
297

298 299 300 301

def run_testcase(daemons, case, root_addr, addr_family, prog_under_test_ip):
    """Run actual test and raise exception if the test failed"""
    server = testserver.TestServer(case, root_addr, addr_family)
302 303
    server.start()

Marek Vavruša's avatar
Marek Vavruša committed
304
    try:
305
        server.play(prog_under_test_ip)
Marek Vavruša's avatar
Marek Vavruša committed
306 307
    finally:
        server.stop()
308 309 310 311 312 313 314 315 316 317 318
        for daemon in daemons:
            daemon['proc'].terminate()
            daemon['proc'].wait()
            daemon_logger_log = logging.getLogger('deckard.daemon_log.%s' % daemon['cfg']['name'])
            with open(daemon['cfg']['log']) as logf:
                for line in logf:
                    daemon_logger_log.debug(line.strip())
            ignore_exit = bool(os.environ.get('IGNORE_EXIT_CODE', 0))
            if daemon['proc'].returncode != 0 and not ignore_exit:
                raise ValueError('process %s terminated with return code %s'
                                 % (daemon['cfg']['name'], daemon['proc'].returncode))
Marek Vavruša's avatar
Marek Vavruša committed
319
    # Do not clear files if the server crashed (for analysis)
320 321
    if server.undefined_answers > 0:
        raise ValueError('the scenario does not define all necessary answers (see error log)')
Marek Vavruša's avatar
Marek Vavruša committed
322

323

324
def test_platform():
Marek Vavruša's avatar
Marek Vavruša committed
325
    if sys.platform == 'windows':
326
        raise NotImplementedError('not supported at all on Windows')
Marek Vavruša's avatar
Marek Vavruša committed
327

328 329

def deckard():
330
    # auxilitary classes for argparse
331 332 333 334
    class ColonSplitter(argparse.Action):  # pylint: disable=too-few-public-methods
        """Split argument string into list holding items separated by colon."""
        def __call__(self, parser, namespace, values, option_string=None):
            setattr(namespace, self.dest, values.split(':'))
Marek Vavruša's avatar
Marek Vavruša committed
335

336 337 338 339 340 341 342 343 344 345 346 347
    class EnvDefault(argparse.Action):  # pylint: disable=too-few-public-methods
        """Get default value for parameter from environment variable."""
        def __init__(self, envvar, required=True, default=None, **kwargs):
            if envvar and envvar in os.environ:
                default = os.environ[envvar]
            if required and default is not None:
                required = False
            super(EnvDefault, self).__init__(default=default, required=required, **kwargs)

        def __call__(self, parser, namespace, values, option_string=None):
            setattr(namespace, self.dest, values)

348 349 350 351 352 353 354 355 356 357 358
    def loglevel2number(level):
        """Convert direct log level number or symbolic name to a number."""
        try:
            return int(level)
        except ValueError:
            pass  # not a number, try if it is a named constant from logging module
        try:
            return getattr(logging, level.upper())
        except AttributeError:
            raise ValueError('unknown log level %s' % level)

359 360
    test_platform()

361
    argparser = argparse.ArgumentParser()
362
    argparser.add_argument('--qmin', help='query minimization (default: enabled)', default=True,
363
                           action=EnvDefault, envvar='QMIN', type=scenario.str2bool)
364 365 366
    argparser.add_argument('--loglevel', help='verbosity (default: errors + test results)',
                           action=EnvDefault, envvar='VERBOSE',
                           type=loglevel2number, required=False)
367
    argparser.add_argument('scenario', help='path to test scenario')
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

    subparsers = argparser.add_subparsers(
        dest='cmd', title='sub-commands',
        description='run scenario with one binary specified on command line '
                    'or multiple binaries specified in config file')

    run_one = subparsers.add_parser('one', help='run single binary inside single scenario')
    run_one.add_argument('binary', help='executable to test')
    run_one.add_argument('templates', help='colon-separated list of jinja2 template files',
                         action=ColonSplitter)
    run_one.add_argument('configs',
                         help='colon-separated list of files to be generated from templates',
                         action=ColonSplitter)
    run_one.add_argument('additional', help='additional parameters for the binary', nargs='*')

    run_cfg = subparsers.add_parser(
        'multiple',
        help='run all binaries specified in YaML file; '
             'all binaries will be executed inside single scenario')
    run_cfg.add_argument('yaml', help='YaML specifying binaries and their parameter',
                         type=open)
389 390
    args = argparser.parse_args()

391 392 393 394 395 396 397 398
    if not args.loglevel:
        # default verbosity: errors + test results
        args.loglevel = logging.ERROR
        logging.config.dictConfig(
            {
                'version': 1,
                'incremental': True,
                'loggers': {
399
                    'deckard.hint': {'level': 'INFO'},
400 401 402 403 404 405 406 407 408 409
                    'pydnstest.test.Test': {'level': 'INFO'}
                }
            })

    if args.loglevel <= logging.DEBUG:  # include message origin
        logging.basicConfig(level=args.loglevel)
    else:
        logging.basicConfig(level=args.loglevel, format='%(message)s')
    log = logging.getLogger('deckard')

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    if args.cmd == 'multiple':
        config = yaml.load(args.yaml)
    else:
        assert args.cmd == 'one'
        config = {
            'programs': [{
                'binary': args.binary,
                'templates': args.templates,
                'configs': args.configs,
                'additional': args.additional,
                'name': os.path.basename(args.binary),
            }]}

    mandatory_keys = {'name', 'binary', 'templates', 'configs', 'additional'}
    for cfg in config['programs']:
        missing_keys = mandatory_keys - set(cfg.keys())
        if missing_keys:
            log.critical('Mandatory fields in configuration are missing: %s', missing_keys)
            sys.exit(1)

        # sanity check templates vs. configs
        if len(cfg['templates']) != len(cfg['configs']):
            log.critical('Number of jinja2 template files is not equal '
                         'to number of config files to be generated for '
                         'program "%s", i.e. len(templates) != len(configs)',
                         cfg['name'])
            sys.exit(1)
Marek Vavruša's avatar
Marek Vavruša committed
437 438

    # Scan for scenarios
439
    testset = test.Test()
440 441
    objects = find_objects(args.scenario)
    for path in objects:
442
        testset.add(path, process_file, args, config)
443 444 445 446 447 448
    sys.exit(testset.run())


if __name__ == '__main__':
    # this is done to avoid creating global variables
    deckard()