1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
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 ##############################################################################
10 from __future__ import absolute_import
20 from yardstick import ssh
21 from yardstick.benchmark.contexts.base import Context
22 from yardstick.common.constants import YARDSTICK_ROOT_PATH
24 LOG = logging.getLogger(__name__)
27 class NodeContext(Context):
28 """Class that handle nodes info"""
30 __context_type__ = "Node"
40 super(NodeContext, self).__init__()
42 def read_config_file(self):
43 """Read from config file"""
45 with open(self.file_path) as stream:
46 LOG.info("Parsing pod file: %s", self.file_path)
47 cfg = yaml.load(stream)
50 def init(self, attrs):
51 """initializes itself from the supplied arguments"""
52 self.name = attrs["name"]
53 self.file_path = attrs.get("file", "pod.yaml")
56 cfg = self.read_config_file()
57 except IOError as ioerror:
58 if ioerror.errno == errno.ENOENT:
60 os.path.join(YARDSTICK_ROOT_PATH, self.file_path)
61 cfg = self.read_config_file()
65 self.nodes.extend(cfg["nodes"])
66 self.controllers.extend([node for node in cfg["nodes"]
67 if node["role"] == "Controller"])
68 self.computes.extend([node for node in cfg["nodes"]
69 if node["role"] == "Compute"])
70 self.baremetals.extend([node for node in cfg["nodes"]
71 if node["role"] == "Baremetal"])
72 LOG.debug("Nodes: %r", self.nodes)
73 LOG.debug("Controllers: %r", self.controllers)
74 LOG.debug("Computes: %r", self.computes)
75 LOG.debug("BareMetals: %r", self.baremetals)
77 self.env = attrs.get('env', {})
78 LOG.debug("Env: %r", self.env)
81 setups = self.env.get('setup', [])
83 for host, info in setup.items():
84 self._execute_script(host, info)
87 teardowns = self.env.get('teardown', [])
88 for teardown in teardowns:
89 for host, info in teardown.items():
90 self._execute_script(host, info)
92 def _get_server(self, attr_name):
93 """lookup server info by name from context
94 attr_name: a name for a server listed in nodes config file
96 if isinstance(attr_name, collections.Mapping):
99 if self.name != attr_name.split(".")[1]:
101 node_name = attr_name.split(".")[0]
102 matching_nodes = (n for n in self.nodes if n["name"] == node_name)
105 # A clone is created in order to avoid affecting the
107 node = dict(next(matching_nodes))
108 except StopIteration:
112 duplicate = next(matching_nodes)
113 except StopIteration:
116 raise ValueError("Duplicate nodes!!! Nodes: %s %s",
117 (matching_nodes, duplicate))
119 node["name"] = attr_name
122 def _execute_script(self, node_name, info):
123 if node_name == 'local':
124 self._execute_local_script(info)
126 self._execute_remote_script(node_name, info)
128 def _execute_remote_script(self, node_name, info):
129 prefix = self.env.get('prefix', '')
130 script, options = self._get_script(info)
132 script_file = pkg_resources.resource_filename(prefix, script)
134 self._get_client(node_name)
135 self.client._put_file_shell(script_file, '~/{}'.format(script))
137 cmd = 'sudo bash {} {}'.format(script, options)
138 status, stdout, stderr = self.client.execute(cmd)
140 raise RuntimeError(stderr)
142 def _execute_local_script(self, info):
143 script, options = self._get_script(info)
144 script = os.path.join(YARDSTICK_ROOT_PATH, script)
145 cmd = ['bash', script, options]
147 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
148 LOG.debug('\n%s', p.communicate()[0])
150 def _get_script(self, info):
151 return info.get('script'), info.get('options', '')
153 def _get_client(self, node_name):
154 node = self._get_node_info(node_name.strip())
157 raise SystemExit('No such node')
159 user = node.get('user', 'ubuntu')
160 ssh_port = node.get("ssh_port", ssh.DEFAULT_PORT)
162 pwd = node.get('password')
163 key_fname = node.get('key_filename', '/root/.ssh/id_rsa')
166 LOG.debug("Log in via pw, user:%s, host:%s, password:%s",
168 self.client = ssh.SSH(user, ip, password=pwd, port=ssh_port)
170 LOG.debug("Log in via key, user:%s, host:%s, key_filename:%s",
172 self.client = ssh.SSH(user, ip, key_filename=key_fname,
175 self.client.wait(timeout=600)
177 def _get_node_info(self, name):
178 return next((n for n in self.nodes if n['name'].strip() == name))