Merge "Bugfix: task_id parameter from API can not pass to yardstick core"
[yardstick.git] / yardstick / benchmark / scenarios / availability / attacker / attacker_baremetal.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.attacker.baseattacker import \
16     BaseAttacker
17
18 LOG = logging.getLogger(__name__)
19
20
21 def _execute_shell_command(command, stdin=None):
22     """execute shell script with error handling"""
23     exitcode = 0
24     output = []
25     try:
26         output = subprocess.check_output(command, stdin=stdin, shell=True)
27     except Exception:
28         exitcode = -1
29         output = traceback.format_exc()
30         LOG.error("exec command '%s' error:\n ", command)
31         LOG.error(traceback.format_exc())
32
33     return exitcode, output
34
35
36 class BaremetalAttacker(BaseAttacker):
37     __attacker_type__ = 'bare-metal-down'
38
39     def setup(self):
40         LOG.debug("config:%s context:%s", self._config, self._context)
41         host = self._context.get(self._config['host'], None)
42         ip = host.get("ip", None)
43         user = host.get("user", "root")
44         ssh_port = host.get("ssh_port", ssh.DEFAULT_PORT)
45         key_filename = host.get("key_filename", "~/.ssh/id_rsa")
46
47         self.connection = ssh.SSH(user, ip, key_filename=key_filename,
48                                   port=ssh_port)
49         self.connection.wait(timeout=600)
50         LOG.debug("ssh host success!")
51         self.host_ip = ip
52
53         self.ipmi_ip = host.get("ipmi_ip", None)
54         self.ipmi_user = host.get("ipmi_user", "root")
55         self.ipmi_pwd = host.get("ipmi_pwd", None)
56
57         self.fault_cfg = BaseAttacker.attacker_cfgs.get('bare-metal-down')
58         self.check_script = self.get_script_fullpath(
59             self.fault_cfg['check_script'])
60         self.recovery_script = self.get_script_fullpath(
61             self.fault_cfg['recovery_script'])
62
63         if self.check():
64             self.setup_done = True
65
66     def check(self):
67         with open(self.check_script, "r") as stdin_file:
68             exit_status, stdout, stderr = self.connection.execute(
69                 "/bin/sh -s {0} -W 10".format(self.host_ip),
70                 stdin=stdin_file)
71
72         LOG.debug("check ret: %s out:%s err:%s",
73                   exit_status, stdout, stderr)
74         if not stdout or "running" not in stdout:
75             LOG.info("the host (ipmi_ip:%s) is not running!", self.ipmi_ip)
76             return False
77
78         return True
79
80     def inject_fault(self):
81         exit_status, stdout, stderr = self.connection.execute(
82             "shutdown -h now")
83         LOG.debug("inject fault ret: %s out:%s err:%s",
84                   exit_status, stdout, stderr)
85         if not exit_status:
86             LOG.info("inject fault success")
87
88     def recover(self):
89         jump_host_name = self._config.get("jump_host", None)
90         self.jump_connection = None
91         if jump_host_name is not None:
92             host = self._context.get(jump_host_name, None)
93             ip = host.get("ip", None)
94             user = host.get("user", "root")
95             ssh_port = host.get("ssh_port", ssh.DEFAULT_PORT)
96             pwd = host.get("pwd", None)
97
98             LOG.debug("jump_host ip:%s user:%s", ip, user)
99             self.jump_connection = ssh.SSH(user, ip, password=pwd,
100                                            port=ssh_port)
101             self.jump_connection.wait(timeout=600)
102             LOG.debug("ssh jump host success!")
103
104         if self.jump_connection is not None:
105             with open(self.recovery_script, "r") as stdin_file:
106                 exit_status, stdout, stderr = self.jump_connection.execute(
107                     "/bin/bash -s {0} {1} {2} {3}".format(
108                         self.ipmi_ip, self.ipmi_user, self.ipmi_pwd, "on"),
109                     stdin=stdin_file)
110         else:
111             exit_status, stdout = _execute_shell_command(
112                 "/bin/bash -s {0} {1} {2} {3}".format(
113                     self.ipmi_ip, self.ipmi_user, self.ipmi_pwd, "on"),
114                 stdin=open(self.recovery_script, "r"))
115
116
117 def _test():  # pragma: no cover
118     host = {
119         "ipmi_ip": "10.20.0.5",
120         "ipmi_user": "root",
121         "ipmi_pwd": "123456",
122         "ip": "10.20.0.5",
123         "user": "root",
124         "key_filename": "/root/.ssh/id_rsa"
125     }
126     context = {"node1": host}
127     attacker_cfg = {
128         'fault_type': 'bear-metal-down',
129         'host': 'node1',
130     }
131     ins = BaremetalAttacker(attacker_cfg, context)
132     ins.setup()
133     ins.inject_fault()
134
135
136 if __name__ == '__main__':  # pragma: no cover
137     _test()