improve logging, clear using print
[yardstick.git] / yardstick / benchmark / core / 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 from __future__ import print_function
13 from __future__ import absolute_import
14 import os
15 import sys
16 import time
17 import logging
18 import pkg_resources
19 import yardstick.ssh as ssh
20
21 from yardstick.common.task_template import TaskTemplate
22 from yardstick.common.yaml_loader import yaml_load
23
24 LOG = logging.getLogger(__name__)
25
26
27 class Plugin(object):
28     """Plugin commands.
29
30        Set of commands to manage plugins.
31     """
32
33     def install(self, args):
34         """Install a plugin."""
35
36         total_start_time = time.time()
37         parser = PluginParser(args.input_file[0])
38
39         plugins, deployment = parser.parse_plugin()
40         plugin_name = plugins.get("name")
41         LOG.info("Installing plugin: %s", plugin_name)
42
43         LOG.debug("Executing _install_setup()")
44         self._install_setup(plugin_name, deployment)
45
46         LOG.debug("Executing _run()")
47         self._run(plugin_name)
48
49         total_end_time = time.time()
50         LOG.info("Total finished in %d secs",
51                  total_end_time - total_start_time)
52
53         LOG.info("Plugin %s Done, exiting", plugin_name)
54
55     def remove(self, args):
56         """Remove a plugin."""
57
58         total_start_time = time.time()
59         parser = PluginParser(args.input_file[0])
60
61         plugins, deployment = parser.parse_plugin()
62         plugin_name = plugins.get("name")
63         print("Removing plugin: %s" % plugin_name)
64
65         LOG.info("Executing _remove_setup()")
66         self._remove_setup(plugin_name, deployment)
67
68         LOG.info("Executing _run()")
69         self._run(plugin_name)
70
71         total_end_time = time.time()
72         LOG.info("total finished in %d secs",
73                  total_end_time - total_start_time)
74
75         print("Done, exiting")
76
77     def _install_setup(self, plugin_name, deployment):
78         """Deployment environment setup"""
79         target_script = plugin_name + ".bash"
80         self.script = pkg_resources.resource_filename(
81             'yardstick.resources', 'scripts/install/' + target_script)
82
83         deployment_ip = deployment.get("ip", None)
84
85         if deployment_ip == "local":
86             self.client = ssh.SSH.from_node(deployment, overrides={
87                 # host can't be None, fail if no JUMP_HOST_IP
88                 'ip': os.environ["JUMP_HOST_IP"],
89             })
90         else:
91             self.client = ssh.SSH.from_node(deployment)
92         self.client.wait(timeout=600)
93
94         # copy script to host
95         remotepath = '~/%s.sh' % plugin_name
96
97         LOG.info("copying script to host: %s", remotepath)
98         self.client._put_file_shell(self.script, remotepath)
99
100     def _remove_setup(self, plugin_name, deployment):
101         """Deployment environment setup"""
102         target_script = plugin_name + ".bash"
103         self.script = pkg_resources.resource_filename(
104             'yardstick.resources', 'scripts/remove/' + target_script)
105
106         deployment_ip = deployment.get("ip", None)
107
108         if deployment_ip == "local":
109             self.client = ssh.SSH.from_node(deployment, overrides={
110                 # host can't be None, fail if no JUMP_HOST_IP
111                 'ip': os.environ["JUMP_HOST_IP"],
112             })
113         else:
114             self.client = ssh.SSH.from_node(deployment)
115         self.client.wait(timeout=600)
116
117         # copy script to host
118         remotepath = '~/%s.sh' % plugin_name
119
120         LOG.info("copying script to host: %s", remotepath)
121         self.client._put_file_shell(self.script, remotepath)
122
123     def _run(self, plugin_name):
124         """Run installation script """
125         cmd = "sudo bash %s" % plugin_name + ".sh"
126
127         LOG.info("Executing command: %s", cmd)
128         self.client.execute(cmd)
129
130
131 class PluginParser(object):
132     """Parser for plugin configration files in yaml format"""
133
134     def __init__(self, path):
135         self.path = path
136
137     def parse_plugin(self):
138         """parses the plugin file and return a plugins instance
139            and a deployment instance
140         """
141
142         print("Parsing plugin config:", self.path)
143
144         try:
145             kw = {}
146             with open(self.path) as f:
147                 try:
148                     input_plugin = f.read()
149                     rendered_plugin = TaskTemplate.render(input_plugin, **kw)
150                 except Exception as e:
151                     print("Failed to render template:\n%(plugin)s\n%(err)s\n"
152                           % {"plugin": input_plugin, "err": e})
153                     raise e
154                 print("Input plugin is:\n%s\n" % rendered_plugin)
155
156                 cfg = yaml_load(rendered_plugin)
157         except IOError as ioerror:
158             sys.exit(ioerror)
159
160         self._check_schema(cfg["schema"], "plugin")
161
162         return cfg["plugins"], cfg["deployment"]
163
164     def _check_schema(self, cfg_schema, schema_type):
165         """Check if configration file is using the correct schema type"""
166
167         if cfg_schema != "yardstick:" + schema_type + ":0.1":
168             sys.exit("error: file %s has unknown schema %s" % (self.path,
169                                                                cfg_schema))