-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathgetput
More file actions
executable file
·2530 lines (2124 loc) · 90.6 KB
/
getput
File metadata and controls
executable file
·2530 lines (2124 loc) · 90.6 KB
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python -u
# Copyright 2015 Hewlett-Packard Development Company, L.P.
# Use of this script is subject to HP Terms of Use at
# http://www8.hp.com/us/en/privacy/terms-of-use.html.
# 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.
# debug
# 1 - print some basic stuff. inclucing test starts info
# 2 - show more details about process startup/shutdown
# 4 - report container header info
# 8 - show name of container being used
# 16 - show inputs for starting multiprocessing
# 32 - show trandIDs/latencies, only make sense for small values of -n
# 64 - show connection information
# 128 - trace execution to log in /tmp
# 256 - report end of test/set/proc sleeps
# 1024 - report object etag
# logops masks
# 1 - log all latencies
# 2 - log traces [type 3 calls]
# 4 - log latencies > :latency
import sys
import os
import re
import struct
import random
import requests
import signal
import socket
import string
import time
import inspect
import cStringIO
import requests
import md5
import hashlib
from random import randint
from optparse import OptionParser, OptionGroup
from multiprocessing import Pool, Value
from urlparse import urlparse
from swiftclient import Connection
from swiftclient import ClientException
from swiftclient import put_object
# This is for process synchronization and warning/error threshold secs
counter = None
threshold_conn = 5
threshold_hang = 300
# Handy for tracing execution of getput itself
def logexec(text):
if debug & 128:
logfile = '/tmp/getput-exec-%s.log' % (time.strftime('%Y%m%d'))
log = open(logfile, 'a')
log.write('%s %s\n' % (time.strftime('%H:%M:%S', time.gmtime()), text))
log.close()
def exclogger(text):
exc = open(exclog, 'a')
exc.write("%s\n" % text)
exc.close()
def error(text, exit_flag=True):
"""
Main error reporting, usually exits
"""
print "Error -- Host: %s getput: %s" % (hostname, text)
if exit_flag:
sys.exit(0)
def build_object():
"""
build a fixed length non-compressible object (unless --objopts
is 'c') based on size specified by -s
"""
global md5_digest
# build a fixed size object of appropriate size with RANDOM bytes so we can
# be sure they all get transfered and not compressed, but if '--objopts c'
# use all the same so we WILL. join() a lot faster than +
temp = ''
count = 0
if not options.objopts or not re.search('c', options.objopts):
while (count < (32 * 1024)):
num = int(random.random() * 255)
temp = ''.join([temp, struct.pack('B', num)])
count = count + 1
else:
temp = ' ' * 32 * 1024
# replicate it exponentially for speed
fixed_object = temp
while (len(fixed_object) < osize):
fixed_object = ''.join([fixed_object, fixed_object])
# trim it down if necessary
fixed_object = fixed_object[:osize]
m = md5.new()
m.update(fixed_object)
md5_digest = m.hexdigest()
if debug & 1024:
print "Obj MD5:", md5_digest
return(fixed_object)
def md5check(oper, cname, objname, response, md5_digest):
etag = response['headers']['etag']
if etag != md5_digest:
txid = response['headers']['x-trans-id']
print "MD5 Error - on %s, TransID: %s for %s/%s, %s != %s" % \
(oper, txid, cname, objname, md5_digest, etag)
def reset_last(num_procs):
"""
Sets the ending object numbers for each process to get, put or delete
some explanation needed... last[] contains the max number of objects to
PUT, GET or DELETE per process. In the case of multiple sets of tests,
these need to be reset to the original value specified with -n and if a
single value spread across all procs. Since a PUT test also resets last[]
to contain actual number of objects so GET/DEL will need to know how many
there are. The errors can only happen looking at original values of -n.
"""
global last
last = []
if options.nobjects and re.search(':', options.nobjects):
for string in options.nobjects.split(':'):
try:
last.append(int(string))
except ValueError:
error('-n must be a set of : separated integers')
else:
for i in range(num_procs):
# reset everything to what was specified with -n and if not there
# we already know there's a runtime so set a huge max objects
if options.nobjects:
numobj = int(options.nobjects)
else:
numobj = 999999
try:
last.append(numobj)
except ValueError:
error('-n must be an integer')
def getenv(varname):
"""
get value for environment variable
"""
try:
value = os.environ[varname]
except KeyError:
value = ''
return(value)
def parse_creds(creds_file=None):
"""
parse credentials either from environment OR credentials file
"""
# remember, --creds overrides environment
stnum = 0
stvars = {}
for varname in ['ST_AUTH', 'ST_USER', 'ST_KEY']:
stvars[varname] = getenv(varname)
if stvars[varname] != '':
stnum += 1
osnum = 0
osvars = {}
for varname in ['OS_AUTH_URL', 'OS_USERNAME', 'OS_PASSWORD', \
'OS_TENANT_ID', 'OS_TENANT_NAME', \
'OS_PROJECT_NAME', 'OS_PROJECT_ID', \
'OS_PROJECT_DOMAIN_NAME', 'OS_PROJECT_DOMAIN_ID', \
'OS_USER_DOMAIN_NAME', 'OS_USER_DOMAIN_ID', \
'OS_REGION_NAME', 'OS_SERVICE_TYPE', 'OS_AUTH_VERSION', \
'OS_ENDPOINT_TYPE', 'OS_IDENTITY_API_VERSION', \
'OS_STORAGE_URL', \
'OS_SWIFTCLIENT_INSECURE', 'OS_CACERT', 'OS_CERT']:
osvars[varname] = getenv(varname)
if osvars[varname] != '':
osnum += 1
rgwnum = 0
rgwvars = {}
for varname in ['RGW_ACCESS_ID', 'RGW_SECRET_KEY', 'RGW_HOST', 'RGW_PORT']:
rgwvars[varname] = getenv(varname)
if rgwvars[varname] != '':
rgwnum += 1
if creds_file:
try:
f = open(creds_file, 'r')
for line in f:
if re.match('\#|\s*$', line):
continue
line = line.rstrip('\n')
search = re.search('(ST|OS|RGW|SWIFTCLIENT)_(.*)=(.*)', line)
if search:
value = search.group(3).strip(";'\"")
if search.group(1) == 'ST':
stvars["ST_" + search.group(2)] = value
stnum += 1
elif search.group(1) == 'OS':
osvars["OS_" + search.group(2)] = value
osnum += 1
elif search.group(1) == 'RGW':
rgwvars["RGW_" + search.group(2)] = value
rgwnum += 1
elif search.group(1) == 'SWIFTCLIENT':
osvars["SWIFTCLIENT_" + search.group(2)] = value
osnum += 1
except IOError, err:
error("Couldn't read creds file: " + creds_file)
if not s3:
if stnum > 0 and osnum > 0:
error('you have both ST_ and OS_style varibles defined' + \
' in your environment and you must only have 1 type')
if stnum > 0 and stnum != 3:
error('you have at least 1 ST_ style variable defined but not all 3')
if osnum > 0:
if osvars['OS_AUTH_URL'] == '' or osvars['OS_USERNAME'] == '' \
or osvars['OS_PASSWORD'] == '':
error('your environment has at least 1 OS_ style variable ' + \
'defined but not OS_AUTH_URL, OS_USERNAME or OS_PASSWORD')
if osvars['OS_TENANT_NAME'] == '' and osvars['OS_TENANT_ID'] == '' \
and osvars['OS_PROJECT_NAME'] == ''\
and osvars['OS_PROJECT_ID'] == '':
error('your environment has at least 1 OS_ style variable ' + \
'defined but not OS_TENANT_NAME, OS_TENANT_ID or ' + \
'OS_PROJECT_NAME, OS_PROJECT_ID')
username = password = authurl = ''
if stnum > 1:
authurl = stvars['ST_AUTH']
username = stvars['ST_USER']
password = stvars['ST_KEY']
elif osnum > 1:
authurl = osvars['OS_AUTH_URL']
del osvars['OS_AUTH_URL']
username = osvars['OS_USERNAME']
del osvars['OS_USERNAME']
password = osvars['OS_PASSWORD']
del osvars['OS_PASSWORD']
return((authurl, username, password, osvars))
# I hate multiple returns, but given the way this is called it makes things lot easier
else:
rgw_access_id = rgwvars['RGW_ACCESS_ID']
rgw_secret_key = rgwvars['RGW_SECRET_KEY']
rgw_host = rgwvars['RGW_HOST']
rgw_port = rgwvars['RGW_PORT']
if rgw_access_id == '' or rgw_secret_key == '' or rgw_host == '' or rgw_port == '':
error("not all 4 s3 access variables specified with --creds or found in environment")
return((rgw_access_id, rgw_secret_key, rgw_host, rgw_port))
def main(argv):
"""
read/parse switches
"""
global debug, options, procset, sizeset, ldist10, s3
global username, password, authurl, osvars, errmax
global latexc_min, latexc_max, latexc_filt, exclog, excopt, \
sha_size, obj_max_proc, put_test, put_test_first
ldist10 = 0
procset = [1]
latexc_min = latexc_max = 9999
parser = OptionParser(add_help_option=False)
group0 = OptionGroup(parser, 'these are the basic switches')
group0.add_option('-c', '--cname', dest='cname',
help='container name')
group0.add_option('-d', '--debug', dest='debug',
help='debugging mask', default=0)
group0.add_option('-n', '--nobjects', dest='nobjects',
help='containter/object numbers as a value OR range')
group0.add_option('-o', '--obj', dest='oname',
help='object name prefix')
group0.add_option('-p', '--policy', dest='policy',
help='container storage policy', default='')
group0.add_option('-r', '--runtime', dest='runtime',
help="runtime in secs")
group0.add_option('-s', '--size', dest='sizeset',
help='object size(s)')
group0.add_option('-t', '--tests', dest='tests',
help='tests to run [gpd]')
group0.add_option('-h', '--help', dest='help',
help='show this help message and exit',
action='store_true')
group0.add_option('-v', '--version', dest='version',
help='print version and exit',
action='store_true')
parser.add_option_group(group0)
groupa = OptionGroup(parser, 'these switches control the output')
groupa.add_option('--echo', dest='echo',
help='echo command', action='store_true')
groupa.add_option('--ldist', dest='ldist',
help="report latency distributions at this granularity")
groupa.add_option('--nohead', dest='nohead',
help="do not print header with results",
action='store_true', default=False)
groupa.add_option('--psum', dest='psum',
help="include process summary in output",
action='store_true', default=False)
groupa.add_option('--putsperproc', dest='putsperproc',
action='store_true', default=False,
help='list numbers of puts by each process')
parser.add_option_group(groupa)
groupc = OptionGroup(parser, 'these switches effect behavior')
groupc.add_option('--cont-nodelete', dest='cont_nodelete',
help="do not delete container after a delete test",
action='store_true', default=False)
groupc.add_option('--ctype', dest='ctype', default='byproc',
help="container type: shared|bynode|byproc")
groupc.add_option('--errmax', dest='errmax',
help="quit after this number of errors, [def=5]",
default=5)
groupc.add_option('--exclog', dest='exclog',
help="write latencies to log instead or terminal")
groupc.add_option('--extra', dest='extra',
help="defined value for X-Trans-Id-Extra")
groupc.add_option('--headers', dest='headers',
help="additional headers")
groupc.add_option('--insecure', dest='insecure',
action='store_true', default=False,
help="allow access without verifying SSL certs")
groupc.add_option('--latexc', dest='latexc',
help="stop when max latency matches exception")
groupc.add_option('--logops', dest='logops',
help="log latencies for all operations",
default='0')
groupc.add_option('--mixopts', dest='mixopts', default='',
help='mixed test options [m]')
groupc.add_option('--objopts', dest='objopts', default='',
help='object options [acfmru]')
groupc.add_option('--objoffset', dest='objoffset', default='0',
help='object number offset for flat hierarchies')
groupc.add_option('--objseed', dest='objseed', default='0',
help='seed for random object naming')
groupc.add_option('--printheader', dest='printheader',
action='store_true',
help="print a one line header and exit")
groupc.add_option('--preauthtoken', dest='preauthtoken',
default='',
help="use this rather then the one returned")
groupc.add_option('--procs', dest='procset',
help="number of processes to run")
groupc.add_option('--proxies', dest='proxies', default='',
help='bypass load balancer and connect directly')
groupc.add_option('--quiet', dest='quiet', default=False,
help='suppress api errors & sync time warnings',
action='store_true')
groupc.add_option('--quiton404', dest='quiton404',
help='exit 404', action='store_true')
groupc.add_option('--range', dest='range', default='',
help='get object by this range')
groupc.add_option('--repeat', dest='repeats',
help='number of time to repeat --num tests')
groupc.add_option('--retries', dest='retries', default='5',
help='number of time to retry failed test')
groupc.add_option('--retry-on-ratelimit', dest='retry_on_ratelimit',
help='Let swift client retry on ratelimit hit', action='store_true')
groupc.add_option('--sleeps', dest='sleeps',
help='times to sleep at various test points')
groupc.add_option('--s3', dest='s3', action='store_true',
help='use s3 api')
groupc.add_option('--scheme', dest='scheme', default='',
help='authurl connection scheme, http|https')
groupc.add_option('--warnexit', dest='warnexit',
help='exit on warnings', action='store_true')
parser.add_option_group(groupc)
groupb = OptionGroup(parser, 'multi-node access')
groupb.add_option('--creds', dest='creds',
help='credentials')
groupb.add_option('--rank', dest='rank',
help='rank among clients, used in obj/container names',
default='0')
groupb.add_option('--sync', dest='synctime',
help='time, in seconds since epoch, to start test')
groupb.add_option('--utc', dest='utc',
action='store_true', default=False,
help='append utc time to container names')
parser.add_option_group(groupb)
try:
(options, args) = parser.parse_args(argv)
except:
print 'invalid command'
sys.exit()
if options.help:
parser.print_help()
sys.exit()
if options.version:
print 'getput V%s\n\n%s' % (version, copyright)
sys.exit()
s3 = options.s3
if s3:
global boto
import boto
import boto.s3.connection
# we have to do before printheader() in case we want
# to include latency historgram headers
if options.ldist:
try:
if int(options.ldist) > 3:
error("--ldist > 3 not supported")
except ValueError:
error('--ldist must be an integer')
ldist10 = 10 ** int(options.ldist)
if options.printheader:
print_header()
sys.exit()
# G e t C r e d e n t i a l s f r o m E n v o r C r e d s F i l e
if not s3:
(authurl, username, password, osvars) = parse_creds(options.creds)
if username == '' or password == '' or authurl == '':
error('specify credentials with --creds OR set ST_* variables')
else:
(rgw_access_id, rgw_secret_key, rgw_host, rgw_port) = parse_creds(options.creds)
# big time hack to make easier to constently call connect()
username = rgw_access_id
password = rgw_secret_key
authurl = rgw_host + ':' + rgw_port
osvars = {}
try:
debug = int(options.debug)
except:
error('-d must be an integer')
try:
errmax = int(options.errmax)
except ValueError:
error('--errmax must be an integer')
# R e q u i r e d : - - t e s t s & - - c n a m e
# note -- mixed_test means one of possibly multiple tests is mixed but we
# don't know which one(s). We also need to know if there was a pure PUT
# test preceding the first mixed test and for that use put_test_first.
if options.tests:
put_test = put_test_first = mixed_test = False
for test in options.tests.split(','):
if not re.match('^p\d+g\d+$', test) and not re.match('^[pgd]$', test):
error('-test must be combinations of p, g, d and pxgy')
if test == 'p':
put_test = True
if re.match('^p\d+g\d+$', test):
mixed_test = True
num = options.nobjects
if put_test:
put_test_first = True
if not put_test and (not num or not re.search(':', num)):
error("mixed workload must be preceeded by 'p' test OR include putsperproc with -n")
else:
error('define test list with -t')
if options.mixopts:
if options.mixopts != 'm':
error("only valid value for --mixopts is 'm'")
# cname and oname actually defined in init_test()
if not options.cname:
error('specify container name with -c')
obj_max_proc = 0 # only set when 'm' option
if options.objopts:
# if you include 'r', you can optionally include a length too, so
# first remove everything but the 'r', 'm' and digits
objopts = re.sub('[acfu]*', '', options.objopts)
if re.search('r', objopts):
match = re.search('r(\d*)', objopts)
sha_size = 128 if match.group(1) == '' else int(match.group(1))
objopts = re.sub(match.group(0), '', objopts)
if re.search('m', objopts):
if options.ctype != 'shared':
error("--objopts m only makes sense with shared containers")
match = re.search('m(\d*)', objopts)
if match.group(1):
obj_max_proc = int(match.group(1))
objopts = re.sub(match.group(0), '', objopts)
else:
error("--objopt requires max procs")
if objopts != '':
error("unknown --objopts values: %s" % objopts)
if options.objoffset and options.objoffset != '0':
try:
objoffset = int(options.objoffset)
except ValueError:
error("--objoffset must be an integer")
if re.search('a', options.objopts):
error("--objnum and append mode are mutually exclusive")
if not re.search('f', options.objopts):
error("--objoffset only makes sense for flat hierarchies")
try:
objoffset = int(options.objoffset)
except ValueError:
error("--objoffset must be an integer")
# T e s t D e p e n d e n t S w i t c h e s
if options.range != '':
#if not re.search('g', options.tests):
# error("--range only applies to 'get' tests")
for value in options.range.split(','):
if not re.match('\d+-\d+$', value):
error("range '%s' must be in min-max format" % (value))
if re.match('[gpd]', options.tests):
if not options.oname:
error('get, put and delete tests require object name')
if options.sizeset:
if re.search(',', options.sizeset):
if not re.match('p', options.tests):
error('multiple obj sizes require PUT test')
sizeset = []
for size in options.sizeset.split(','):
match = re.match('(\d+)([kmg]?\Z)', size, re.I)
if (match):
sizeset.append(size)
else:
error('object size must be a number OR number + k/m/g')
else:
error('object size required')
# O p t i o n a l
if options.procset:
procset = []
for p in options.procset.split(','):
try:
proc = int(p)
procset.append(proc)
except ValueError:
error('--procs must be an integer')
# a real pain but we have to recheck for each value of --procs
for test in options.tests.split(','):
match = re.search('p(\d+)g(\d+)', test)
if match:
tot = int(match.group(1)) + int(match.group(2))
min = int(proc/tot)
if min * tot != proc:
error("--procs %s not even multiple of %s" % (p, test))
if options.runtime:
if not re.match('\d+$', options.runtime):
error('--runtime must be an integer')
if options.ctype != None:
if not re.match('shared|bynode|byproc', options.ctype):
error("invalid ctype, expecting: 'shared|bynode|byproc'")
if options.rank and not re.match('\d+$', options.rank):
error('--rank must be an integer')
# initialze last[] for all processes based on first value of -n
if options.nobjects:
reset_last(procset[0])
elif not options.runtime:
error('specify at least one of -n and/or --runtime')
if options.repeats and not re.match('\d+$', options.repeats):
error('-r must be an integer')
if options.synctime and not re.match('\d+$', options.synctime):
error('sync time must be an integer')
if args:
print "Extra command argument(s):", args
sys.exit()
if options.latexc:
latexc_filt = 'pg'
pieces = options.latexc.split(':')
if len(pieces) > 1:
options.latexc = pieces[0]
latexc_filt = pieces[1]
if not re.match('[pgd]+$', latexc_filt):
error('--latexc filter must be combination of p and g')
if re.search('-', options.latexc):
latexc_min, latexc_max = options.latexc.split('-')
else:
latexc_min = options.latexc
latexc_max = 9999
latexc_min = float(latexc_min)
latexc_max = float(latexc_max)
if options.exclog:
if not options.latexc:
error('--exclog required --latexc')
if re.search(':', options.exclog):
exclog, excopt = options.exclog.split(':')
if excopt != 'c':
error('only valid --excopt options is c')
else:
exclog = options.exclog
excopt = ''
def cvtFromKMG(str):
"""
converts a string containing K, M or G to its equivilent number
"""
# remember, we already verify sizeset[]
match = re.match('(\d+)([kmg]?\Z)', str, re.I)
size = int(match.group(1))
type = match.group(2).lower()
if type == '':
objsize = size
if type == 'k':
objsize = size * 1024
elif type == 'm':
objsize = size * 1024 * 1024
elif type == 'g':
objsize = size * 1024 * 1024 * 1024
return(objsize)
def cvt2KMG(num):
"""
converts a string which is a multiple of 1024 to the form: number[KMG]
"""
# only do this is exact multiple of 1024
temp = num
suffix = ''
if (int(num / 1024) * 1024 == num):
modifiers = 'kmg'
while(temp > 1023):
temp = temp / 1024
suffix = modifiers[0]
modifiers = modifiers[1:]
return(str(temp) + suffix)
native_close = True
if not hasattr(Connection, 'close'):
native_close = False
class MyConnection(Connection):
def close(self):
if self.http_conn:
self.http_conn[1].close()
def connect(authurl, username, password, osvars, \
preauthurl=None, preauthtoken=None):
"""
make a connection using swift or s3 api
"""
if s3:
s3_access_key = username
s3_secret_key = password
s3_host, s3_port = authurl.split(':')
s3_port = int(s3_port)
if debug & 64:
print "Connect - Access: %s Secret: %s Host: %s Port: %s" % \
(s3_access_key, s3_secret_key, s3_host, s3_port)
try:
connection = boto.connect_s3(
aws_access_key_id = s3_access_key,
aws_secret_access_key = s3_secret_key,
host = s3_host,
#is_secure=False, # uncomment if you are not using ssl
calling_format = boto.s3.connection.OrdinaryCallingFormat(),
port=s3_port,
)
except Exception as err:
import traceback
print "Connect failure: %s" % err
logexec('connect() exception: %s %s' % (err, traceback.format_exc()))
return(-1)
if debug & 64:
print "Connected to S3", connection
return(connection)
if osvars['OS_AUTH_VERSION'] != '':
auth_version = osvars['OS_AUTH_VERSION']
elif osvars['OS_IDENTITY_API_VERSION'] != '':
auth_version = osvars['OS_IDENTITY_API_VERSION']
elif re.search('v1.0', authurl):
auth_version = '1.0'
elif re.search('v2.0', authurl):
auth_version = '2.0'
elif re.search('v3', authurl):
auth_version = '3'
# simple 1:1 mapping to parameter value
cacert = None
if 'OS_CACERT' in osvars:
cacert = osvars['OS_CACERT']
if 'OS_STORAGE_URL' in osvars:
osvars['object_storage_url'] = osvars['OS_STORAGE_URL']
if osvars['OS_SWIFTCLIENT_INSECURE'] != '':
insecure = osvars['OS_SWIFTCLIENT_INSECURE']
else:
insecure = options.insecure
insecure = 1
retries = int(options.retries)
# these get specified in opts dictionary noting BOTH tenant_id
# and _name must be defined in dictionary
os_options = {}
for key, value in osvars.iteritems():
if value == "":
continue
key = key.replace("OS_", "")
key = key.lower()
os_options[key] = value
if preauthurl != None:
authurl = ''
if debug & 64:
print "Connect - User: %s Key: %s Options: %s" % \
(username, password, os_options)
print "Connect - Retries: %d AuthVer: %s AuthURL: %s" % \
(retries, auth_version, authurl)
print "Connect - Insecure: %s Cert: %s" % \
(insecure, cacert)
print "Connect - PreauthURL: %s PreauthToken: %s" % \
(preauthurl, preauthtoken)
# get the connection object
if preauthurl:
logexec('connect - PreauthURL: %s PreauthToken: %s' % \
(preauthurl, preauthtoken))
try:
response = {}
if native_close:
connection = \
Connection(authurl=authurl,
user=username,
key=password,
auth_version=auth_version,
retries=retries,
preauthurl=preauthurl,
preauthtoken=preauthtoken,
insecure=insecure,
cacert=cacert,
os_options=os_options,
retry_on_ratelimit=options.retry_on_ratelimit)
else:
connection = \
MyConnection(authurl=authurl,
user=username,
key=password,
auth_version=auth_version,
preauthurl=preauthurl,
preauthtoken=preauthtoken,
insecure=insecure,
cacert=cacert,
os_options=os_options,
retry_on_ratelimit=options.retry_on_ratelimit)
except Exception as err:
import traceback
print "Connect failure: %s" % err
logexec('connect() exception: %s %s' % (err, traceback.format_exc()))
return(-1)
# Just created the connection object, so make sure we're really connected
# Errors are very rare, but if something misconfigured we want to know!
logexec('connected')
try:
headers = connection.head_account()
except Exception as err:
import traceback
print "%s head_account failure: %s" % (ptime(time.time()), err)
logexec('head_account() exception: %s %s' % \
(err, traceback.format_exc()))
# I'm not happy with the pattern I'm matching but I've seen
# at least these 2 types of messages when proxies were set
# and head_account failed.
failure = "%s" % err
if re.search('Not Found|Unable to establish connection', failure):
print " => are proxies or the lack of them the problem? <="
return(-1)
if debug & 4:
print "Headers: ", headers
container_count = int(headers.get('x-account-container-count', 0))
if debug & 64:
print "connected!", connection
return(connection)
def logger(optype=None, data=None, inst=None, test_time=None):
"""
write operation details to a log file, including start/stop times
and latencies
types:
1 - open log
2 - latency record
3 - tracing record
4 - errors
9 - close logfile
mask
1 - just latencies
2 - just traces
4 - exception traces
"""
global logfiles
if not logmask:
return
if optype == 9:
logfiles[inst].close()
return()
# should we log?
if optype == 2 and (not logmask & 5) or (optype == 3 and not logmask & 2):
return()
if optype == 1:
# data is actually the name of the test for type 1 call
filename = '/tmp/getput-%s-%d-%d.log' % (data, inst, int(test_time))
logfiles[inst] = open(filename, 'w')
else:
secs = time.time()
usecs = '%.3f' % (secs - int(secs))
now = "%s.%s" % (time.ctime(secs).split()[3], usecs.split('.')[1])
logfiles[inst].write('%s %f %s\n' % (now, secs, data))
logfiles[inst].flush()
def api_error(type, instance, cname, oname, err, response=None):
"""
Report SWIFT api errors
"""
time_now = time.strftime('%H:%M:%S')
if not s3:
status = err.http_status
error_string = '%s %s API Error %d' % (time_now, type, status)
try:
if response:
error_string += ' TransID: %s' % response['headers']['x-trans-id']
except KeyError:
pass
error_string += ' %s/%s' % (cname, oname)
else:
status = err.status
error_string = '%s %s API Error %d' % (time_now, type, status)
if not options.quiet:
print error_string
logger(4, 'ApiError: %s ' % status, instance)
def latcalc(latency, min, max, tot, dist):
"""
track total latency times and also incrememnt appropriate histogram bucket
"""
tot = tot + latency
if latency < min:
min = latency
if latency > max:
max = latency
# Distribution: 0 1 2 3 4 5 10 20 30 40 50
# bucket 5 contains values of 5.xxx whereas higher numbered bucket
# contains values not including that value so bucket 6 goes up to 9.999
# and 7 up to 19.999
bucket = int(latency * ldist10)
if bucket >= 5:
bucket = int(bucket / 10) + 5
if bucket > 10:
bucket = 10
dist[bucket] = dist[bucket] + 1
return(min, max, tot)
def reset_url(url, new_address=None):
"""
reset url's scheme and port based on --scheme
and optional addresss
"""
if s3:
return('')
# parse url's scheme, addr, port and path
new_url = url
pieces = urlparse(new_url)
scheme = pieces[0]
address = pieces[1]
if re.search(':', address):
address, port = address.split(':')
else:
port = ''
path = pieces[2]
# if an address specified, we reset that one
if new_address:
address = new_address
# if user specificed --scheme, we use both the scheme and/or port
# depending on which are named
if options.scheme != '':
pieces = options.scheme.split(':')
if pieces[0] != '':
scheme = pieces[0]
if len(pieces) > 1:
port = pieces[1]
new_url = '%s://%s' % (scheme, address)
if port != '':
new_url += ':%s' % port
new_url += path
if url != new_url and debug & 64:
print "Reset: %s To: %s" % (url, new_url)
return(new_url)
#########################
# Object Operations
#########################
def get_offset(procs, instance, csize):
"""
when doing random I/O, the object numbering depends on container type
and doing it here makes sure consistent for ALL types of operations
"""