Merge "attacker_general: fix logging to use %s"
[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),
121                                   params={'id': job_id, 'type': 'status'})
122
123         report_res_content = jsonutils.loads(
124             report_res.content)
125
126         if report_res.status_code != 200:
127             raise RuntimeError("Failed to fetch report, error message:",
128                                report_res_content["message"])
129         else:
130             job_status = report_res_content["Status"]
131
132         LOG.debug("Job is: %s...", job_status)
133         self.job_completed = job_status == "Completed"
134
135         # TODO: Support using StorPerf ReST API to read Job ETA.
136
137         # if job_status == "completed":
138         #     self.job_completed = True
139         #     ETA = 0
140         # elif job_status == "running":
141         #     ETA = report_res_content['time']
142         #
143         # return ETA
144
145     def run(self, result):
146         """Execute StorPerf benchmark"""
147         if not self.setup_done:
148             self.setup()
149
150         job_args = {}
151         job_args_payload_list = ["block_sizes", "queue_depths", "deadline",
152                                  "target", "nossd", "nowarm", "workload"]
153
154         for job_argument in job_args_payload_list:
155             try:
156                 job_args[job_argument] = self.options[job_argument]
157             except KeyError:
158                 pass
159
160         LOG.info("Starting a job with parameters %s", job_args)
161         job_res = requests.post('http://%s:5000/api/v1.0/jobs' % self.target,
162                                 json=job_args)
163
164         job_res_content = jsonutils.loads(job_res.content)
165
166         if job_res.status_code != 200:
167             raise RuntimeError("Failed to start a job, error message:",
168                                job_res_content["message"])
169         elif job_res.status_code == 200:
170             job_id = job_res_content["job_id"]
171             LOG.info("Started job id: %s...", job_id)
172
173             while not self.job_completed:
174                 self._query_job_state(job_id)
175                 time.sleep(self.query_interval)
176
177             terminate_res = requests.delete('http://%s:5000/api/v1.0/jobs' %
178                                             self.target)
179
180             if terminate_res.status_code != 200:
181                 terminate_res_content = jsonutils.loads(
182                     terminate_res.content)
183                 raise RuntimeError("Failed to start a job, error message:",
184                                    terminate_res_content["message"])
185
186         # TODO: Support using ETA to polls for completion.
187         #       Read ETA, next poll in 1/2 ETA time slot.
188         #       If ETA is greater than the maximum allowed job time,
189         #       then terminate job immediately.
190
191         #   while not self.job_completed:
192         #       esti_time = self._query_state(job_id)
193         #       if esti_time > self.timeout:
194         #           terminate_res = requests.delete('http://%s:5000/api/v1.0
195         #                                           /jobs' % self.target)
196         #       else:
197         #           time.sleep(int(est_time)/2)
198
199             result_res = requests.get('http://%s:5000/api/v1.0/jobs?id=%s' %
200                                       (self.target, job_id))
201             result_res_content = jsonutils.loads(
202                 result_res.content)
203
204             result.update(result_res_content)
205
206     def teardown(self):
207         """Deletes the agent configuration and the stack"""
208         teardown_res = requests.delete('http://%s:5000/api/v1.0/\
209                                        configurations' % self.target)
210
211         if teardown_res.status_code == 400:
212             teardown_res_content = jsonutils.loads(
213                 teardown_res.content)
214             raise RuntimeError("Failed to reset environment, error message:",
215                                teardown_res_content['message'])
216
217         self.setup_done = False