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 ANSIBLE_DIR, YARDSTICK_ROOT_PATH
24 LOG = logging.getLogger(__name__)
27 class NodeContext(Context):
28 """Class that handle nodes info"""
30 __context_type__ = "Node"
42 super(NodeContext, self).__init__()
44 def read_config_file(self):
45 """Read from config file"""
47 with open(self.file_path) as stream:
48 LOG.info("Parsing pod file: %s", self.file_path)
49 cfg = yaml.safe_load(stream)
52 def init(self, attrs):
53 """initializes itself from the supplied arguments"""
54 self.name = attrs["name"]
55 self.file_path = file_path = attrs.get("file", "pod.yaml")
58 cfg = self.read_config_file()
59 except IOError as io_error:
60 if io_error.errno != errno.ENOENT:
63 self.file_path = os.path.join(YARDSTICK_ROOT_PATH, file_path)
64 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', {})
80 LOG.debug("Env: %r", self.env)
82 # add optional static network definition
83 self.networks.update(cfg.get("networks", {}))
86 config_type = self.env.get('type', '')
87 if config_type == 'ansible':
88 self._dispatch_ansible('setup')
89 elif config_type == 'script':
90 self._dispatch_script('setup')
93 config_type = self.env.get('type', '')
94 if config_type == 'ansible':
95 self._dispatch_ansible('teardown')
96 elif config_type == 'script':
97 self._dispatch_script('teardown')
98 super(NodeContext, self).undeploy()
100 def _dispatch_script(self, key):
101 steps = self.env.get(key, [])
103 for host, info in step.items():
104 self._execute_script(host, info)
106 def _dispatch_ansible(self, key):
112 self._do_ansible_job(step)
114 def _do_ansible_job(self, path):
115 cmd = 'ansible-playbook -i inventory.ini %s' % path
116 p = subprocess.Popen(cmd, shell=True, cwd=ANSIBLE_DIR)
119 def _get_server(self, attr_name):
120 """lookup server info by name from context
121 attr_name: a name for a server listed in nodes config file
123 node_name, name = self.split_name(attr_name)
124 if name is None or self.name != name:
127 matching_nodes = (n for n in self.nodes if n["name"] == node_name)
130 # A clone is created in order to avoid affecting the
132 node = dict(next(matching_nodes))
133 except StopIteration:
137 duplicate = next(matching_nodes)
138 except StopIteration:
141 raise ValueError("Duplicate nodes!!! Nodes: %s %s",
144 node["name"] = attr_name
145 node.setdefault("interfaces", {})
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', {})
155 # for node context networks are dicts
156 iter1 = (n for n in self.networks.values() if n.get('vld_id') == vld_id)
157 network = next(iter1, None)
164 "name": network["name"],
165 "vld_id": network.get("vld_id"),
166 "segmentation_id": network.get("segmentation_id"),
167 "network_type": network.get("network_type"),
168 "physical_network": network.get("physical_network"),
172 def _execute_script(self, node_name, info):
173 if node_name == 'local':
174 self._execute_local_script(info)
176 self._execute_remote_script(node_name, info)
178 def _execute_remote_script(self, node_name, info):
179 prefix = self.env.get('prefix', '')
180 script, options = self._get_script(info)
182 script_file = pkg_resources.resource_filename(prefix, script)
184 self._get_client(node_name)
185 self.client._put_file_shell(script_file, '~/{}'.format(script))
187 cmd = 'sudo bash {} {}'.format(script, options)
188 status, stdout, stderr = self.client.execute(cmd)
190 raise RuntimeError(stderr)
192 def _execute_local_script(self, info):
193 script, options = self._get_script(info)
194 script = os.path.join(YARDSTICK_ROOT_PATH, script)
195 cmd = ['bash', script, options]
197 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
198 LOG.debug('\n%s', p.communicate()[0])
200 def _get_script(self, info):
201 return info.get('script'), info.get('options', '')
203 def _get_client(self, node_name):
204 node = self._get_node_info(node_name.strip())
207 raise SystemExit('No such node')
209 self.client = ssh.SSH.from_node(node, defaults={'user': 'ubuntu'})
211 self.client.wait(timeout=600)
213 def _get_node_info(self, name):
214 return next((n for n in self.nodes if n['name'].strip() == name))