-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjmeter_cluster.py
executable file
·397 lines (328 loc) · 13.4 KB
/
jmeter_cluster.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
#!/usr/bin/env python
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command line tool for JMeter server cluster on Google Compute Engine.
The script starts Google Compute Engine instances, install JMeter,
and starts JMeter servers on them. The script can also start JMeter
client on local machine, that are connected to JMeter servers started
in advance.
"""
import argparse
import logging
import os
import os.path
import re
import subprocess
import sys
import time
import oauth2client
from gce_api import GceApi
# Project-related configuration.
CLIENT_ID = '{{{{ client_id }}}}'
CLIENT_SECRET = '{{{{ client_secret }}}}'
CLOUD_STORAGE = 'gs://{{{{ cloud_storage }}}}'
DEFAULT_PROJECT = '{{{{ project_id }}}}'
DEFAULT_ZONE = 'us-central1-a'
DEFAULT_IMAGE = 'projects/debian-cloud/global/images/debian-7-wheezy-v20131120'
DEFAULT_MACHINE_TYPE = 'n1-standard-2'
GCE_STATUS_CHECK_INTERVAL = 3
class JMeterFiles(object):
"""Class to handle local files for JMeter client."""
CLIENT_DIR = 'apache-jmeter-2.9-client'
STARTUP_SCRIPT = ['startup.sh']
CLIENT_CONFIG = [CLIENT_DIR, 'bin', 'jmeter.properties']
CLIENT_JMETER = [CLIENT_DIR, 'bin', 'jmeter.sh']
@classmethod
def _GetPath(cls, *params):
return os.path.join(os.path.relpath(os.path.dirname(__file__)),
*list(*params))
@classmethod
def GetStartupScriptPath(cls):
return cls._GetPath(cls.STARTUP_SCRIPT)
@classmethod
def RunJmeterClient(cls, *params):
executable = cls._GetPath(cls.CLIENT_JMETER)
command = ' '.join([executable, '-Djava.rmi.server.hostname=127.0.0.1'] +
list(params))
subprocess.call(command, shell=True)
@classmethod
def RewriteConfig(cls, regexp_pattern, replace_string):
"""Rewrite JMeter config file with regular expression rule.
The function reads jmeter.properties and overwrites the same file.
Args:
regexp_pattern: Regular expression rule in string to match against.
replace_string: New string to replace the rule with.
"""
config_file = cls._GetPath(cls.CLIENT_CONFIG)
with open(config_file) as f:
contents = f.read()
new_contents = re.compile(regexp_pattern, re.MULTILINE).sub(
replace_string, contents)
with open(config_file, 'w') as f:
f.write(new_contents)
class JMeterCluster(object):
"""Class to manipulate JMeter server cluster on Google Compute Engine."""
def __init__(self, params):
self.params = params
self.api = None
def _GetGceApi(self):
"""Set up and get GoogleComputeEngine object if necessary."""
if not self.api:
self.project = (getattr(self.params, 'project', None) or DEFAULT_PROJECT)
self.zone = (getattr(self.params, 'zone', None) or DEFAULT_ZONE)
self.image = (getattr(self.params, 'image', None) or DEFAULT_IMAGE)
self.machine_type = (getattr(self.params, 'machinetype', None)
or DEFAULT_MACHINE_TYPE)
if not self.project:
sys.stderr.write(
'\nPlease specify a project using the --project option.\n\n')
os.exit(1)
self.api = GceApi('jmeter_cluster', CLIENT_ID, CLIENT_SECRET,
self.project, self.zone)
return self.api
def _MakeInstanceName(self, index):
return '%s-%03d' % (self.params.prefix, index)
def _WaitForAllInstancesRunning(self):
"""Waits until all instances have status 'RUNNING'."""
size = self.params.size
while True:
logging.info('Checking instance status...')
status_count = {}
for index in xrange(size):
instance_info = self._GetGceApi().GetInstance(
self._MakeInstanceName(index))
if instance_info:
status = instance_info['status']
else:
status = 'NOT YET CREATED'
status_count[status] = status_count.get(status, 0) + 1
logging.info('Total instances: %d', size)
for status, count in status_count.items():
logging.info(' %s: %d', status, count)
if status_count.get('RUNNING', 0) == size:
break
logging.info('Wait for instances RUNNING...')
time.sleep(GCE_STATUS_CHECK_INTERVAL)
def _WaitForAllInstancesSshReady(self):
"""Waits until all instances are ready to SSH."""
size = self.params.size
while True:
ssh_ready = 0
for index in xrange(size):
instance_name = self._MakeInstanceName(index)
command = ('gcutil ssh --project=%s --zone=%s '
'--ssh_arg "-o ConnectTimeout=10" '
'--ssh_arg "-o StrictHostKeyChecking=no" '
'%s exit') % (self.project, self.zone, instance_name)
logging.debug('SSH availability check command: %s', command)
if subprocess.call(command, shell=True):
# Non-zero return code indicates an error.
logging.info('SSH is not yet ready on %s', instance_name)
else:
ssh_ready += 1
logging.info('%d instances out of %d are ready for SSH', ssh_ready, size)
if ssh_ready == size:
break
logging.info('Wait for SSH to get ready on instances...')
time.sleep(GCE_STATUS_CHECK_INTERVAL)
def Start(self):
"""Starts up JMeter server cluster."""
size = self.params.size
startup_script = open(JMeterFiles.GetStartupScriptPath()).read() % (
CLOUD_STORAGE)
for index in xrange(size):
instance_name = self._MakeInstanceName(index)
logging.info('Starting instance: %s', instance_name)
self._GetGceApi().CreateInstanceWithNewBootDisk(
instance_name, self.machine_type, self.image,
startup_script=startup_script,
service_accounts=[
'https://www.googleapis.com/auth/devstorage.read_only'],
metadata={'id': index})
self._WaitForAllInstancesRunning()
self._WaitForAllInstancesSshReady()
self.SetPortForward()
def SetPortForward(self):
"""Sets up SSH port forwarding."""
project = getattr(self.params, 'project', None) or DEFAULT_PROJECT
server_list = []
for index in xrange(self.params.size):
instance_name = self._MakeInstanceName(index)
logging.info('Setting up port forwarding for: %s', instance_name)
server_port = 24000 + index
server_rmi_port = 26000 + index
client_rmi_port = 25000
# Run "gcutil ssh" command to activate SSH port forwarding.
command = [
'gcutil', '--project', project, 'ssh',
'--ssh_arg', '-oStrictHostKeyChecking=no',
'--ssh_arg', '-L%(server_port)d:127.0.0.1:%(server_port)d',
'--ssh_arg', '-L%(server_rmi_port)d:127.0.0.1:%(server_rmi_port)d',
'--ssh_arg', '-R%(client_rmi_port)d:127.0.0.1:%(client_rmi_port)d',
'--ssh_arg', '-N',
'--ssh_arg', '-f',
'%(instance_name)s']
subprocess.call(
' '.join(command) % {
'instance_name': instance_name,
'server_port': server_port,
'server_rmi_port': server_rmi_port,
'client_rmi_port': client_rmi_port,
},
shell=True)
server_list.append('127.0.0.1:%d' % server_port)
# Update remote_hosts configuration in client configuration.
JMeterFiles.RewriteConfig('(?<=^remote_hosts=).*',
','.join(server_list))
@staticmethod
def _DeleteResource(filter_string, list_method, delete_method, get_method):
"""Deletes Compute Engine resource that matches the filter.
Args:
filter_string: Filter string of the resource.
list_method: Method to list the resources.
delete_method: Method to delete the single resource.
get_method: Method to get the status of the single resource.
"""
while True:
list_of_resources = list_method(filter_string)
resource_names = [i['name'] for i in list_of_resources]
if not resource_names:
break
for name in resource_names:
logging.info(' %s', name)
delete_method(name)
for _ in xrange(10):
still_alive = []
for name in resource_names:
if get_method(name):
still_alive.append(name)
else:
logging.info('Deletion complete: %s', name)
if not still_alive:
break
resource_names = still_alive
time.sleep(GCE_STATUS_CHECK_INTERVAL)
def ShutDown(self):
"""Shuts down JMeter server cluster."""
name_filter = 'name eq ^%s-.*' % self.params.prefix
logging.info('Delete instances:')
self._DeleteResource(
name_filter, self._GetGceApi().ListInstances,
self._GetGceApi().DeleteInstance, self._GetGceApi().GetInstance)
logging.info('Delete disks:')
self._DeleteResource(
name_filter, self._GetGceApi().ListDisks,
self._GetGceApi().DeleteDisk, self._GetGceApi().GetDisk)
def Start(params):
"""Sub-command handler for 'start'."""
jmeter_cluster = JMeterCluster(params)
jmeter_cluster.Start()
def ShutDown(params):
"""Sub-command handler for 'shutdown'."""
jmeter_cluster = JMeterCluster(params)
jmeter_cluster.ShutDown()
def PortForward(params):
"""Sub-command handler for 'portforward'."""
jmeter_cluster = JMeterCluster(params)
jmeter_cluster.SetPortForward()
def Client(unused_params, *additional_args):
"""Sub-command handler for 'client'."""
JMeterFiles.RunJmeterClient(*additional_args)
class JMeterExecuter(object):
"""Class to parse command line arguments and execute sub-commands."""
def __init__(self):
self.parser = argparse.ArgumentParser()
# Specify --noauth_local_webserver as instructed when you use remote
# terminal such as ssh.
class SetNoAuthLocalWebserverAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
oauth2client.tools.gflags.FLAGS.auth_local_webserver = False
self.parser.add_argument(
'--noauth_local_webserver', nargs=0,
action=SetNoAuthLocalWebserverAction,
help='Do not attempt to open browser on local machine.')
self.subparsers = self.parser.add_subparsers(
title='Sub-commands', dest='subcommand')
def _AddGceWideParams(self, subparser):
subparser.add_argument(
'--project',
help='Project name to start Google Compute Engine instances in.')
subparser.add_argument(
'--prefix', default='%s-jmeter' % os.environ['USER'],
help='Name prefix of Google Compute Engine instances. '
'(default "$USER-jmeter")')
subparser.add_argument(
'--zone',
help='Zone name where JMeter server cluster is located.')
def _AddStartSubcommand(self):
"""Add 'start' subcommand to argument parser."""
parser_start = self.subparsers.add_parser(
'start',
help='Start JMeter server cluster. Also sets port forwarding.')
parser_start.add_argument(
'size', default=3, type=int, nargs='?',
help='JMeter server cluster size. (default 3)')
self._AddGceWideParams(parser_start)
parser_start.add_argument(
'--image',
help='Machine image of Google Compute Engine instance.')
parser_start.add_argument(
'--machinetype',
help='Machine type of Google Compute Engine instance.')
parser_start.set_defaults(handler=Start)
def _AddShutdownSubcommand(self):
"""Add 'shutdown' subcommand to argument parser."""
parser_shutdown = self.subparsers.add_parser(
'shutdown',
help='Tear down JMeter server cluster.')
self._AddGceWideParams(parser_shutdown)
parser_shutdown.set_defaults(handler=ShutDown)
def _AddPortforwardSubcommand(self):
"""Add 'portforward' subcommand to argument parser."""
parser_portforward = self.subparsers.add_parser(
'portforward',
help='Set up JMeter SSH port forwarding.')
parser_portforward.add_argument(
'size', default=3, type=int, nargs='?',
help='JMeter server cluster size. (default 3)')
self._AddGceWideParams(parser_portforward)
parser_portforward.set_defaults(handler=PortForward)
def _AddClientSubcommand(self):
"""Add 'client' subcommand to argument parser."""
parser_client = self.subparsers.add_parser(
'client',
help='Start JMeter client. Can take additional parameters passed to '
'JMeter.')
parser_client.set_defaults(handler=Client)
def ParseArgumentsAndExecute(self, argv):
"""Parses command arguments and starts sub-command handler.
Args:
argv: Parameters in list of strings.
"""
self._AddStartSubcommand()
self._AddShutdownSubcommand()
self._AddPortforwardSubcommand()
self._AddClientSubcommand()
# Parse command-line arguments and execute corresponding handler function.
params, additional_args = self.parser.parse_known_args(argv)
# Execute handler function given by "handler" parameter.
params.handler(params, *additional_args)
def main():
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(module)s:%(levelname)s] %(message)s')
executer = JMeterExecuter()
executer.ParseArgumentsAndExecute(sys.argv[1:])
if __name__ == '__main__':
main()