Merge "Set TEST_DB_URL for storperf"
[yardstick.git] / yardstick / benchmark / scenarios / storage / storperf.py
1 ##############################################################################
2 # Copyright (c) 2016 Huawei Technologies Co.,Ltd.
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 from __future__ import absolute_import
10
11 import os
12 import logging
13 import time
14
15 import requests
16 from oslo_serialization import jsonutils
17
18 from yardstick.benchmark.scenarios import base
19
20 LOG = logging.getLogger(__name__)
21
22
23 class StorPerf(base.Scenario):
24     """Execute StorPerf benchmark.
25     Once the StorPerf container has been started and the ReST API exposed,
26     you can interact directly with it using the ReST API. StorPerf comes with a
27     Swagger interface that is accessible through the exposed port at:
28     http://StorPerf:5000/swagger/index.html
29
30   Command line options:
31     target = [device or path] (Optional):
32     The path to either an attached storage device (/dev/vdb, etc) or a
33     directory path (/opt/storperf) that will be used to execute the performance
34     test. In the case of a device, the entire device will be used.
35     If not specified, the current directory will be used.
36
37     workload = [workload module] (Optional):
38     If not specified, the default is to run all workloads.
39     The workload types are:
40         rs: 100% Read, sequential data
41         ws: 100% Write, sequential data
42         rr: 100% Read, random access
43         wr: 100% Write, random access
44         rw: 70% Read / 30% write, random access
45
46     nossd (Optional):
47     Do not perform SSD style preconditioning.
48
49     nowarm (Optional):
50     Do not perform a warmup prior to measurements.
51
52     report = [job_id] (Optional):
53     Query the status of the supplied job_id and report on metrics.
54     If a workload is supplied, will report on only that subset.
55
56     """
57     __scenario_type__ = "StorPerf"
58
59     def __init__(self, scenario_cfg, context_cfg):
60         """Scenario construction."""
61         super(StorPerf, self).__init__()
62         self.scenario_cfg = scenario_cfg
63         self.context_cfg = context_cfg
64         self.options = self.scenario_cfg["options"]
65
66         self.target = self.options.get("StorPerf_ip", None)
67         self.query_interval = self.options.get("query_interval", 10)
68         # Maximum allowed job time
69         self.timeout = self.options.get('timeout', 3600)
70
71         self.setup_done = False
72         self.job_completed = False
73
74     def _query_setup_state(self):
75         """Query the stack status."""
76         LOG.info("Querying the stack state...")
77         setup_query = requests.get('http://%s:5000/api/v1.0/configurations'
78                                    % self.target)
79
80         setup_query_content = jsonutils.loads(
81             setup_query.content)
82         if setup_query_content["stack_created"]:
83             self.setup_done = True
84             LOG.debug("stack_created: %s",
85                       setup_query_content["stack_created"])
86
87     def setup(self):
88         """Set the configuration."""
89         env_args = {}
90         env_args_payload_list = ["agent_count", "public_network",
91                                  "agent_image", "volume_size"]
92
93         for env_argument in env_args_payload_list:
94             try:
95                 env_args[env_argument] = self.options[env_argument]
96             except KeyError:
97                 pass
98
99         LOG.info("Creating a stack on node %s with parameters %s",
100                  self.target, env_args)
101         setup_res = requests.post('http://%s:5000/api/v1.0/configurations'
102                                   % self.target, json=env_args)
103
104         setup_res_content = jsonutils.loads(
105             setup_res.content)
106
107         if setup_res.status_code != 200:
108             raise RuntimeError("Failed to create a stack, error message:",
109                                setup_res_content["message"])
110         elif setup_res.status_code == 200:
111             LOG.info("stack_id: %s", setup_res_content["stack_id"])
112
113             while not self.setup_done:
114                 self._query_setup_state()
115                 time.sleep(self.query_interval)
116
117     def _query_job_state(self, job_id):
118         """Query the status of the supplied job_id and report on metrics"""
119         LOG.info("Fetching report for %s...", job_id)
120         report_res = requests.get('http://{}:5000/api/v1.0/jobs'.format
121                                   (self.target),
122                                   params={'id': job_id, 'type': 'status'})
123
124         report_res_content = jsonutils.loads(
125             report_res.content)
126
127         if report_res.status_code != 200:
128             raise RuntimeError("Failed to fetch report, error message:",
129                                report_res_content["message"])
130         else:
131             job_status = report_res_content["Status"]
132
133         LOG.debug("Job is: %s...", job_status)
134         self.job_completed = job_status == "Completed"
135
136         # TODO: Support using StorPerf ReST API to read Job ETA.
137
138         # if job_status == "completed":
139         #     self.job_completed = True
140         #     ETA = 0
141         # elif job_status == "running":
142         #     ETA = report_res_content['time']
143         #
144         # return ETA
145
146     def run(self, result):
147         """Execute StorPerf benchmark"""
148         if not self.setup_done:
149             self.setup()
150
151         metadata = {"build_tag": "latest", "test_case": "opnfv_yardstick_tc074"}
152         metadata_payload_dict = {"pod_name": "NODE_NAME",
153                                  "scenario_name": "DEPLOY_SCENARIO",
154                                  "version": "YARDSTICK_BRANCH"}
155
156         for key, value in metadata_payload_dict.items():
157             try:
158                 metadata[key] = os.environ[value]
159             except KeyError:
160                 pass
161
162         job_args = {"metadata": metadata}
163         job_args_payload_list = ["block_sizes", "queue_depths", "deadline",
164                                  "target", "nossd", "nowarm", "workload"]
165
166         for job_argument in job_args_payload_list:
167             try:
168                 job_args[job_argument] = self.options[job_argument]
169             except KeyError:
170                 pass
171
172         LOG.info("Starting a job with parameters %s", job_args)
173         job_res = requests.post('http://%s:5000/api/v1.0/jobs' % self.target,
174                                 json=job_args)
175
176         job_res_content = jsonutils.loads(job_res.content)
177
178         if job_res.status_code != 200:
179             raise RuntimeError("Failed to start a job, error message:",
180                                job_res_content["message"])
181         elif job_res.status_code == 200:
182             job_id = job_res_content["job_id"]
183             LOG.info("Started job id: %s...", job_id)
184
185             while not self.job_completed:
186                 self._query_job_state(job_id)
187                 time.sleep(self.query_interval)
188
189             terminate_res = requests.delete('http://%s:5000/api/v1.0/jobs' %
190                                             self.target)
191
192             if terminate_res.status_code != 200:
193                 terminate_res_content = jsonutils.loads(
194                     terminate_res.content)
195                 raise RuntimeError("Failed to start a job, error message:",
196                                    terminate_res_content["message"])
197
198         # TODO: Support using ETA to polls for completion.
199         #       Read ETA, next poll in 1/2 ETA time slot.
200         #       If ETA is greater than the maximum allowed job time,
201         #       then terminate job immediately.
202
203         #   while not self.job_completed:
204         #       esti_time = self._query_state(job_id)
205         #       if esti_time > self.timeout:
206         #           terminate_res = requests.delete('http://%s:5000/api/v1.0
207         #                                           /jobs' % self.target)
208         #       else:
209         #           time.sleep(int(est_time)/2)
210
211             result_res = requests.get('http://%s:5000/api/v1.0/jobs?id=%s' %
212                                       (self.target, job_id))
213             result_res_content = jsonutils.loads(
214                 result_res.content)
215
216             result.update(result_res_content)
217
218     def teardown(self):
219         """Deletes the agent configuration and the stack"""
220         teardown_res = requests.delete('http://%s:5000/api/v1.0/\
221                                        configurations' % self.target)
222
223         if teardown_res.status_code == 400:
224             teardown_res_content = jsonutils.loads(
225                 teardown_res.content)
226             raise RuntimeError("Failed to reset environment, error message:",
227                                teardown_res_content['message'])
228
229         self.setup_done = False