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 import constants as consts
24 LOG = logging.getLogger(__name__)
27 class NodeContext(Context):
28 """Class that handle nodes info"""
30 __context_type__ = "Node"
41 super(NodeContext, self).__init__()
43 def read_config_file(self):
44 """Read from config file"""
46 with open(self.file_path) as stream:
47 LOG.info("Parsing pod file: %s", self.file_path)
48 cfg = yaml.load(stream)
51 def init(self, attrs):
52 """initializes itself from the supplied arguments"""
53 self.name = attrs["name"]
54 self.file_path = attrs.get("file", "pod.yaml")
57 cfg = self.read_config_file()
58 except IOError as ioerror:
59 if ioerror.errno == errno.ENOENT:
61 os.path.join(consts.YARDSTICK_ROOT_PATH, self.file_path)
62 cfg = self.read_config_file()
66 self.nodes.extend(cfg["nodes"])
67 self.controllers.extend([node for node in cfg["nodes"]
68 if node["role"] == "Controller"])
69 self.computes.extend([node for node in cfg["nodes"]
70 if node["role"] == "Compute"])
71 self.baremetals.extend([node for node in cfg["nodes"]
72 if node["role"] == "Baremetal"])
73 LOG.debug("Nodes: %r", self.nodes)
74 LOG.debug("Controllers: %r", self.controllers)
75 LOG.debug("Computes: %r", self.computes)
76 LOG.debug("BareMetals: %r", self.baremetals)
78 self.env = attrs.get('env', {})
79 LOG.debug("Env: %r", self.env)
81 # add optional static network definition
82 self.networks.update(cfg.get("networks", {}))
85 config_type = self.env.get('type', '')
86 if config_type == 'ansible':
87 self._dispatch_ansible('setup')
88 elif config_type == 'script':
89 self._dispatch_script('setup')
92 config_type = self.env.get('type', '')
93 if config_type == 'ansible':
94 self._dispatch_ansible('teardown')
95 elif config_type == 'script':
96 self._dispatch_script('teardown')
97 super(NodeContext, self).undeploy()
99 def _dispatch_script(self, key):
100 steps = self.env.get(key, [])
102 for host, info in step.items():
103 self._execute_script(host, info)
105 def _dispatch_ansible(self, key):
111 self._do_ansible_job(step)
113 def _do_ansible_job(self, path):
114 cmd = 'ansible-playbook -i inventory.ini %s' % path
115 p = subprocess.Popen(cmd, shell=True, cwd=consts.ANSIBLE_DIR)
118 def _get_server(self, attr_name):
119 """lookup server info by name from context
120 attr_name: a name for a server listed in nodes config file
122 if isinstance(attr_name, collections.Mapping):
125 if self.name != attr_name.split(".")[1]:
127 node_name = attr_name.split(".")[0]
128 matching_nodes = (n for n in self.nodes if n["name"] == node_name)
131 # A clone is created in order to avoid affecting the
133 node = dict(next(matching_nodes))
134 except StopIteration:
138 duplicate = next(matching_nodes)
139 except StopIteration:
142 raise ValueError("Duplicate nodes!!! Nodes: %s %s",
143 (matching_nodes, duplicate))
145 node["name"] = attr_name
148 def _get_network(self, attr_name):
149 if not isinstance(attr_name, collections.Mapping):
150 network = self.networks.get(attr_name)
153 # Don't generalize too much Just support vld_id
154 vld_id = attr_name.get('vld_id')
158 network = next((n for n in self.networks.values() if
159 n.get("vld_id") == vld_id), None)
166 "name": network["name"],
167 "vld_id": network.get("vld_id"),
168 "segmentation_id": network.get("segmentation_id"),
169 "network_type": network.get("network_type"),
170 "physical_network": network.get("physical_network"),
174 def _execute_script(self, node_name, info):
175 if node_name == 'local':
176 self._execute_local_script(info)
178 self._execute_remote_script(node_name, info)
180 def _execute_remote_script(self, node_name, info):
181 prefix = self.env.get('prefix', '')
182 script, options = self._get_script(info)
184 script_file = pkg_resources.resource_filename(prefix, script)
186 self._get_client(node_name)
187 self.client._put_file_shell(script_file, '~/{}'.format(script))
189 cmd = 'sudo bash {} {}'.format(script, options)
190 status, stdout, stderr = self.client.execute(cmd)
192 raise RuntimeError(stderr)
194 def _execute_local_script(self, info):
195 script, options = self._get_script(info)
196 script = os.path.join(consts.YARDSTICK_ROOT_PATH, script)
197 cmd = ['bash', script, options]
199 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
200 LOG.debug('\n%s', p.communicate()[0])
202 def _get_script(self, info):
203 return info.get('script'), info.get('options', '')
205 def _get_client(self, node_name):
206 node = self._get_node_info(node_name.strip())
209 raise SystemExit('No such node')
211 self.client = ssh.SSH.from_node(node, defaults={'user': 'ubuntu'})
213 self.client.wait(timeout=600)
215 def _get_node_info(self, name):
216 return next((n for n in self.nodes if n['name'].strip() == name))