Override default Xtesting logs in cnf-conformance
[functest-kubernetes.git] / functest_kubernetes / cnf_conformance / conformance.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2020 Orange and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 """
11 The CNF Conformance program enables interoperability of Cloud native Network
12 Functions (CNFs) from multiple vendors running on top of Kubernetes supplied by
13 different vendors [1].
14 [1] https://github.com/cncf/cnf-conformance
15 """
16
17 from __future__ import division
18
19 import fnmatch
20 import logging
21 import os
22 import re
23 import shutil
24 import subprocess
25 import time
26 import yaml
27
28 import prettytable
29
30 from xtesting.core import testcase
31
32
33 class CNFConformance(testcase.TestCase):
34     """ Implement CNF Conformance driver.
35
36     https://hackmd.io/@vulk/SkY54QnsU
37     """
38
39     src_dir = '/src/cnf-conformance'
40     bin_dir = '/usr/local/bin'
41     default_tag = 'all'
42
43     __logger = logging.getLogger(__name__)
44
45     def __init__(self, **kwargs):
46         super(CNFConformance, self).__init__(**kwargs)
47         self.output_log_name = 'functest-kubernetes.log'
48         self.output_debug_log_name = 'functest-kubernetes.debug.log'
49
50     def check_requirements(self):
51         """Check if cnf-conformance is in $PATH"""
52         if not os.path.exists(os.path.join(self.bin_dir, 'cnf-conformance')):
53             self.__logger.warning(
54                 "cnf-conformance is not compiled for arm and arm64 for the "
55                 "time being")
56             self.is_skipped = True
57
58     def setup(self):
59         """Implement initialization and pre-reqs steps"""
60         if os.path.exists(self.res_dir):
61             shutil.rmtree(self.res_dir)
62         os.makedirs(self.res_dir)
63         shutil.copy2(os.path.join(self.src_dir, 'points.yml'), self.res_dir)
64         shutil.copy2(
65             os.path.join(self.src_dir, 'cnf-conformance.yml'), self.res_dir)
66         os.chdir(self.res_dir)
67         # cnf-conformance must be in the working dir
68         # https://github.com/cncf/cnf-conformance/issues/388
69         if not os.path.exists(os.path.join(self.res_dir, 'cnf-conformance')):
70             os.symlink(
71                 os.path.join(self.bin_dir, 'cnf-conformance'),
72                 os.path.join(self.res_dir, 'cnf-conformance'))
73         cmd = ['cnf-conformance', 'setup']
74         output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
75         self.__logger.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
76         cmd = ['cnf-conformance', 'cnf_setup',
77                'cnf-config=cnf-conformance.yml']
78         output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
79         self.__logger.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
80
81     def run_conformance(self, **kwargs):
82         """Run CNF Conformance"""
83         # a previous results.yml leads to interactive mode
84         if os.path.exists(os.path.join(self.res_dir, 'results.yml')):
85             os.remove(os.path.join(self.res_dir, 'results.yml'))
86         cmd = ['cnf-conformance', kwargs.get("tag", self.default_tag)]
87         output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
88         self.__logger.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
89         for lfile in os.listdir(self.res_dir):
90             if fnmatch.fnmatch(lfile, 'cnf-conformance-results-*.yml'):
91                 with open(os.path.join(self.res_dir, lfile)) as yfile:
92                     self.details = yaml.safe_load(yfile)
93                     msg = prettytable.PrettyTable(
94                         header_style='upper', padding_width=5,
95                         field_names=['name', 'status'])
96                     for item in self.details['items']:
97                         msg.add_row([item['name'], item['status']])
98                     self.__logger.info("\n\n%s\n", msg.get_string())
99         grp = re.search(r'Final score: (\d+) of (\d+)', output.decode("utf-8"))
100         if grp:
101             self.result = int(grp.group(1)) / int(grp.group(2)) * 100
102
103     def run(self, **kwargs):
104         """"Running the test with example CNF"""
105         self.start_time = time.time()
106         try:
107             self.setup()
108             self.run_conformance(**kwargs)
109         except Exception:  # pylint: disable=broad-except
110             self.__logger.exception("Can not run CNF Conformance")
111         self.stop_time = time.time()
112
113     def clean(self):
114         cmd = ['cnf-conformance', 'cnf_cleanup',
115                'cnf-config=cnf-conformance.yml']
116         output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
117         self.__logger.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
118         shutil.rmtree(os.path.join(self.res_dir, 'tools'), ignore_errors=True)
119         shutil.rmtree(os.path.join(self.res_dir, 'cnfs'), ignore_errors=True)
120         for lfile in os.listdir(self.res_dir):
121             if not fnmatch.fnmatch(lfile, 'cnf-conformance-results-*.yml'):
122                 os.remove(os.path.join(self.res_dir, lfile))