cf66125297b1dfe46a489df6316c2084a0bc0285
[yardstick.git] / yardstick / cmd / commands / plugin.py
1 ##############################################################################
2 # Copyright (c) 2016 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 """ Handler for yardstick command 'plugin' """
11
12 import os
13 import sys
14 import yaml
15 import time
16 import logging
17 import pkg_resources
18 import yardstick.ssh as ssh
19
20 from yardstick.common.utils import cliargs
21 from yardstick.common.task_template import TaskTemplate
22
23 LOG = logging.getLogger(__name__)
24
25
26 class PluginCommands(object):
27     '''Plugin commands.
28
29        Set of commands to manage plugins.
30     '''
31
32     @cliargs("input_file", type=str, help="path to plugin configuration file",
33              nargs=1)
34     def do_install(self, args):
35         '''Install a plugin.'''
36
37         total_start_time = time.time()
38         parser = PluginParser(args.input_file[0])
39
40         plugins, deployment = parser.parse_plugin()
41         plugin_name = plugins.get("name")
42         print("Installing plugin: %s" % plugin_name)
43
44         LOG.info("Executing _install_setup()")
45         self._install_setup(plugin_name, deployment)
46
47         LOG.info("Executing _run()")
48         self._run(plugin_name)
49
50         total_end_time = time.time()
51         LOG.info("total finished in %d secs",
52                  total_end_time - total_start_time)
53
54         print("Done, exiting")
55
56     @cliargs("input_file", type=str, help="path to plugin configuration file",
57              nargs=1)
58     def do_remove(self, args):
59         '''Remove a plugin.'''
60
61         total_start_time = time.time()
62         parser = PluginParser(args.input_file[0])
63
64         plugins, deployment = parser.parse_plugin()
65         plugin_name = plugins.get("name")
66         print("Removing plugin: %s" % plugin_name)
67
68         LOG.info("Executing _remove_setup()")
69         self._remove_setup(plugin_name, deployment)
70
71         LOG.info("Executing _run()")
72         self._run(plugin_name)
73
74         total_end_time = time.time()
75         LOG.info("total finished in %d secs",
76                  total_end_time - total_start_time)
77
78         print("Done, exiting")
79
80     def _install_setup(self, plugin_name, deployment):
81         '''Deployment environment setup'''
82         target_script = plugin_name + ".bash"
83         self.script = pkg_resources.resource_filename(
84             'yardstick.resources', 'scripts/install/' + target_script)
85
86         deployment_user = deployment.get("user")
87         deployment_ssh_port = deployment.get("ssh_port", ssh.DEFAULT_PORT)
88         deployment_ip = deployment.get("ip", None)
89         deployment_password = deployment.get("password", None)
90         deployment_key_filename = deployment.get("key_filename",
91                                                  "/root/.ssh/id_rsa")
92
93         if deployment_ip == "local":
94             installer_ip = os.environ.get("INSTALLER_IP", None)
95
96             if deployment_password is not None:
97                 self._login_via_password(deployment_user, installer_ip,
98                                          deployment_password,
99                                          deployment_ssh_port)
100             else:
101                 self._login_via_key(self, deployment_user, installer_ip,
102                                     deployment_key_filename,
103                                     deployment_ssh_port)
104         else:
105             if deployment_password is not None:
106                 self._login_via_password(deployment_user, deployment_ip,
107                                          deployment_password,
108                                          deployment_ssh_port)
109             else:
110                 self._login_via_key(self, deployment_user, deployment_ip,
111                                     deployment_key_filename,
112                                     deployment_ssh_port)
113         # copy script to host
114         cmd = "cat > ~/%s.sh" % plugin_name
115
116         LOG.info("copying script to host: %s", cmd)
117         self.client.run(cmd, stdin=open(self.script, 'rb'))
118
119     def _remove_setup(self, plugin_name, deployment):
120         '''Deployment environment setup'''
121         target_script = plugin_name + ".bash"
122         self.script = pkg_resources.resource_filename(
123             'yardstick.resources', 'scripts/remove/' + target_script)
124
125         deployment_user = deployment.get("user")
126         deployment_ssh_port = deployment.get("ssh_port", ssh.DEFAULT_PORT)
127         deployment_ip = deployment.get("ip", None)
128         deployment_password = deployment.get("password", None)
129         deployment_key_filename = deployment.get("key_filename",
130                                                  "/root/.ssh/id_rsa")
131
132         if deployment_ip == "local":
133             installer_ip = os.environ.get("INSTALLER_IP", None)
134
135             if deployment_password is not None:
136                 self._login_via_password(deployment_user, installer_ip,
137                                          deployment_password,
138                                          deployment_ssh_port)
139             else:
140                 self._login_via_key(self, deployment_user, installer_ip,
141                                     deployment_key_filename,
142                                     deployment_ssh_port)
143         else:
144             if deployment_password is not None:
145                 self._login_via_password(deployment_user, deployment_ip,
146                                          deployment_password,
147                                          deployment_ssh_port)
148             else:
149                 self._login_via_key(self, deployment_user, deployment_ip,
150                                     deployment_key_filename,
151                                     deployment_ssh_port)
152
153         # copy script to host
154         cmd = "cat > ~/%s.sh" % plugin_name
155
156         LOG.info("copying script to host: %s", cmd)
157         self.client.run(cmd, stdin=open(self.script, 'rb'))
158
159     def _login_via_password(self, user, ip, password, ssh_port):
160         LOG.info("Log in via pw, user:%s, host:%s", user, ip)
161         self.client = ssh.SSH(user, ip, password=password, port=ssh_port)
162         self.client.wait(timeout=600)
163
164     def _login_via_key(self, user, ip, key_filename, ssh_port):
165         LOG.info("Log in via key, user:%s, host:%s", user, ip)
166         self.client = ssh.SSH(user, ip, key_filename=key_filename,
167                               port=ssh_port)
168         self.client.wait(timeout=600)
169
170     def _run(self, plugin_name):
171         '''Run installation script '''
172         cmd = "sudo bash %s" % plugin_name + ".sh"
173
174         LOG.info("Executing command: %s", cmd)
175         status, stdout, stderr = self.client.execute(cmd)
176
177
178 class PluginParser(object):
179     '''Parser for plugin configration files in yaml format'''
180
181     def __init__(self, path):
182         self.path = path
183
184     def parse_plugin(self):
185         '''parses the plugin file and return a plugins instance
186            and a deployment instance
187         '''
188
189         print "Parsing plugin config:", self.path
190
191         try:
192             kw = {}
193             with open(self.path) as f:
194                 try:
195                     input_plugin = f.read()
196                     rendered_plugin = TaskTemplate.render(input_plugin, **kw)
197                 except Exception as e:
198                     print(("Failed to render template:\n%(plugin)s\n%(err)s\n")
199                           % {"plugin": input_plugin, "err": e})
200                     raise e
201                 print(("Input plugin is:\n%s\n") % rendered_plugin)
202
203                 cfg = yaml.load(rendered_plugin)
204         except IOError as ioerror:
205             sys.exit(ioerror)
206
207         self._check_schema(cfg["schema"], "plugin")
208
209         return cfg["plugins"], cfg["deployment"]
210
211     def _check_schema(self, cfg_schema, schema_type):
212         '''Check if configration file is using the correct schema type'''
213
214         if cfg_schema != "yardstick:" + schema_type + ":0.1":
215             sys.exit("error: file %s has unknown schema %s" % (self.path,
216                                                                cfg_schema))