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