#!/usr/bin/env python3 from __future__ import print_function import gc import logging import sys import os import select import signal import subprocess import unittest import tempfile import time import faulthandler import random import copy import psutil import platform from collections import deque from threading import Thread, Event from inspect import getdoc, isclass from traceback import format_exception from logging import FileHandler, DEBUG, Formatter from enum import Enum from abc import ABC, abstractmethod from struct import pack, unpack import scapy.compat from scapy.packet import Raw import hook as hookmodule from vpp_pg_interface import VppPGInterface from vpp_sub_interface import VppSubInterface from vpp_lo_interface import VppLoInterface from vpp_bvi_interface import VppBviInterface from vpp_papi_provider import VppPapiProvider from vpp_papi import VppEnum import vpp_papi from vpp_papi.vpp_stats import VPPStats from vpp_papi.vpp_transport_socket import VppTransportSocketIOError from log import RED, GREEN, YELLOW, double_line_delim, single_line_delim, \ get_logger, colorize from vpp_object import VppObjectRegistry from util import ppp, is_core_present from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror from scapy.layers.inet6 import ICMPv6DestUnreach, ICMPv6EchoRequest from scapy.layers.inet6 import ICMPv6EchoReply from cpu_config import available_cpus, num_cpus, max_vpp_cpus logger = logging.getLogger(__name__) # Set up an empty logger for the testcase that can be overridden as necessary null_logger = logging.getLogger('VppTestCase') null_logger.addHandler(logging.NullHandler()) PASS = 0 FAIL = 1 ERROR = 2 SKIP = 3 TEST_RUN = 4 SKIP_CPU_SHORTAGE = 5 class BoolEnvironmentVariable(object): def __init__(self, env_var_name, default='n', true_values=None): self.name = env_var_name self.default = default self.true_values = true_values if true_values is not None else \ ("y", "yes", "1") def __bool__(self): return os.getenv(self.name, self.default).lower() in self.true_values if sys.version_info[0] == 2: __nonzero__ = __bool__ def __repr__(self): return 'BoolEnvironmentVariable(%r, default=%r, true_values=%r)' % \ (self.name, self.default, self.true_values) debug_framework = BoolEnvironmentVariable('TEST_DEBUG') if debug_framework: import debug_internal """ Test framework module. The module provides a set of tools for constructing and running tests and representing the results. """ class VppDiedError(Exception): """ exception for reporting that the subprocess has died.""" signals_by_value = {v: k for k, v in signal.__dict__.items() if k.startswith('SIG') and not k.startswith('SIG_')} def __init__(self, rv=None, testcase=None, method_name=None): self.rv = rv self.signal_name = None self.testcase = testcase self.method_name = method_name try: self.signal_name = VppDiedError.signals_by_value[-rv] except (KeyError, TypeError): pass if testcase is None and method_name is None: in_msg = '' else: in_msg = ' while running %s.%s' % (testcase, method_name) if self.rv: msg = "VPP subprocess died unexpectedly%s with return code: %d%s."\ % (in_msg, self.rv, ' [%s]' % (self.signal_name if self.signal_name is not None else '')) else: msg = "VPP subprocess died unexpectedly%s." % in_msg super(VppDiedError, self).__init__(msg) class _PacketInfo(object): """Private class to create packet info object. Help process information about the next packet. Set variables to default values. """ #: Store the index of the packet. index = -1 #: Store the index of the source packet generator interface of the packet. src = -1 #: Store the index of the destination packet generator interface #: of the packet. dst = -1 #: Store expected ip version ip = -1 #: Store expected upper protocol proto = -1 #: Store the copy of the former packet. data = None def __eq__(self, other): index = self.index == other.index src = self.src == other.src dst = self.dst == other.dst data = self.data == other.data return index and src and dst and data def pump_output(testclass): """ pump output from vpp stdout/stderr to proper queues """ stdout_fragment = "" stderr_fragment = "" while not testclass.pump_thread_stop_flag.is_set(): readable = select.select([testclass.vpp.stdout.fileno(), testclass.vpp.stderr.fileno(), testclass.pump_thread_wakeup_pipe[0]], [], [])[0] if testclass.vpp.stdout.fileno() in readable: read = os.read(testclass.vpp.stdout.fileno(), 102400) if len(read) > 0: split = read.decode('ascii', errors='backslashreplace').splitlines(True) if len(stdout_fragment) > 0: split[0] = "%s%s" % (stdout_fragment, split[0]) if len(split) > 0 and split[-1].endswith("\n"): limit = None else: limit = -1 stdout_fragment = split[-1] testclass.vpp_stdout_deque.extend(split[:limit]) if not testclass.cache_vpp_output: for line in split[:limit]: testclass.logger.info( "VPP STDOUT: %s" % line.rstrip("\n")) if testclass.vpp.stderr.fileno() in readable: read = os.read(testclass.vpp.stderr.fileno(), 102400) if len(read) > 0: split = read.decode('ascii', errors='backslashreplace').splitlines(True) if len(stderr_fragment) > 0: split[0] = "%s%s" % (stderr_fragment, split[0]) if len(split) > 0 and split[-1].endswith("\n"): limit = None else: limit = -1 stderr_fragment = split[-1] testclass.vpp_stderr_deque.extend(split[:limit]) if not testclass.cache_vpp_output: for line in split[:limit]: testclass.logger.error( "VPP STDERR: %s" % line.rstrip("\n")) # ignoring the dummy pipe here intentionally - the # flag will take care of properly terminating the loop def _is_skip_aarch64_set(): return BoolEnvironmentVariable('SKIP_AARCH64') is_skip_aarch64_set = _is_skip_aarch64_set() def _is_platform_aarch64(): return platform.machine() == 'aarch64' is_platform_aarch64 = _is_platform_aarch64() def _running_extended_tests(): return BoolEnvironmentVariable("EXTENDED_TESTS") running_extended_tests = _running_extended_tests() def _running_gcov_tests(): return BoolEnvironmentVariable("GCOV_TESTS") running_gcov_tests = _running_gcov_tests() def get_environ_vpp_worker_count(): worker_config = os.getenv("VPP_WORKER_CONFIG", None) if worker_config: elems = worker_config.split(" ") if elems[0] != "workers" or len(elems) != 2: raise ValueError("Wrong VPP_WORKER_CONFIG == '%s' value." % worker_config) return int(elems[1]) else: return 0 environ_vpp_worker_count = get_environ_vpp_worker_count() class KeepAliveReporter(object): """ Singleton object which reports test start to parent process """ _shared_state = {} def __init__(self): self.__dict__ = self._shared_state self._pipe = None @property def pipe(self): return self._pipe @pipe.setter def pipe(self, pipe): if self._pipe is not None: raise Exception("Internal error - pipe should only be set once.") self._pipe = pipe def send_keep_alive(self, test, desc=None): """ Write current test tmpdir & desc to keep-alive pipe to signal liveness """ if self.pipe is None: # if not running forked.. return if isclass(test): desc = '%s (%s)' % (desc, unittest.util.strclass(test)) else: desc = test.id() self.pipe.send((desc, test.vpp_bin, test.tempdir, test.vpp.pid)) class TestCaseTag(Enum): # marks the suites that must run at the end # using only a single test runner RUN_SOLO = 1 # marks the suites broken on VPP multi-worker FIXME_VPP_WORKERS = 2 def create_tag_decorator(e): def decorator(cls): try: cls.test_tags.append(e) except AttributeError: cls.test_tags = [e] return cls return decorator tag_run_solo = create_tag_decorator(TestCaseTag.RUN_SOLO) tag_fixme_vpp_workers = create_tag_decorator(TestCaseTag.FIXME_VPP_WORKERS) class DummyVpp: returncode = None pid = 0xcafebafe def poll(self): pass def terminate(self): pass class CPUInterface(ABC): cpus = [] skipped_due_to_cpu_lack = False @classmethod @abstractmethod def get_cpus_required(cls): pass @classmethod def assign_cpus(cls, cpus): cls.cpus = cpus class VppTestCase(CPUInterface, unittest.TestCase): """This subclass is a base class for VPP test cases that are implemented as classes. It provides methods to create and run test case. """ extra_vpp_statseg_config = "" extra_vpp_punt_config = [] extra_vpp_plugin_config = [] logger = null_logger vapi_response_timeout = 5 @property def packet_infos(self): """List of packet infos""" return self._packet_infos @classmethod def get_packet_count_for_if_idx(cls, dst_if_index): """Get the number of packet info for specified destination if index""" if dst_if_index in cls._packet_count_for_dst_if_idx: return cls._packet_count_for_dst_if_idx[dst_if_index] else: return 0 @classmethod def has_tag(cls, tag): """ if the test case has a given tag - return true """ try: return tag in cls.test_tags except AttributeError: pass return False @classmethod def is_tagged_run_solo(cls): """ if the test case class is timing-sensitive - return true """ return cls.has_tag(TestCaseTag.RUN_SOLO) @classmethod def instance(cls): """Return the instance of this testcase""" return cls.test_instance @classmethod def set_debug_flags(cls, d): cls.gdbserver_port = 7777 cls.debug_core = False cls.debug_gdb = False cls.debug_gdbserver = False cls.debug_all = False cls.debug_attach = False if d is None: return dl = d.lower() if dl == "core": cls.debug_core = True elif dl == "gdb" or dl == "gdb-all": cls.debug_gdb = True elif dl == "gdbserver" or dl == "gdbserver-all": cls.debug_gdbserver = True elif dl == "attach": cls.debug_attach = True else: raise Exception("Unrecognized DEBUG option: '%s'" % d) if dl == "gdb-all" or dl == "gdbserver-all": cls.debug_all = True @classmethod def get_vpp_worker_count(cls): if not hasattr(cls, "vpp_worker
# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Bump regularly.
tox==3.7.0
# Tox dependencies. Consult "pip freeze" after installing
# bumped tox into an empty virtualenv.
filelock==3.0.10
pluggy==0.8.1
py==1.7.0
six==1.12.0
toml==0.10.0
virtualenv==16.4.0