1 # Copyright (c) 2016-2017 Intel Corporation
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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 """ Resource collection definitions """
17 from itertools import chain
19 import multiprocessing
26 from oslo_config import cfg
27 from oslo_utils.encodeutils import safe_decode
29 from yardstick import ssh
30 from yardstick.common.exceptions import ResourceCommandError
31 from yardstick.common.task_template import finalize_for_yaml
32 from yardstick.common.utils import validate_non_string_sequence
33 from yardstick.network_services.nfvi.collectd import AmqpConsumer
36 LOG = logging.getLogger(__name__)
40 ZMQ_POLLING_TIME = 12000
41 LIST_PLUGINS_ENABLED = ["amqp", "cpu", "cpufreq", "memory",
45 class ResourceProfile(object):
47 This profile adds a resource at the beginning of the test session
49 COLLECTD_CONF = "collectd.conf"
52 DEFAULT_TIMEOUT = 3600
53 OVS_SOCKET_PATH = "/usr/local/var/run/openvswitch/db.sock"
55 def __init__(self, mgmt, port_names=None, plugins=None, interval=None, timeout=None):
60 self.plugins = plugins
63 self.interval = self.DEFAULT_INTERVAL
65 self.interval = interval
68 self.timeout = self.DEFAULT_TIMEOUT
70 self.timeout = timeout
73 self._queue = multiprocessing.Queue()
74 self.amqp_client = None
75 self.port_names = validate_non_string_sequence(port_names, default=[])
77 # we need to save mgmt so we can connect to port 5672
79 self.connection = ssh.AutoConnectSSH.from_node(mgmt)
82 def make_from_node(cls, node, timeout):
83 # node dict works as mgmt dict
84 # don't need port names, there is no way we can
85 # tell what port is used on the compute node
86 collectd_options = node["collectd"]
87 plugins = collectd_options.get("plugins", {})
88 interval = collectd_options.get("interval")
90 return cls(node, plugins=plugins, interval=interval, timeout=timeout)
92 def check_if_system_agent_running(self, process):
93 """ verify if system agent is running """
95 err, pid, _ = self.connection.execute("pgrep -f %s" % process)
97 return err, pid.strip()
99 if e.errno in {errno.ECONNRESET}:
100 # if we can't connect to check, then we won't be able to connect to stop it
101 LOG.exception("Can't connect to host to check %s status", process)
105 def run_collectd_amqp(self):
106 """ run amqp consumer to collect the NFVi data """
107 amqp_url = 'amqp://admin:admin@{}:{}/%2F'.format(self.mgmt['ip'], self.AMPQ_PORT)
108 amqp = AmqpConsumer(amqp_url, self._queue)
111 except (AttributeError, RuntimeError, KeyboardInterrupt):
115 def parse_simple_resource(cls, key, value):
116 reskey = "/".join(rkey for rkey in key if "nsb_stats" not in rkey)
117 return {reskey: value.split(":")[1]}
120 def get_cpu_data(cls, res_key0, res_key1, value):
121 """ Get cpu topology of the host """
124 if 'cpufreq' in res_key0:
125 metric, source = res_key0, res_key1
127 metric, source = res_key1, res_key0
129 match = re.search(pattern, source, re.MULTILINE)
131 return "error", "Invalid", "", ""
133 time, value = value.split(":")
134 return str(match.group(1)), metric, value, time
137 def parse_hugepages(cls, key, value):
138 return cls.parse_simple_resource(key, value)
141 def parse_dpdkstat(cls, key, value):
142 return cls.parse_simple_resource(key, value)
145 def parse_virt(cls, key, value):
146 return cls.parse_simple_resource(key, value)
149 def parse_ovs_stats(cls, key, value):
150 return cls.parse_simple_resource(key, value)
153 def parse_intel_pmu_stats(cls, key, value):
154 return {''.join(str(v) for v in key): value.split(":")[1]}
156 def parse_collectd_result(self, metrics):
157 """ convert collectd data into json"""
169 decoded = ((safe_decode(k, 'utf-8'), safe_decode(v, 'utf-8')) for k, v in metrics.items())
170 for key, value in decoded:
171 key_split = key.split("/")
172 res_key_iter = (key for key in key_split if "nsb_stats" not in key)
173 res_key0 = next(res_key_iter)
174 res_key1 = next(res_key_iter)
176 if "cpu" in res_key0 or "intel_rdt" in res_key0 or "intel_pmu" in res_key0:
177 cpu_key, name, metric, testcase = \
178 self.get_cpu_data(res_key0, res_key1, value)
179 result["cpu"].setdefault(cpu_key, {}).update({name: metric})
181 elif "memory" in res_key0:
182 result["memory"].update({res_key1: value.split(":")[0]})
184 elif "hugepages" in res_key0:
185 result["hugepages"].update(self.parse_hugepages(key_split, value))
187 elif "dpdkstat" in res_key0:
188 result["dpdkstat"].update(self.parse_dpdkstat(key_split, value))
190 elif "virt" in res_key1:
191 result["virt"].update(self.parse_virt(key_split, value))
193 elif "ovs_stats" in res_key0:
194 result["ovs_stats"].update(self.parse_ovs_stats(key_split, value))
196 result["timestamp"] = testcase
200 def amqp_process_for_nfvi_kpi(self):
201 """ amqp collect and return nfvi kpis """
202 if self.amqp_client is None and self.enable:
203 self.amqp_client = multiprocessing.Process(
204 name="AmqpClient-{}-{}".format(self.mgmt['ip'], os.getpid()),
205 target=self.run_collectd_amqp)
206 self.amqp_client.start()
208 def amqp_collect_nfvi_kpi(self):
209 """ amqp collect and return nfvi kpis """
214 while not self._queue.empty():
215 metric.update(self._queue.get())
216 msg = self.parse_collectd_result(metric)
219 def _provide_config_file(self, config_file_path, nfvi_cfg, template_kwargs):
220 template = pkg_resources.resource_string("yardstick.network_services.nfvi",
221 nfvi_cfg).decode('utf-8')
222 cfg_content = jinja2.Template(template, trim_blocks=True, lstrip_blocks=True,
223 finalize=finalize_for_yaml).render(
225 # cfg_content = io.StringIO(template.format(**template_kwargs))
226 cfg_file = os.path.join(config_file_path, nfvi_cfg)
227 # must write as root, so use sudo
228 self.connection.execute("cat | sudo tee {}".format(cfg_file), stdin=cfg_content)
230 def _prepare_collectd_conf(self, config_file_path):
231 """ Prepare collectd conf """
234 "interval": self.interval,
235 "loadplugins": set(chain(LIST_PLUGINS_ENABLED, self.plugins.keys())),
236 # Optional fields PortName is descriptive only, use whatever is present
237 "port_names": self.port_names,
238 # "ovs_bridge_interfaces": ["br-int"],
239 "plugins": self.plugins,
241 self._provide_config_file(config_file_path, self.COLLECTD_CONF, kwargs)
243 def _setup_ovs_stats(self, connection):
245 socket_path = self.plugins["ovs_stats"].get("ovs_socket_path", self.OVS_SOCKET_PATH)
247 # ovs_stats is not a dict
248 socket_path = self.OVS_SOCKET_PATH
249 status = connection.execute("test -S {}".format(socket_path))[0]
251 LOG.error("cannot find OVS socket %s", socket_path)
253 def _start_rabbitmq(self, connection):
255 LOG.debug("reset and setup amqp to collect data from collectd")
256 # ensure collectd.conf.d exists to avoid error/warning
257 cmd_list = ["sudo mkdir -p /etc/collectd/collectd.conf.d",
258 "sudo service rabbitmq-server restart",
259 "sudo rabbitmqctl stop_app",
260 "sudo rabbitmqctl reset",
261 "sudo rabbitmqctl start_app",
262 "sudo rabbitmqctl add_user admin admin",
263 "sudo rabbitmqctl authenticate_user admin admin",
264 "sudo rabbitmqctl set_permissions -p / admin '.*' '.*' '.*'"
267 exit_status, stdout, stderr = connection.execute(cmd)
269 raise ResourceCommandError(command=cmd, stderr=stderr)
271 # check stdout for "sudo rabbitmqctl status" command
272 cmd = "sudo rabbitmqctl status"
273 _, stdout, stderr = connection.execute(cmd)
274 if not re.search("RabbitMQ", stdout):
275 LOG.error("rabbitmqctl status don't have RabbitMQ in running apps")
276 raise ResourceCommandError(command=cmd, stderr=stderr)
278 def _start_collectd(self, connection, bin_path):
279 LOG.debug("Starting collectd to collect NFVi stats")
280 collectd_path = os.path.join(bin_path, "collectd", "sbin", "collectd")
281 config_file_path = os.path.join(bin_path, "collectd", "etc")
282 self._prepare_collectd_conf(config_file_path)
284 connection.execute('sudo pkill -x -9 collectd')
285 exit_status = connection.execute("which %s > /dev/null 2>&1" % collectd_path)[0]
287 LOG.warning("%s is not present disabling", collectd_path)
289 if "ovs_stats" in self.plugins:
290 self._setup_ovs_stats(connection)
292 LOG.debug("Starting collectd to collect NFVi stats")
293 LOG.debug("Start collectd service..... %s second timeout", self.timeout)
294 # intel_pmu plug requires large numbers of files open, so try to set
295 # ulimit -n to a large value
296 connection.execute("sudo bash -c 'ulimit -n 1000000 ; %s'" % collectd_path,
297 timeout=self.timeout)
300 def initiate_systemagent(self, bin_path):
301 """ Start system agent for NFVi collection on host """
304 self._start_rabbitmq(self.connection)
305 self._start_collectd(self.connection, bin_path)
306 except ResourceCommandError as e:
307 LOG.exception("Exception during collectd and rabbitmq start: %s", str(e))
311 """ start nfvi collection """
313 LOG.debug("Start NVFi metric collection...")
316 """ stop nfvi collection """
321 LOG.debug("Stop resource monitor...")
323 if self.amqp_client is not None:
324 # we proper and try to join first
325 self.amqp_client.join(3)
326 self.amqp_client.terminate()
328 LOG.debug("Check if %s is running", agent)
329 status, pid = self.check_if_system_agent_running(agent)
330 LOG.debug("status %s pid %s", status, pid)
335 self.connection.execute('sudo kill -9 "%s"' % pid)
336 self.connection.execute('sudo pkill -9 "%s"' % agent)
337 self.connection.execute('sudo service rabbitmq-server stop')
338 self.connection.execute("sudo rabbitmqctl stop_app")