/
benchmarkrunner.py
1136 lines (932 loc) · 41.6 KB
/
benchmarkrunner.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
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
# Copyright (c) 2013-2014 Turbulenz Limited
import StringIO
import errno
import json
import re
import csv
import calendar
import posixpath
import subprocess
from sys import argv, executable
from argparse import ArgumentParser
from glob import glob
from os import getcwd, makedirs, walk, curdir, pardir, environ
from os.path import join as path_join, exists as path_exists, abspath, dirname, normpath, relpath
from os.path import splitdrive as path_splitdrive, split as path_split, commonprefix as path_commonprefix
from json import load as json_load, dumps as json_dumps
from threading import Thread, BoundedSemaphore
from shutil import rmtree, copy as shutil_copy, copytree as shutil_copytree
from urllib2 import urlopen, HTTPError, URLError, unquote
from gzip import GzipFile
from socket import error as socket_error
from time import sleep
from datetime import datetime
from re import compile as re_compile
from traceback import format_exc
from logging import basicConfig, CRITICAL, INFO, WARNING, error, info, warn
from runner.browserrunner import BrowserRunner, list_browsers
from runner.utils import simple_config, sh, CalledProcessError
import urlparse
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from SocketServer import TCPServer
(PWD, OS, _) = simple_config()
__version__ = '0.1.0'
BENCHMARK_NAME_DEFAULT = 'WebGL Benchmark'
BENCHMARK_ID_DEFAULT = 'webgl_benchmark'
BENCHMARK_VERSION = '1.0.1'
BENCHMARK_TYPE_DEFAULT = 'offline'
# The name used by the server
SERVERNAME = "WebGL Benchmark Server"
CONFIG_PATH = "scripts/config.js"
CONFIGS_DIR_PATH = "scripts/configurations/"
STREAM_MAPPING_PATH = "assets/config/stream_mapping.json"
CAPTURES_PATH = "capture/"
ASSETS_PATH = "capture/"
OUTPUT_PATH = "output/"
STATIC_TEMPLATE_PATH = "templates/page/"
STATIC_OUTPUT_PATH = "static_page/"
DEFAULT_SEQUENCE_NAME = "Story"
DEFAULT_CAPTURE_NAME = "story_high_particles"
DEFAULT_TEST_NAME = "story_flythrough_full"
NUM_FRAMES = 3600
NUM_FRAMES_BLOCK = 60
CONFIG_TEMPLATE = ( "/* Generated by benchmarkrunner.py */\n"
"%s\n"
"//\n"
"// Name: %s\n"
"//\n"
"// Config - %s\n"
"//\n"
"\n"
"function Config() {}\n"
"Config.prototype = {};\n"
"\n"
"Config.create = function configCreateFn()\n"
"{\n"
" var config = %s.create();\n"
" %s\n"
" %s\n"
" %s\n"
" %s\n"
" %s\n"
" %s\n"
" %s\n"
" return config;\n"
"};" )
RESULTS_BASE_TEMPLATE_VERSION = 2
RESULTS_BASE_TEMPLATE = {
'version': RESULTS_BASE_TEMPLATE_VERSION,
'config': {
'benchmark': {
'name': BENCHMARK_NAME_DEFAULT,
'id': BENCHMARK_ID_DEFAULT,
'version': BENCHMARK_VERSION,
'type': BENCHMARK_TYPE_DEFAULT
},
'hardware': {},
'browser': {},
'playback': {},
'sequences': []
},
'data': {
'sequences': []
}
}
TEMPLATES_DIR = "assets/config/templates"
DATA_DIR = "data"
RESULTS_TEMPLATE_FILENAME = "results_template-default"
RESULTS_TEMPLATE_FILE = RESULTS_TEMPLATE_FILENAME + ".json"
SYSTEM_INFO_FIELDS_WIN = ['OS Name', 'Host Name', 'Total Physical Memory', 'System Type', 'OS Version', 'Processor(s)']
SYSTEM_INFO_MAPPING_WIN = {
'OS Name': ['osName'],
'Host Name': ['machineName'],
'Total Physical Memory': ['totalMemory'],
'System Type': ['platformArchitecture'],
'OS Version': ['osVersion'],
'Processor(s)': ['processor']
}
RELEASE_FILES = [
"mapping_table.json",
"js/whichbrowser-js-0.1.0-min.js"
]
RELEASE_PAGE_FILES = [
"favicon.ico",
"favicon.ico.gz",
"index.html",
"comingsoon.html",
"css/*.css",
"img/*",
"js/*"
]
def mkdir(path, verbose=True):
if verbose:
info('Creating: %s' % path)
try:
makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST:
pass
else:
raise
def generate_filename(name):
return re.sub(r'[^a-zA-Z0-9 ]', '-', name).lower().replace(' ', '_')
def generate_globals(globals_list=None):
if globals_list is None:
return ""
globals_string = ""
for g in globals_list:
globals_string += "/*globals %s: false*/\n" % g
return globals_string
def read_csv(filepath, fields=None):
if not path_exists(filepath):
raise Exception("File does not exist: %s" % filepath)
file_dict = {}
field_dict = {}
def add_to_file_dict(fieldname, value):
file_dict[fieldname] = value
return fieldname
def add_to_field_dict(index, fieldname):
field_dict[index] = fieldname
return index
try:
f = open(filepath, 'r')
reader = csv.reader(f)
rownum = 0
for row in reader:
if rownum == 0:
if fields is None:
for i in range(len(row)):
add_to_field_dict(i, row[i])
else:
for field in row:
if field in fields:
add_to_field_dict(row.index(field), field)
else:
for i in range(len(row)):
if i in field_dict:
add_to_file_dict(field_dict[i], row[i])
rownum += 1
f.close()
except IOError:
raise Exception("Failed to read CSV file: %s" % filepath)
return file_dict
def get_systeminfo(hardware_name):
hardware_dict = {}
hardware_filename = generate_filename(hardware_name)
hardware_dir = path_join(DATA_DIR, hardware_filename)
if OS == 'win32':
print "Gathering System Information..."
timestamp = calendar.timegm(datetime.utcnow().utctimetuple()) * 1000
systeminfo_filename = '%s-systeminfo.csv' % timestamp
systeminfo_dir = path_join(PWD, hardware_dir)
systeminfo_filepath = path_join(systeminfo_dir, systeminfo_filename)
if not path_exists(systeminfo_dir):
mkdir(systeminfo_dir)
info("Generating systeminfo: %s" % systeminfo_filepath)
systeminfo_command_win = ["systeminfo", "/FO", "CSV", ">", systeminfo_filepath]
try:
sh(systeminfo_command_win, shell=True)
except CalledProcessError as e:
raise Exception("System information gathering failed: %s" % e)
info("OS:%s: Looking for systeminfo.csv" % OS)
systeminfo_filenames = []
for _, _, files in walk(hardware_dir):
for name in files:
if name.lower().endswith('systeminfo.csv'):
info("Found systeminfo file: %s" % name)
systeminfo_filenames.append(name)
info("Found %d systeminfo files" % len(systeminfo_filenames))
latest_timestamp = -1
latest_systeminfo_filename = None
for systeminfo_filename in systeminfo_filenames:
timestamp_endindex = systeminfo_filename.rfind("-systeminfo")
if timestamp_endindex == -1:
raise Exception("System info file is formatted incorrectly: %s" % systeminfo_filename)
timestamp_str = systeminfo_filename[0:timestamp_endindex]
if timestamp_str == "":
raise Exception("System info file is missing timestamp: %s" % systeminfo_filename)
try:
timestamp = int(timestamp_str)
if timestamp > latest_timestamp:
latest_timestamp = timestamp
latest_systeminfo_filename = systeminfo_filename
except ValueError as e:
raise Exception("Timestamp cannot be parsed: %s" % e)
if latest_systeminfo_filename is None:
info("No suitable file for systeminfo")
return False
info("Using file: %s" % latest_systeminfo_filename)
try:
timestamp_date = datetime.utcfromtimestamp(latest_timestamp / 1000.0)
timestamp_format = "%Y-%m-%d %H:%M:%S UTC"
timestamp_formatted_str = timestamp_date.strftime(timestamp_format)
info("System Info recorded on: %s" % timestamp_formatted_str)
except ValueError as e:
raise Exception("System Info timestamp cannot be read: %s" % e)
systeminfo_filepath = path_join(hardware_dir, latest_systeminfo_filename)
systeminfo_dict = read_csv(systeminfo_filepath, fields=SYSTEM_INFO_FIELDS_WIN)
def process_systeminfo_field(fieldname):
#TODO: Process totalMemory
if fieldname == 'System Type':
processorArch = ''
windowSystemType = systeminfo_dict[fieldname].lower()
if windowSystemType.find('x64') != -1:
processorArch = 'x64'
elif windowSystemType.find('x86'):
processorArch = 'x86'
# Don't add system type if unknown
if processorArch != '':
hardware_dict[SYSTEM_INFO_MAPPING_WIN[fieldname][0]] = processorArch
else:
hardware_dict[SYSTEM_INFO_MAPPING_WIN[fieldname][0]] = systeminfo_dict[fieldname]
map(process_systeminfo_field, SYSTEM_INFO_FIELDS_WIN)
return hardware_dict
else:
warn('System information not supported for OS: %s' % OS)
return None
def generate_results_template(results_template_name=None,
config_target=None,
hardware_name=None,
base_template_path=None,
benchmark_type=None,
benchmark_id=None,
benchmark_name=None,
benchmark_version=None):
if config_target is None:
raise Exception("Target missing from results template")
if results_template_name is None:
raise Exception("Template name is missing from results template")
info("Generating results template for: %s" % results_template_name)
results_template_filename = results_template_name + '.json'
results_template_path = normpath(path_join(TEMPLATES_DIR, results_template_filename))
if base_template_path:
if results_template_path == base_template_path:
raise Exception("Template name is the same as the base template name")
if not path_exists(base_template_path):
raise Exception("Base template is missing: %s" % base_template_path)
info("Using base template: %s" % base_template_path)
try:
f = open(base_template_path, 'r')
base_template = json.load(f)
f.close()
except IOError:
raise Exception("Failed to read base template file: %s" % base_template_path)
else:
info("Using default base template")
base_template = RESULTS_BASE_TEMPLATE
if base_template['version'] != 1 and base_template['version'] != 2:
raise Exception("Do not understand base template files with version: %s" % base_template['version'])
try:
results_config = base_template['config']
# Add benchmark information
info("Adding configuration: benchmark")
benchmark_config = results_config['benchmark']
if base_template['version'] == 2:
if benchmark_id:
benchmark_config['id'] = benchmark_id
if benchmark_name:
benchmark_config['name'] = benchmark_name
if benchmark_type:
benchmark_config['type'] = benchmark_type
if benchmark_version:
benchmark_config['version'] = benchmark_version
# Add hardware information
info("Adding configuration: hardware")
hardware_config = results_config['hardware']
if hardware_name is not None:
info("Hardware name: %s" % hardware_name)
# A blank hardware name will require the browser to prompt
hardware_config['name'] = hardware_name
# Add system info if it exists
systeminfo_dict = get_systeminfo(hardware_name=hardware_name)
if systeminfo_dict is not None:
info("Adding systeminfo")
for s in systeminfo_dict:
hardware_config[s] = systeminfo_dict[s]
else:
info("No hardware name, skipping systeminfo")
except KeyError as e:
raise Exception("Results template is missing section: %s" % e)
results_template_dir = dirname(results_template_path)
mkdir(results_template_dir)
try:
f = open(results_template_path, 'w')
json.dump(base_template, f)
f.close()
except IOError:
raise Exception("Failed to write results template file: %s" % results_template_path)
def generate_config(config_name="default", config_target=None, allow_querystring=False, results_template_name=None):
info("Generating config for %s" % config_name)
config_inherit = "BaseConfig"
if config_target == "online":
config_inherit = "OnlineConfig"
if config_target == "offline":
config_inherit = "OfflineConfig"
if config_target == "static":
config_inherit = "StaticConfig"
info("Base config: %s" % config_inherit)
globals_list = [config_inherit]
if allow_querystring:
globals_list.append("updateDictFromQueryString")
config_querystring = "updateDictFromQueryString(config);"
else:
config_querystring = ""
config_globals = generate_globals(globals_list)
config_default_sequence_name = "config.defaultSequenceName = \"%s\";" % DEFAULT_SEQUENCE_NAME
config_default_test_name = "config.defaultTestName = \"%s\";" % DEFAULT_TEST_NAME
config_stream_ids = ""
try:
with open(STREAM_MAPPING_PATH, 'r') as f:
stream_mapping = json_load(f)
except IOError:
raise Exception("Missing required file: %s" % STREAM_MAPPING_PATH)
try:
stream_ids = stream_mapping['captureLookUp']
config_stream_ids = "config.streamIDs = " + json_dumps(stream_ids) + ";"
except KeyError:
pass
config_prefix_templates_url = ""
if config_target == "online":
config_desc = "The online configuration, targeting online data"
elif config_target == "offline":
config_desc = "The offline configuration, to run without an internet connection or local server"
elif config_target == "static":
config_desc = "The static configuration, to run hosted on a static site"
elif config_target == "local":
config_desc = "The local configuration, to run with either online or offline data via the local server"
else: #default
config_desc = "The standard configuration, no changes to the base"
config_override = "config.defaultCapture = \"" + config_name + "\";"
if results_template_name is not None:
info("Using resultsTemplate: %s" % results_template_name)
config_results_template = "config.resultsTemplate = \"" + results_template_name + "\";"
else:
info("Using default resultsTemplate")
config_results_template = ""
#TODO: Output to file
config_output = CONFIG_TEMPLATE % ( config_globals, \
config_name, \
config_desc, \
config_inherit, \
config_override, \
config_results_template, \
config_prefix_templates_url, \
config_default_sequence_name, \
config_default_test_name, \
config_stream_ids, \
config_querystring)
try:
info("Writing resultsTemplate: %s" % CONFIG_PATH)
f = open(CONFIG_PATH, 'w')
f.write(config_output)
f.close()
return True
except IOError:
raise Exception("Failed to write config file: %s" % CONFIG_PATH)
def download(url, target_filename=None, retries=0, return_data=False):
num_attempts = retries + 1
while num_attempts:
try:
connection = urlopen(url)
except HTTPError as e:
error('Failed downloading %s: HTTPError %s' % (url, e.code))
except URLError as e:
error('Failed downloading %s: URLError %s' % (url, e))
except socket_error:
info('Error during download%s' % ' will retry in 2 secs' if num_attempts else '')
else:
output = StringIO.StringIO()
try:
if connection.headers.getheader('Content-Encoding', None) == 'gzip':
iobuf = StringIO.StringIO()
iobuf.write(connection.read())
iobuf.seek(0)
output.write(GzipFile(fileobj=iobuf).read())
else:
output.write(connection.read())
if target_filename:
with open(target_filename, 'wb') as f:
f.write(output.getvalue())
if return_data:
return output.getvalue()
except socket_error:
error('Error during download%s' % ' will retry in 2 secs' if num_attempts else '')
num_attempts -= 1
if num_attempts:
sleep(2)
return None
def downloader(path, output_path, bounded_semaphore):
download(path, output_path, retries=3)
bounded_semaphore.release()
def download_assets(config_name="default", max_connections=20, force_download=False):
try:
with open(STREAM_MAPPING_PATH, 'r') as f:
config = json_load(f)
except IOError:
error('Missing stream mapping file: %s' % STREAM_MAPPING_PATH)
exit(1)
except ValueError as e:
error('Stream mapping file %s has invalid format: %s' % (STREAM_MAPPING_PATH, str(e)))
exit(1)
try:
download_id = config['captureLookUp'][config_name]
download_prefix = 'http://%s%s/' % (config['prefixCaptureURL'], config['captureLookUp'][config_name])
except KeyError:
error('No capture path for config name %s' % config_name)
exit(1)
info("Looking for config '%s' data: %s" % (config_name, download_prefix))
output_prefix = capture_output_path = path_join(CAPTURES_PATH, config_name, download_id)
# Create capture path if missing
mkdir(CAPTURES_PATH)
# Create path for capture data
mkdir(output_prefix)
bounded_semaphore = BoundedSemaphore(max_connections)
threads = []
paths = []
if force_download:
info("Force download enabled")
def add_downloader(file_name):
download_path = '%s%s' % (download_prefix, file_name)
output_path = path_join(output_prefix, file_name)
if not path_exists(output_path) or force_download:
threads.append(Thread(target=downloader, args=[download_path, output_path, bounded_semaphore]))
paths.append(download_path)
add_downloader('meta.json')
for start_frame in xrange(0, NUM_FRAMES, NUM_FRAMES_BLOCK):
block_postfix = '%d-%d' % (start_frame, start_frame + NUM_FRAMES_BLOCK - 1)
add_downloader('resources-%s.json' % block_postfix)
add_downloader('frames-%s.json' % block_postfix)
add_downloader('data-%s.bin' % block_postfix)
for (i, t) in enumerate(threads):
t.daemon = True
bounded_semaphore.acquire()
print('Downloading recording %-3d/%d (%s)' % (i + 1, len(threads), paths[i]))
t.start()
for t in threads:
t.join()
threads = []
paths = []
download_prefix = 'http://%s' % config['prefixAssetURL']
output_prefix = ASSETS_PATH
# Create assets path if missing
mkdir(output_prefix)
# Create path for assets
output_staticmax_path = path_join(output_prefix, 'staticmax')
mkdir(output_staticmax_path)
for start_frame in xrange(0, NUM_FRAMES, NUM_FRAMES_BLOCK):
block_postfix = '%d-%d' % (start_frame, start_frame + NUM_FRAMES_BLOCK - 1)
resource_str = path_join(capture_output_path, 'resources-%s.json' % block_postfix)
try:
with open(resource_str) as f:
resources_data = json_load(f)
if resources_data.has_key('resources'):
resources_data = resources_data['resources']
if resources_data.has_key('textures'):
textures = resources_data['textures']
for tex in textures.itervalues():
if tex.has_key('src'):
src = tex['src']
if src:
add_downloader(src)
if resources_data.has_key('videos'):
videos = resources_data['videos']
for video in videos.itervalues():
if video.has_key('src'):
src = video['src']
if src:
add_downloader(src)
except IOError as e:
error('Failed processing assets for %s' % resource_str)
for (i, t) in enumerate(threads):
t.daemon = True
bounded_semaphore.acquire()
print('Downloading assets %-3d/%d (%s)' % (i + 1, len(threads), paths[i]))
t.start()
for t in threads:
t.join()
def copy_release_capture(config_name="default",dummy=False):
try:
with open(STREAM_MAPPING_PATH, 'r') as f:
config = json_load(f)
except IOError:
error('Missing stream mapping file: %s' % STREAM_MAPPING_PATH)
exit(1)
except ValueError as e:
error('Stream mapping file %s has invalid format: %s' % (STREAM_MAPPING_PATH, str(e)))
exit(1)
try:
stream_id = config['captureLookUp'][config_name]
stream_path = normpath(path_join(CAPTURES_PATH, config_name, stream_id))
except KeyError:
error('No capture path for config name %s' % config_name)
exit(1)
info("Looking for config '%s' data: %s" % (config_name, stream_path))
if not path_exists(stream_path):
error('Stream path does not exist: %s' % stream_path)
return
stream_output_path = normpath(path_join(STATIC_OUTPUT_PATH, stream_path))
if path_exists(stream_output_path):
info('Removing dir: %s' % stream_output_path)
if not dummy:
rmtree(stream_output_path)
asset_prefix = ASSETS_PATH
asset_output_prefix = path_join(STATIC_OUTPUT_PATH, CAPTURES_PATH)
# Create assets path if missing
mkdir(asset_output_prefix)
mkdir(stream_output_path)
# Create path for assets
output_staticmax_path = path_join(asset_output_prefix, 'staticmax')
mkdir(output_staticmax_path)
copy_failed = False
def copy_resource_stream(file_name):
asset_path = path_join(stream_path, file_name)
output_path = path_join(stream_output_path, file_name)
if path_exists(asset_path):
info('%s -> %s' % (asset_path, output_path))
if not dummy:
shutil_copy(asset_path, output_path)
else:
error('File does not exist: %s' % asset_path)
copy_failed = True
return
def copy_resource_asset(file_name):
asset_path = normpath(path_join(asset_prefix, file_name))
output_path = normpath(path_join(asset_output_prefix, file_name))
if path_exists(asset_path):
info('%s -> %s' % (asset_path, output_path))
if not dummy:
shutil_copy(asset_path, output_path)
else:
error('File does not exist: %s' % asset_path)
copy_failed = True
return
# Copy all stream data
copy_resource_stream('meta.json')
for start_frame in xrange(0, NUM_FRAMES, NUM_FRAMES_BLOCK):
block_postfix = '%d-%d' % (start_frame, start_frame + NUM_FRAMES_BLOCK - 1)
copy_resource_stream('resources-%s.json' % block_postfix)
copy_resource_stream('frames-%s.json' % block_postfix)
copy_resource_stream('data-%s.bin' % block_postfix)
for start_frame in xrange(0, NUM_FRAMES, NUM_FRAMES_BLOCK):
block_postfix = '%d-%d' % (start_frame, start_frame + NUM_FRAMES_BLOCK - 1)
resource_file = normpath(path_join(stream_path, 'resources-%s.json' % block_postfix))
try:
with open(resource_file) as f:
resources_data = json_load(f)
if resources_data.has_key('resources'):
resources_data = resources_data['resources']
if resources_data.has_key('textures'):
textures = resources_data['textures']
for tex in textures.itervalues():
if tex.has_key('src'):
src = tex['src']
if src:
copy_resource_asset(src)
if resources_data.has_key('videos'):
videos = resources_data['videos']
for video in videos.itervalues():
if video.has_key('src'):
src = video['src']
if src:
copy_resource_asset(src)
except IOError as e:
error('Resource file does not exist: %s' % resource_file)
copy_failed = True
if copy_failed:
error('One or more files failed to copy')
def copy_release():
if path_exists(STATIC_OUTPUT_PATH):
rmtree(STATIC_OUTPUT_PATH)
for pattern in RELEASE_PAGE_FILES:
for f in glob(path_join(STATIC_TEMPLATE_PATH, pattern)):
srcfile = normpath(f)
dstfile = normpath(path_join(STATIC_OUTPUT_PATH, relpath(f, STATIC_TEMPLATE_PATH)))
dst_dir = dirname(dstfile)
if dst_dir != "" and not path_exists(dst_dir):
makedirs(dst_dir)
shutil_copy(srcfile, dstfile)
for f in RELEASE_FILES:
srcfile = normpath(f)
dstfile = normpath(path_join(STATIC_OUTPUT_PATH, f))
dst_dir = dirname(dstfile)
if dst_dir != "" and not path_exists(dst_dir):
makedirs(dst_dir)
shutil_copy(srcfile, dstfile)
shutil_copy("benchmark.canvas.js", normpath(path_join(STATIC_OUTPUT_PATH, "benchmark.canvas.js")))
shutil_copytree(normpath('staticmax'), path_join(STATIC_OUTPUT_PATH, 'staticmax'))
copy_release_capture(config_name=DEFAULT_CAPTURE_NAME)
# shutil_copytree(path_join(CAPTURES_PATH, DEFAULT_CAPTURE_NAME), path_join(STATIC_OUTPUT_PATH, CAPTURES_PATH, DEFAULT_CAPTURE_NAME))
# shutil_copytree(path_join(CAPTURES_PATH, 'staticmax'), path_join(STATIC_OUTPUT_PATH, CAPTURES_PATH, 'staticmax'))
class ServerOptions:
def __init__(self, port = 8070, static = False):
self.port = port
self.static = static
def start_server(output_path, server_options):
# This is a hack to patch slow socket.getfqdn calls that
# BaseHTTPServer (and its subclasses) make.
# See: http://bugs.python.org/issue6085
# See: http://www.answermysearches.com/xmlrpc-server-slow-in-python-how-to-fix/2140/
def _bare_address_string(self):
host, _ = self.client_address[:2]
return str(host)
BaseHTTPRequestHandler.address_string = _bare_address_string
STATIC_ROUTES = (
['data', abspath(path_join(getcwd(), 'data'))],
['', output_path]
)
class StaticHTTPRequestHandler(SimpleHTTPRequestHandler):
def translate_path(self, path):
root = getcwd()
for pattern, rootdir in STATIC_ROUTES:
if path.startswith(pattern):
path = path[len(pattern):]
root = rootdir
break;
path = path.split('?',1)[0]
path = path.split('#',1)[0]
path = posixpath.normpath(unquote(path))
words = path.split('/')
words = filter(None, words)
path = root
for word in words:
drive, word = path_splitdrive(word)
head, word = path_split(word)
if word in (curdir, pardir):
continue
path = path_join(path, word)
return path
class RequestsSaveHandler(StaticHTTPRequestHandler):
# Forced regex to include 'data' to avoid overwriting any files with the API
local_save_regex = re_compile('/local/v1/save/([^/]+)/data/([^/]+)/(.*)')
def do_POST(self): # pylint: disable=C0103
def ok(msg='{"ok":true}'): # pylint: disable=C0103
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.send_header('Pragma', 'no-cache')
self.send_header('Cache-Control', 'no-cache')
self.send_header('Cache-Control', 'no-store')
self.send_header('Expires', '-1')
self.end_headers()
self.wfile.write(msg)
self.wfile.close()
def save_file(args):
game_slug = args[0]
username = args[1]
filepath = args[2]
info("Save file request: game_slug=%s, username=%s, filepath=%s" % (game_slug, username, filepath))
content_type = self.headers.getheader('content-type')
if not content_type or not 'application/x-www-form-urlencoded; charset=UTF-8' in content_type:
unsupported_error = 'Unsupported Content-Type: %s' % content_type
error(unsupported_error)
self.send_error(400, unsupported_error)
return
if '..' in filepath:
subdir_error = 'Filename must be a sub directory (cannot contain "..")'
self.send_error(400, subdir_error)
return
length = int(self.headers.getheader('content-length'))
post_data = urlparse.parse_qs(self.rfile.read(length).decode('utf-8'))
content = post_data['content'][0]
if not content:
content_error = 'Missing argument: content'
error(content_error)
self.send_error(400, content_error)
return
file_path = normpath(path_join(output_path, 'data', username, normpath(filepath)))
info("Writing to path %s: " % file_path)
mkdir(dirname(file_path))
with open(file_path, 'w') as f:
f.write(content)
ok()
path = self.path
info('POST request: %s' % path)
try:
match = self.local_save_regex.match(path)
if match:
info(match.groups())
save_file(match.groups())
else:
match_error = 'Not Found: %s' % self.path
error(match_error)
self.send_error(404, match_error)
except IOError:
io_error = 'File Not Found: %s' % self.path
error(io_error)
self.send_error(404, io_error)
except Exception:
log_msg = 'Exception when processing request: %s' % self.path
trace_string = format_exc()
error(log_msg)
error(trace_string)
self.send_error(500, 'Internal Server Error')
def do_GET(self):
# Respond with a blank page
info('GET request: %s' % self.path)
if self.path == '/':
self.path = '/benchmark.canvas.debug.html'
StaticHTTPRequestHandler.do_GET(self)
print "Starting capture server: %s" % SERVERNAME
info("Running in directory: %s" % output_path)
try:
server_handler = RequestsSaveHandler
server_class = HTTPServer
if server_options.static:
server_handler = StaticHTTPRequestHandler
server_class = TCPServer
server = server_class(('', server_options.port), server_handler)
def run_server_thread(server):
server.serve_forever()
t = Thread(target=run_server_thread, args=[server])
t.daemon = True
t.start()
return server
except socket_error:
return None
def main():
parser = ArgumentParser(description="Run the benchmark with given settings.")
parser.add_argument("-v", "--verbose", action="store_true", help="verbose output")
parser.add_argument("-s", "--silent", action="store_true", help="silent running")
parser.add_argument("--version", action='version', version=__version__)
browser_list = [browser for browser in list_browsers() if browser != 'explorer']
parser.add_argument("--config", action='store', default=DEFAULT_CAPTURE_NAME,
help="the configuration to run (by name)")
parser.add_argument("--target", action='store', choices=['online', 'offline', 'static'], default='offline',
help="the target to run")
parser.add_argument("--browser", action='store', choices=browser_list, default='chrome',
help="browser to run (defaults to chrome)")
parser.add_argument("--server", action='store_true',
help="only run the server (for saving data files to disk)")
parser.add_argument("--hardware-name", action='store', default='default',
help="the name of the hardware to save in the results")
parser.add_argument("--browser-launch", action='store_false',
help="run the browser after the configuration step")
parser.add_argument("--force-download", action='store_true',
help="download the capture date, even if the file(s) already exists")
parser.add_argument("--browser-path", action='store', default=None,
help="the path to the browser binary to run. This must be used in conjunction with the --browser option in " +
"the case where the user wants to override the default browser path")
parser.add_argument("--browser-profile", action='store', default=None,
help="the name of the profile to launch the browser with if supported. On Firefox this is name of the" +
" profile. On Chrome this the profile directory.")
parser.add_argument("--copy", action='store_true',
help="copy the release build of the benchmark to the '%s' directory." % STATIC_OUTPUT_PATH)
parser.add_argument("--release", action='store_true',
help="run the release build of the benchmark server in the '%s' directory." % STATIC_OUTPUT_PATH)
parser.add_argument("--build", action='store_true',
help="build the benchmark using the Turbulenz build system. Requires (env)")
parser.add_argument("--clean", action='store_true',
help="clean the benchmark project using the Turbulenz build system. Requires (env)")
parser.add_argument("--base-template-path", action='store', default=None,
help="the path to the file to be used as the base results template. Defaults to generating the base template.")
parser.add_argument("--local", action='store_true', default=False,
help="assume turbulenz_local is the server")
parser.add_argument("--browser-timeout", type=int, default=0,
help="automatically close the browser after timeout (seconds)")
args = parser.parse_args(argv[1:])
if args.silent:
basicConfig(level=CRITICAL)
elif args.verbose:
basicConfig(level=INFO)
else:
basicConfig(level=WARNING)
python_path, _ = path_split(executable)
env_path = normpath(path_join(python_path, '..', '..'))
benchmark_name = BENCHMARK_NAME_DEFAULT
benchmark_id = BENCHMARK_ID_DEFAULT
benchmark_type = BENCHMARK_TYPE_DEFAULT
benchmark_version = BENCHMARK_VERSION
if args.release:
info('Release mode activated: Forcing target to static')
args.target = 'static'
if args.target == 'static':
benchmark_id = 'polycraft_gl'
benchmark_name = 'POLYCRAFT.GL'
benchmark_type = 'online'
elif args.target == 'online':
benchmark_type = 'online'
if args.build or args.clean:
require_env = True
else:
require_env = False
if require_env:
virtual_env = environ.get('VIRTUAL_ENV', None)
if virtual_env:
active_env = True
else:
error("Command requires Turbulenz environment to be run")