Merge "heat: close file before parsing template"
[yardstick.git] / yardstick / benchmark / scenarios / availability / monitor / monitor_command.py
1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd. and others
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 from __future__ import absolute_import
10 import logging
11 import subprocess
12 import traceback
13
14 import yardstick.ssh as ssh
15 from yardstick.benchmark.scenarios.availability.monitor import basemonitor
16
17 LOG = logging.getLogger(__name__)
18
19
20 def _execute_shell_command(command):
21     """execute shell script with error handling"""
22     exitcode = 0
23     output = []
24     try:
25         output = subprocess.check_output(command, shell=True)
26     except Exception:
27         exitcode = -1
28         output = traceback.format_exc()
29         LOG.error("exec command '%s' error:\n ", command)
30         LOG.error(traceback.format_exc())
31
32     return exitcode, output
33
34
35 class MonitorOpenstackCmd(basemonitor.BaseMonitor):
36     """docstring for MonitorApi"""
37
38     __monitor_type__ = "openstack-cmd"
39
40     def setup(self):
41         self.connection = None
42         node_name = self._config.get("host", None)
43         if node_name:
44             host = self._context[node_name]
45             ip = host.get("ip", None)
46             user = host.get("user", "root")
47             ssh_port = host.get("ssh_port", ssh.DEFAULT_PORT)
48             key_filename = host.get("key_filename", "~/.ssh/id_rsa")
49
50             self.connection = ssh.SSH(user, ip, key_filename=key_filename,
51                                       port=ssh_port)
52             self.connection.wait(timeout=600)
53             LOG.debug("ssh host success!")
54
55         self.check_script = self.get_script_fullpath(
56             "ha_tools/check_openstack_cmd.bash")
57
58         self.cmd = self._config["command_name"]
59
60     def monitor_func(self):
61         exit_status = 0
62         if self.connection:
63             with open(self.check_script, "r") as stdin_file:
64                 exit_status, stdout, stderr = self.connection.execute(
65                     "/bin/bash -s '{0}'".format(self.cmd),
66                     stdin=stdin_file)
67
68             LOG.debug("the ret stats: %s stdout: %s stderr: %s",
69                       exit_status, stdout, stderr)
70         else:
71             exit_status, stdout = _execute_shell_command(self.cmd)
72         if exit_status:
73             return False
74         return True
75
76     def verify_SLA(self):
77         outage_time = self._result.get('outage_time', None)
78         LOG.debug("the _result:%s", self._result)
79         max_outage_time = self._config["sla"]["max_outage_time"]
80         if outage_time > max_outage_time:
81             LOG.info("SLA failure: %f > %f", outage_time, max_outage_time)
82             return False
83         else:
84             LOG.info("the sla is passed")
85             return True
86
87
88 def _test():    # pragma: no cover
89     host = {
90         "ip": "192.168.235.22",
91         "user": "root",
92         "key_filename": "/root/.ssh/id_rsa"
93     }
94     context = {"node1": host}
95     monitor_configs = []
96     config = {
97         'monitor_type': 'openstack-cmd',
98         'command_name': 'nova image-list',
99         'monitor_time': 1,
100         'host': 'node1',
101         'sla': {'max_outage_time': 5}
102     }
103     monitor_configs.append(config)
104
105     p = basemonitor.MonitorMgr()
106     p.init_monitors(monitor_configs, context)
107     p.start_monitors()
108     p.wait_monitors()
109     p.verify_SLA()
110
111
112 if __name__ == '__main__':    # pragma: no cover
113     _test()