Merge "Record test case names when run a task using API"
[yardstick.git] / yardstick / benchmark / contexts / node.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
10 from __future__ import absolute_import
11 import errno
12 import subprocess
13 import os
14 import collections
15 import logging
16
17 import yaml
18 import pkg_resources
19
20 from yardstick import ssh
21 from yardstick.benchmark.contexts.base import Context
22 from yardstick.common.constants import YARDSTICK_ROOT_PATH
23
24 LOG = logging.getLogger(__name__)
25
26
27 class NodeContext(Context):
28     """Class that handle nodes info"""
29
30     __context_type__ = "Node"
31
32     def __init__(self):
33         self.name = None
34         self.file_path = None
35         self.nodes = []
36         self.controllers = []
37         self.computes = []
38         self.baremetals = []
39         self.env = {}
40         super(NodeContext, self).__init__()
41
42     def read_config_file(self):
43         """Read from config file"""
44
45         with open(self.file_path) as stream:
46             LOG.info("Parsing pod file: %s", self.file_path)
47             cfg = yaml.load(stream)
48         return cfg
49
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")
54
55         try:
56             cfg = self.read_config_file()
57         except IOError as ioerror:
58             if ioerror.errno == errno.ENOENT:
59                 self.file_path = \
60                     os.path.join(YARDSTICK_ROOT_PATH, self.file_path)
61                 cfg = self.read_config_file()
62             else:
63                 raise
64
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)
76
77         self.env = attrs.get('env', {})
78         LOG.debug("Env: %r", self.env)
79
80     def deploy(self):
81         setups = self.env.get('setup', [])
82         for setup in setups:
83             for host, info in setup.items():
84                 self._execute_script(host, info)
85
86     def undeploy(self):
87         teardowns = self.env.get('teardown', [])
88         for teardown in teardowns:
89             for host, info in teardown.items():
90                 self._execute_script(host, info)
91
92         super(NodeContext, self).undeploy()
93
94     def _get_server(self, attr_name):
95         """lookup server info by name from context
96         attr_name: a name for a server listed in nodes config file
97         """
98         if isinstance(attr_name, collections.Mapping):
99             return None
100
101         if self.name != attr_name.split(".")[1]:
102             return None
103         node_name = attr_name.split(".")[0]
104         matching_nodes = (n for n in self.nodes if n["name"] == node_name)
105
106         try:
107             # A clone is created in order to avoid affecting the
108             # original one.
109             node = dict(next(matching_nodes))
110         except StopIteration:
111             return None
112
113         try:
114             duplicate = next(matching_nodes)
115         except StopIteration:
116             pass
117         else:
118             raise ValueError("Duplicate nodes!!! Nodes: %s %s",
119                              (matching_nodes, duplicate))
120
121         node["name"] = attr_name
122         return node
123
124     def _execute_script(self, node_name, info):
125         if node_name == 'local':
126             self._execute_local_script(info)
127         else:
128             self._execute_remote_script(node_name, info)
129
130     def _execute_remote_script(self, node_name, info):
131         prefix = self.env.get('prefix', '')
132         script, options = self._get_script(info)
133
134         script_file = pkg_resources.resource_filename(prefix, script)
135
136         self._get_client(node_name)
137         self.client._put_file_shell(script_file, '~/{}'.format(script))
138
139         cmd = 'sudo bash {} {}'.format(script, options)
140         status, stdout, stderr = self.client.execute(cmd)
141         if status:
142             raise RuntimeError(stderr)
143
144     def _execute_local_script(self, info):
145         script, options = self._get_script(info)
146         script = os.path.join(YARDSTICK_ROOT_PATH, script)
147         cmd = ['bash', script, options]
148
149         p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
150         LOG.debug('\n%s', p.communicate()[0])
151
152     def _get_script(self, info):
153         return info.get('script'), info.get('options', '')
154
155     def _get_client(self, node_name):
156         node = self._get_node_info(node_name.strip())
157
158         if node is None:
159             raise SystemExit('No such node')
160
161         user = node.get('user', 'ubuntu')
162         ssh_port = node.get("ssh_port", ssh.DEFAULT_PORT)
163         ip = node.get('ip')
164         pwd = node.get('password')
165         key_fname = node.get('key_filename', '/root/.ssh/id_rsa')
166
167         if pwd is not None:
168             LOG.debug("Log in via pw, user:%s, host:%s, password:%s",
169                       user, ip, pwd)
170             self.client = ssh.SSH(user, ip, password=pwd, port=ssh_port)
171         else:
172             LOG.debug("Log in via key, user:%s, host:%s, key_filename:%s",
173                       user, ip, key_fname)
174             self.client = ssh.SSH(user, ip, key_filename=key_fname,
175                                   port=ssh_port)
176
177         self.client.wait(timeout=600)
178
179     def _get_node_info(self, name):
180         return next((n for n in self.nodes if n['name'].strip() == name))