Merge "Fix up formatting on devguide"
[yardstick.git] / yardstick / network_services / vnf_generic / vnf / prox_vnf.py
1 # Copyright (c) 2017 Intel Corporation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import errno
16 import logging
17 import datetime
18
19 from yardstick.common.process import check_if_process_failed
20 from yardstick.network_services.vnf_generic.vnf.prox_helpers import ProxDpdkVnfSetupEnvHelper
21 from yardstick.network_services.vnf_generic.vnf.prox_helpers import ProxResourceHelper
22 from yardstick.network_services.vnf_generic.vnf.sample_vnf import SampleVNF
23 from yardstick.network_services import constants
24 from yardstick.benchmark.contexts import base as context_base
25
26 LOG = logging.getLogger(__name__)
27
28
29 class ProxApproxVnf(SampleVNF):
30
31     APP_NAME = 'PROX'
32     APP_WORD = 'PROX'
33     PROX_MODE = "Workload"
34     VNF_PROMPT = "PROX started"
35     LUA_PARAMETER_NAME = "sut"
36
37     def __init__(self, name, vnfd, setup_env_helper_type=None, resource_helper_type=None):
38         if setup_env_helper_type is None:
39             setup_env_helper_type = ProxDpdkVnfSetupEnvHelper
40
41         if resource_helper_type is None:
42             resource_helper_type = ProxResourceHelper
43
44         self.prev_packets_in = 0
45         self.prev_packets_sent = 0
46         self.prev_tsc = 0
47         self.tsc_hz = 0
48         super(ProxApproxVnf, self).__init__(name, vnfd, setup_env_helper_type,
49                                             resource_helper_type)
50
51     def _vnf_up_post(self):
52         self.resource_helper.up_post()
53
54     def vnf_execute(self, cmd, *args, **kwargs):
55         # try to execute with socket commands
56         # ignore socket errors, e.g. when using force_quit
57         ignore_errors = kwargs.pop("_ignore_errors", False)
58         try:
59             return self.resource_helper.execute(cmd, *args, **kwargs)
60         except OSError as e:
61             if e.errno in {errno.EPIPE, errno.ESHUTDOWN, errno.ECONNRESET}:
62                 if ignore_errors:
63                     LOG.debug("ignoring vnf_execute exception %s for command %s", e, cmd)
64                 else:
65                     raise
66             else:
67                 raise
68
69     def collect_kpi(self):
70         # we can't get KPIs if the VNF is down
71         check_if_process_failed(self._vnf_process, 0.01)
72
73         physical_node = context_base.Context.get_physical_node_from_server(
74             self.scenario_helper.nodes[self.name])
75
76         result = {"physical_node": physical_node}
77
78         if self.resource_helper is None:
79             result.update({
80                 "packets_in": 0,
81                 "packets_dropped": 0,
82                 "packets_fwd": 0,
83                 "collect_stats": {"core": {}},
84             })
85             return result
86
87         if (self.tsc_hz == 0):
88             self.tsc_hz = float(self.resource_helper.sut.hz())
89             LOG.debug("TSC = %f", self.tsc_hz)
90             if (self.tsc_hz == 0):
91                 raise RuntimeError("Unable to retrieve TSC")
92
93         # use all_ports so we only use ports matched in topology
94         port_count = len(self.vnfd_helper.port_pairs.all_ports)
95         if port_count not in {1, 2, 4}:
96             raise RuntimeError("Failed ..Invalid no of ports .. "
97                                "1, 2 or 4 ports only supported at this time")
98
99         all_port_stats = self.vnf_execute('multi_port_stats', range(port_count))
100         rx_total = tx_total = tsc = 0
101         try:
102             for single_port_stats in all_port_stats:
103                 rx_total = rx_total + single_port_stats[1]
104                 tx_total = tx_total + single_port_stats[2]
105                 tsc = tsc + single_port_stats[5]
106         except (TypeError, IndexError):
107             LOG.error("Invalid data ...")
108             return {}
109
110         tsc = tsc / port_count
111
112         result.update({
113             "packets_in": rx_total,
114             "packets_dropped": max((tx_total - rx_total), 0),
115             "packets_fwd": tx_total,
116             # we share ProxResourceHelper with TG, but we want to collect
117             # collectd KPIs here and not TG KPIs, so use a different method name
118             "collect_stats": self.resource_helper.collect_collectd_kpi(),
119         })
120         try:
121             curr_packets_in = int(((rx_total - self.prev_packets_in) * self.tsc_hz)
122                                 / (tsc - self.prev_tsc))
123         except ZeroDivisionError:
124             LOG.error("Error.... Divide by Zero")
125             curr_packets_in = 0
126
127         try:
128             curr_packets_fwd = int(((tx_total - self.prev_packets_sent) * self.tsc_hz)
129                                 / (tsc - self.prev_tsc))
130         except ZeroDivisionError:
131             LOG.error("Error.... Divide by Zero")
132             curr_packets_fwd = 0
133
134         result["curr_packets_in"] = curr_packets_in
135         result["curr_packets_fwd"] = curr_packets_fwd
136
137         self.prev_packets_in = rx_total
138         self.prev_packets_sent = tx_total
139         self.prev_tsc = tsc
140
141         LOG.debug("%s collect KPIs %s %s", self.APP_NAME, datetime.datetime.now(), result)
142         return result
143
144     def _tear_down(self):
145         # this should be standardized for all VNFs or removed
146         self.setup_helper.tear_down()
147
148     def terminate(self):
149         # stop collectd first or we get pika errors?
150         self.resource_helper.stop_collect()
151         # try to quit with socket commands
152         # pkill is not matching, debug with pgrep
153         self.ssh_helper.execute("sudo pgrep -lax  %s" % self.setup_helper.APP_NAME)
154         self.ssh_helper.execute("sudo ps aux | grep -i %s" % self.setup_helper.APP_NAME)
155         if self._vnf_process.is_alive():
156             self.vnf_execute("stop_all")
157             self.vnf_execute("quit")
158             # hopefully quit succeeds and socket closes, so ignore force_quit socket errors
159             self.vnf_execute("force_quit", _ignore_errors=True)
160         self.setup_helper.kill_vnf()
161         self._tear_down()
162         if self._vnf_process is not None:
163             LOG.debug("joining before terminate %s", self._vnf_process.name)
164             self._vnf_process.join(constants.PROCESS_JOIN_TIMEOUT)
165             self._vnf_process.terminate()