Debian Codegraph @

script/benchmark/hello-bench/src/hello.py

raw
1 #!/usr/bin/env python
2
3 # Copyright The containerd Authors.
4
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8
9 # http://www.apache.org/licenses/LICENSE-2.0
10
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # The MIT License (MIT)
18 #
19 # Copyright (c) 2015 Tintri
20 #
21 # Permission is hereby granted, free of charge, to any person obtaining a copy
22 # of this software and associated documentation files (the "Software"), to deal
23 # in the Software without restriction, including without limitation the rights
24 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
25 # copies of the Software, and to permit persons to whom the Software is
26 # furnished to do so, subject to the following conditions:
27 #
28 # The above copyright notice and this permission notice shall be included in all
29 # copies or substantial portions of the Software.
30 #
31 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
32 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
33 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
34 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
35 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
36 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
37 # SOFTWARE.
38
39 import os, sys, subprocess, select, random, urllib2, time, json, tempfile, shutil, itertools
40
41 TMP_DIR = tempfile.mkdtemp()
42 LEGACY_MODE = "legacy"
43 ESTARGZ_NOOPT_MODE = "estargz-noopt"
44 ESTARGZ_MODE = "estargz"
45 ZSTDCHUNKED_MODE = "zstdchunked"
46 DEFAULT_OPTIMIZER = "ctr-remote image optimize --oci"
47 DEFAULT_PULLER = "nerdctl image pull"
48 DEFAULT_PUSHER = "nerdctl image push"
49 DEFAULT_TAGGER = "nerdctl image tag"
50 BENCHMARKOUT_MARK = "BENCHMARK_OUTPUT: "
51 CTR="ctr"
52 PODMAN="podman"
53
54 def exit(status):
55 # cleanup
56 shutil.rmtree(TMP_DIR)
57 sys.exit(status)
58
59 def tmp_path():
60 tmp_path.nxt += 1
61 return os.path.join(TMP_DIR, str(tmp_path.nxt))
62 tmp_path.nxt = 0
63
64 def tmp_copy(src):
65 dst = tmp_path()
66 if os.path.isdir(src):
67 shutil.copytree(src, dst)
68 else:
69 shutil.copyfile(src, dst)
70 return dst
71
72 def genargs_for_optimization(arg):
73 if arg == None or arg == "":
74 return ""
75 else:
76 return '-args \'["%s"]\'' % arg.replace('"', '\\\"').replace('\'', '\'"\'"\'')
77
78 def format_repo(mode, repository, name):
79 if mode == ESTARGZ_MODE:
80 return "%s/%s-esgz" % (repository, name)
81 elif mode == ESTARGZ_NOOPT_MODE:
82 return "%s/%s-esgz-noopt" % (repository, name)
83 elif mode == ZSTDCHUNKED_MODE:
84 return "%s/%s-zstdchunked" % (repository, name)
85 else:
86 return "%s/%s-org" % (repository, name)
87
88 class RunArgs:
89 def __init__(self, env={}, arg='', stdin='', stdin_sh='sh', waitline='', mount=[]):
90 self.env = env
91 self.arg = arg
92 self.stdin = stdin
93 self.stdin_sh = stdin_sh
94 self.waitline = waitline
95 self.mount = mount
96
97 class Bench:
98 def __init__(self, name, category='other'):
99 self.name = name
100 self.category = category
101
102 def __str__(self):
103 return json.dumps(self.__dict__)
104
105 class BenchRunner:
106 ECHO_HELLO = set(['alpine:3.15.3',
107 'nixos/nix:2.3.12',
108 'fedora:35',
109 'ubuntu:22.04'])
110
111 CMD_ARG_WAIT = {'rethinkdb:2.4.1': RunArgs(waitline='Server ready'),
112 'glassfish:4.1-jdk8': RunArgs(waitline='Running GlassFish'),
113 'drupal:9.3.9': RunArgs(waitline='apache2 -D FOREGROUND'),
114 'jenkins:2.60.3': RunArgs(waitline='Jenkins is fully up and running'),
115 'redis:6.2.6': RunArgs(waitline='Ready to accept connections'),
116 'tomcat:10.1.0-jdk17-openjdk-bullseye': RunArgs(waitline='Server startup'),
117 'postgres:14.2': RunArgs(waitline='database system is ready to accept connections',
118 env={'POSTGRES_PASSWORD': 'abc'}),
119 'mariadb:10.7.3': RunArgs(waitline='mysqld: ready for connections',
120 env={'MYSQL_ROOT_PASSWORD': 'abc'}),
121 'wordpress:5.9.2': RunArgs(waitline='apache2 -D FOREGROUND'),
122 'php:8.1.4-apache-bullseye': RunArgs(waitline='apache2 -D FOREGROUND'),
123 'rabbitmq:3.9.14': RunArgs(waitline='Server startup complete'),
124 'elasticsearch:8.1.1': RunArgs(waitline='"started"',
125 mount=[('elasticsearch/elasticsearch.yml', '/usr/share/elasticsearch/config/elasticsearch.yml')]),
126 }
127
128 CMD_STDIN = {'php:8.1.4': RunArgs(stdin='php -r "echo \\\"hello\\n\\\";"; exit\n'),
129 'gcc:11.2.0': RunArgs(stdin='cd /src; gcc main.c; ./a.out; exit\n',
130 mount=[('gcc', '/src')]),
131 'golang:1.18': RunArgs(stdin='cd /go/src; go run main.go; exit\n',
132 mount=[('go', '/go/src')]),
133 'jruby:9.3.4': RunArgs(stdin='jruby -e "puts \\\"hello\\\""; exit\n'),
134 'r-base:4.1.3': RunArgs(stdin='sprintf("hello")\nq()\n', stdin_sh='R --no-save'),
135 }
136
137 CMD_ARG = {'perl:5.34.1': RunArgs(arg='perl -e \'print("hello\\n")\''),
138 'python:3.10': RunArgs(arg='python -c \'print("hello")\''),
139 'pypy:3.9': RunArgs(arg='pypy3 -c \'print("hello")\''),
140 'node:17.8.0': RunArgs(arg='node -e \'console.log("hello")\''),
141 }
142
143 # complete listing
144 ALL = dict([(b.name, b) for b in
145 [Bench('alpine:3.15.3', 'distro'),
146 Bench('fedora:35', 'distro'),
147 Bench('ubuntu:22.04', 'distro'),
148 Bench('rethinkdb:2.4.1', 'database'),
149 Bench('postgres:14.2', 'database'),
150 Bench('redis:6.2.6', 'database'),
151 Bench('mariadb:10.7.3', 'database'),
152 Bench('python:3.10', 'language'),
153 Bench('golang:1.18', 'language'),
154 Bench('gcc:11.2.0', 'language'),
155 Bench('jruby:9.3.4', 'language'),
156 Bench('perl:5.34.1', 'language'),
157 Bench('php:8.1.4', 'language'),
158 Bench('pypy:3.9', 'language'),
159 Bench('r-base:4.1.3', 'language'),
160 Bench('drupal:9.3.9'),
161 Bench('jenkins:2.60.3'),
162 Bench('node:17.8.0'),
163 Bench('tomcat:10.1.0-jdk17-openjdk-bullseye', 'web-server'),
164 Bench('wordpress:5.9.2', 'web-server'),
165 Bench('php:8.1.4-apache-bullseye', 'web-server'),
166 Bench('rabbitmq:3.9.14'),
167 Bench('elasticsearch:8.1.1'),
168
169 # needs "--srcrepository=docker.io"
170 Bench('nixos/nix:2.3.12'),
171 ]])
172
173 def __init__(self, repository='docker.io/library', srcrepository='docker.io/library', mode=LEGACY_MODE, optimizer=DEFAULT_OPTIMIZER, puller=DEFAULT_PULLER, pusher=DEFAULT_PUSHER, runtime="containerd", profile=0):
174 if runtime == "containerd":
175 self.controller = ContainerdController(mode == ESTARGZ_NOOPT_MODE or mode == ESTARGZ_MODE or mode == ZSTDCHUNKED_MODE)
176 elif runtime == "podman":
177 self.controller = PodmanController()
178 else:
179 print 'Unknown runtime mode: '+runtime
180 exit(1)
181 self.repository = repository
182 self.srcrepository = srcrepository
183 self.mode = mode
184 self.optimizer = optimizer
185 self.puller = puller
186 self.pusher = pusher
187
188 profile = int(profile)
189 if profile > 0:
190 self.controller.start_profile(profile)
191
192 def cleanup(self, cid, bench):
193 self.controller.cleanup(cid, self.fully_qualify(bench.name))
194
195 def fully_qualify(self, repo):
196 return format_repo(self.mode, self.repository, repo)
197
198 def run_task(self, cid):
199 cmd = self.controller.task_start_cmd(cid)
200 startrun = time.time()
201 rc = os.system(cmd)
202 runtime = time.time() - startrun
203 assert(rc == 0)
204 return runtime
205
206 def run_echo_hello(self, image, cid):
207 cmd = self.controller.create_echo_hello_cmd(image, cid)
208 startcreate = time.time()
209 rc = os.system(cmd)
210 createtime = time.time() - startcreate
211 assert(rc == 0)
212 return createtime, self.run_task(cid)
213
214 def run_cmd_arg(self, image, cid, runargs):
215 assert(len(runargs.mount) == 0)
216 cmd = self.controller.create_cmd_arg_cmd(image, cid, runargs)
217 startcreate = time.time()
218 rc = os.system(cmd)
219 createtime = time.time() - startcreate
220 assert(rc == 0)
221 return createtime, self.run_task(cid)
222
223 def run_cmd_arg_wait(self, image, cid, runargs):
224 cmd = self.controller.create_cmd_arg_wait_cmd(image, cid, runargs)
225 startcreate = time.time()
226 rc = os.system(cmd)
227 createtime = time.time() - startcreate
228 assert(rc == 0)
229
230 cmd = self.controller.task_start_cmd(cid)
231 runtime = 0
232 startrun = time.time()
233
234 # line buffer output
235 p = subprocess.Popen(cmd, shell=True, bufsize=1,
236 stderr=subprocess.STDOUT,
237 stdout=subprocess.PIPE)
238 while True:
239 l = p.stdout.readline()
240 if l == '':
241 continue
242 print 'out: ' + l.strip()
243 # are we done?
244 if l.find(runargs.waitline) >= 0:
245 runtime = time.time() - startrun
246 # cleanup
247 print 'DONE'
248 cmd = self.controller.task_kill_cmd(cid)
249 rc = os.system(cmd)
250 assert(rc == 0)
251 break
252 p.wait()
253 return createtime, runtime
254
255 def run_cmd_stdin(self, image, cid, runargs):
256 cmd = self.controller.create_cmd_stdin_cmd(image, cid, runargs)
257 startcreate = time.time()
258 rc = os.system(cmd)
259 createtime = time.time() - startcreate
260 assert(rc == 0)
261
262 cmd = self.controller.task_start_cmd(cid)
263 startrun = time.time()
264 p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
265 print runargs.stdin
266 out, _ = p.communicate(runargs.stdin)
267 runtime = time.time() - startrun
268 print out
269 assert(p.returncode == 0)
270 return createtime, runtime
271
272 def run(self, bench, cid):
273 name = bench.name
274 image = self.fully_qualify(bench.name)
275
276 print "Pulling the image..."
277 pullcmd = self.controller.pull_cmd(image)
278 startpull = time.time()
279 rc = os.system(pullcmd)
280 assert(rc == 0)
281 pulltime = time.time() - startpull
282
283 runtime = 0
284 createtime = 0
285 if name in BenchRunner.ECHO_HELLO:
286 createtime, runtime = self.run_echo_hello(image=image, cid=cid)
287 elif name in BenchRunner.CMD_ARG:
288 createtime, runtime = self.run_cmd_arg(image=image, cid=cid, runargs=BenchRunner.CMD_ARG[name])
289 elif name in BenchRunner.CMD_ARG_WAIT:
290 createtime, runtime = self.run_cmd_arg_wait(image=image, cid=cid, runargs=BenchRunner.CMD_ARG_WAIT[name])
291 elif name in BenchRunner.CMD_STDIN:
292 createtime, runtime = self.run_cmd_stdin(image=image, cid=cid, runargs=BenchRunner.CMD_STDIN[name])
293 else:
294 print 'Unknown bench: '+name
295 exit(1)
296
297 return pulltime, createtime, runtime
298
299 def convert_echo_hello(self, src, dest, option):
300 period=10
301 cmd = ('%s %s -cni -period %s -entrypoint \'["/bin/sh", "-c"]\' -args \'["echo hello"]\' %s %s' %
302 (self.optimizer, option, period, src, dest))
303 print cmd
304 rc = os.system(cmd)
305 assert(rc == 0)
306
307 def convert_cmd_arg(self, src, dest, runargs, option):
308 period = 30
309 assert(len(runargs.mount) == 0)
310 entry = ""
311 if runargs.arg != "": # FIXME: this is naive...
312 entry = '-entrypoint \'["/bin/sh", "-c"]\''
313 cmd = ('%s %s -cni -period %s %s %s %s %s' %
314 (self.optimizer, option, period, entry, genargs_for_optimization(runargs.arg), src, dest))
315 print cmd
316 rc = os.system(cmd)
317 assert(rc == 0)
318
319 def convert_cmd_arg_wait(self, src, dest, runargs, option):
320 mounts = ''
321 for a,b in runargs.mount:
322 a = os.path.join(os.path.dirname(os.path.abspath(__file__)), a)
323 a = tmp_copy(a)
324 mounts += '--mount type=bind,src=%s,dst=%s,options=rbind ' % (a,b)
325 period = 90
326 env = ' '.join(['-env %s=%s' % (k,v) for k,v in runargs.env.iteritems()])
327 cmd = ('%s %s -cni -period %s %s %s %s %s %s' %
328 (self.optimizer, option, period, mounts, env, genargs_for_optimization(runargs.arg), src, dest))
329 print cmd
330 rc = os.system(cmd)
331 assert(rc == 0)
332
333 def convert_cmd_stdin(self, src, dest, runargs, option):
334 mounts = ''
335 for a,b in runargs.mount:
336 a = os.path.join(os.path.dirname(os.path.abspath(__file__)), a)
337 a = tmp_copy(a)
338 mounts += '--mount type=bind,src=%s,dst=%s,options=rbind ' % (a,b)
339 period = 60
340 cmd = ('%s %s -i -cni -period %s %s -entrypoint \'["/bin/sh", "-c"]\' %s %s %s' %
341 (self.optimizer, option, period, mounts, genargs_for_optimization(runargs.stdin_sh), src, dest))
342 print cmd
343 p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
344 print runargs.stdin
345 out,_ = p.communicate(runargs.stdin)
346 print out
347 p.wait()
348 assert(p.returncode == 0)
349
350 def push_img(self, dest):
351 cmd = '%s %s' % (self.pusher, dest)
352 print cmd
353 rc = os.system(cmd)
354 assert(rc == 0)
355
356 def pull_img(self, src):
357 cmd = '%s %s' % (self.puller, src)
358 print cmd
359 rc = os.system(cmd)
360 assert(rc == 0)
361
362 def copy_img(self, src, dest):
363 cmd = 'crane copy %s %s' % (src, dest)
364 print cmd
365 rc = os.system(cmd)
366 assert(rc == 0)
367
368 def convert_and_push_img(self, src, dest):
369 self.pull_img(src)
370 cmd = '%s --no-optimize %s %s' % (self.optimizer, src, dest)
371 print cmd
372 rc = os.system(cmd)
373 assert(rc == 0)
374 self.push_img(dest)
375
376 def optimize_img(self, name, src, dest, option):
377 self.pull_img(src)
378 if name in BenchRunner.ECHO_HELLO:
379 self.convert_echo_hello(src=src, dest=dest, option=option)
380 elif name in BenchRunner.CMD_ARG:
381 self.convert_cmd_arg(src=src, dest=dest, runargs=BenchRunner.CMD_ARG[name], option=option)
382 elif name in BenchRunner.CMD_ARG_WAIT:
383 self.convert_cmd_arg_wait(src=src, dest=dest, runargs=BenchRunner.CMD_ARG_WAIT[name], option=option)
384 elif name in BenchRunner.CMD_STDIN:
385 self.convert_cmd_stdin(src=src, dest=dest, runargs=BenchRunner.CMD_STDIN[name], option=option)
386 else:
387 print 'Unknown bench: '+name
388 exit(1)
389 self.push_img(dest)
390
391 def prepare(self, bench):
392 name = bench.name
393 src = '%s/%s' % (self.srcrepository, name)
394 self.copy_img(src=src, dest=format_repo(LEGACY_MODE, self.repository, name))
395 self.convert_and_push_img(src=src, dest=format_repo(ESTARGZ_NOOPT_MODE, self.repository, name))
396 self.optimize_img(name=name, src=src, dest=format_repo(ESTARGZ_MODE, self.repository, name), option="")
397 self.optimize_img(name=name, src=src, dest=format_repo(ZSTDCHUNKED_MODE, self.repository, name), option="--zstdchunked")
398
399 def operation(self, op, bench, cid):
400 if op == 'run':
401 return self.run(bench, cid)
402 elif op == 'prepare':
403 self.prepare(bench)
404 return 0, 0, 0
405 else:
406 print 'Unknown operation: '+op
407 exit(1)
408
409 class ContainerdController:
410 def __init__(self, is_lazypull=False):
411 self.is_lazypull = is_lazypull
412
413 def pull_cmd(self, image):
414 base_cmd = "%s i pull" % CTR
415 if self.is_lazypull:
416 base_cmd = "ctr-remote i rpull"
417 cmd = '%s %s' % (base_cmd, image)
418 print cmd
419 return cmd
420
421 def create_echo_hello_cmd(self, image, cid):
422 snapshotter_opt = ""
423 if self.is_lazypull:
424 snapshotter_opt = "--snapshotter=stargz"
425 cmd = '%s c create --net-host %s -- %s %s echo hello' % (CTR, snapshotter_opt, image, cid)
426 print cmd
427 return cmd
428
429 def create_cmd_arg_cmd(self, image, cid, runargs):
430 snapshotter_opt = ""
431 if self.is_lazypull:
432 snapshotter_opt = "--snapshotter=stargz"
433 cmd = '%s c create --net-host %s ' % (CTR, snapshotter_opt)
434 cmd += '-- %s %s ' % (image, cid)
435 cmd += runargs.arg
436 print cmd
437 return cmd
438
439 def create_cmd_arg_wait_cmd(self, image, cid, runargs):
440 snapshotter_opt = ""
441 if self.is_lazypull:
442 snapshotter_opt = "--snapshotter=stargz"
443 env = ' '.join(['--env %s=%s' % (k,v) for k,v in runargs.env.iteritems()])
444 cmd = '%s c create --net-host %s %s '% (CTR, snapshotter_opt, env)
445 for a,b in runargs.mount:
446 a = os.path.join(os.path.dirname(os.path.abspath(__file__)), a)
447 a = tmp_copy(a)
448 cmd += '--mount type=bind,src=%s,dst=%s,options=rbind ' % (a,b)
449 cmd += '-- %s %s %s' % (image, cid, runargs.arg)
450 print cmd
451 return cmd
452
453 def create_cmd_stdin_cmd(self, image, cid, runargs):
454 snapshotter_opt = ""
455 if self.is_lazypull:
456 snapshotter_opt = "--snapshotter=stargz"
457 cmd = '%s c create --net-host %s ' % (CTR, snapshotter_opt)
458 for a,b in runargs.mount:
459 a = os.path.join(os.path.dirname(os.path.abspath(__file__)), a)
460 a = tmp_copy(a)
461 cmd += '--mount type=bind,src=%s,dst=%s,options=rbind ' % (a,b)
462 cmd += '-- %s %s ' % (image, cid)
463 if runargs.stdin_sh:
464 cmd += runargs.stdin_sh # e.g., sh -c
465
466 print cmd
467 return cmd
468
469 def task_start_cmd(self, cid):
470 cmd = '%s t start %s' % (CTR, cid)
471 print cmd
472 return cmd
473
474 def task_kill_cmd(self, cid):
475 cmd = '%s t kill -s 9 %s' % (CTR, cid)
476 print cmd
477 return cmd
478
479 def cleanup(self, name, image):
480 print "Cleaning up environment..."
481 cmd = '%s t kill -s 9 %s' % (CTR, name)
482 print cmd
483 rc = os.system(cmd) # sometimes containers already exit. we ignore the failure.
484 cmd = '%s c rm %s' % (CTR, name)
485 print cmd
486 rc = os.system(cmd)
487 assert(rc == 0)
488 cmd = '%s image rm %s' % (CTR, image)
489 print cmd
490 rc = os.system(cmd)
491 assert(rc == 0)
492
493 def start_profile(self, seconds):
494 out = open('/tmp/hello-bench-output/profile-%d.out' % (random.randint(1,1000000)), 'w')
495 p = subprocess.Popen(
496 [CTR, 'pprof', '-d', '/run/containerd-stargz-grpc/debug.sock', 'profile', '-s', '%ds' % (seconds)],
497 stdout=out
498 )
499
500 class PodmanController:
501 def pull_cmd(self, image):
502 cmd = '%s pull docker://%s' % (PODMAN, image)
503 print cmd
504 return cmd
505
506 def create_echo_hello_cmd(self, image, cid):
507 cmd = '%s create --name %s docker://%s echo hello' % (PODMAN, cid, image)
508 print cmd
509 return cmd
510
511 def create_cmd_arg_cmd(self, image, cid, runargs):
512 cmd = '%s create --name %s docker://%s ' % (PODMAN, cid, image)
513 cmd += runargs.arg
514 print cmd
515 return cmd
516
517 def create_cmd_arg_wait_cmd(self, image, cid, runargs):
518 env = ' '.join(['--env %s=%s' % (k,v) for k,v in runargs.env.iteritems()])
519 cmd = '%s create %s --name %s '% (PODMAN, env, cid)
520 for a,b in runargs.mount:
521 a = os.path.join(os.path.dirname(os.path.abspath(__file__)), a)
522 a = tmp_copy(a)
523 cmd += '--mount type=bind,src=%s,dst=%s ' % (a,b)
524 cmd += ' docker://%s %s ' % (image, runargs.arg)
525 print cmd
526 return cmd
527
528 def create_cmd_stdin_cmd(self, image, cid, runargs):
529 cmd = '%s create -i ' % PODMAN
530 for a,b in runargs.mount:
531 a = os.path.join(os.path.dirname(os.path.abspath(__file__)), a)
532 a = tmp_copy(a)
533 cmd += '--mount type=bind,src=%s,dst=%s ' % (a,b)
534 cmd += '--name %s docker://%s ' % (cid, image)
535 if runargs.stdin_sh:
536 cmd += runargs.stdin_sh # e.g., sh -c
537
538 print cmd
539 return cmd
540
541 def task_start_cmd(self, cid):
542 cmd = '%s start -a %s' % (PODMAN, cid)
543 print cmd
544 return cmd
545
546 def task_kill_cmd(self, cid):
547 cmd = '%s kill -s 9 %s' % (PODMAN, cid)
548 print cmd
549 return cmd
550
551 def cleanup(self, name, image):
552 print "Cleaning up environment..."
553 cmd = '%s kill -s 9 %s' % (PODMAN, name)
554 print cmd
555 rc = os.system(cmd) # sometimes containers already exit. we ignore the failure.
556 cmd = '%s rm %s' % (PODMAN, name)
557 print cmd
558 rc = os.system(cmd)
559 assert(rc == 0)
560 cmd = '%s image rm %s' % (PODMAN, image)
561 print cmd
562 rc = os.system(cmd)
563 assert(rc == 0)
564 cmd = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../reboot_store.sh')
565 print cmd
566 rc = os.system(cmd)
567 assert(rc == 0)
568
569 def main():
570 if len(sys.argv) == 1:
571 print 'Usage: bench.py [OPTIONS] [BENCHMARKS]'
572 print 'OPTIONS:'
573 print '--repository=<repository>'
574 print '--srcrepository=<repository>'
575 print '--all'
576 print '--list'
577 print '--list-json'
578 print '--experiments'
579 print '--profile=<seconds>'
580 print '--runtime'
581 print '--op=(prepare|run)'
582 print '--mode=(%s|%s|%s)' % (LEGACY_MODE, ESTARGZ_NOOPT_MODE, ESTARGZ_MODE, ZSTDCHUNKED_MODE)
583 exit(1)
584
585 benches = []
586 kvargs = {}
587 # parse args
588 for arg in sys.argv[1:]:
589 if arg.startswith('--'):
590 parts = arg[2:].split('=')
591 if len(parts) == 2:
592 kvargs[parts[0]] = parts[1]
593 elif parts[0] == 'all':
594 benches.extend(BenchRunner.ALL.values())
595 elif parts[0] == 'list':
596 template = '%-16s\t%-20s'
597 print template % ('CATEGORY', 'NAME')
598 for b in sorted(BenchRunner.ALL.values(), key=lambda b:(b.category, b.name)):
599 print template % (b.category, b.name)
600 elif parts[0] == 'list-json':
601 print json.dumps([b.__dict__ for b in BenchRunner.ALL.values()])
602 else:
603 benches.append(BenchRunner.ALL[arg])
604
605 op = kvargs.pop('op', 'run')
606 trytimes = int(kvargs.pop('experiments', '1'))
607 if not op == "run":
608 trytimes = 1
609 experiments = range(trytimes)
610
611 profile = int(kvargs.get('profile', 0))
612 if profile > 0:
613 experiments = itertools.count(start=0)
614
615 # run benchmarks
616 runner = BenchRunner(**kvargs)
617 for bench in benches:
618 cid = '%s_bench_%d' % (bench.name.replace(':', '-').replace('/', '-'), random.randint(1,1000000))
619
620 elapsed_times = []
621 pull_times = []
622 create_times = []
623 run_times = []
624
625 for_start = time.time()
626 for i in experiments:
627 start = time.time()
628 pulltime, createtime, runtime = runner.operation(op, bench, cid)
629 elapsed = time.time() - start
630 if op == "run":
631 runner.cleanup(cid, bench)
632 elapsed_times.append(elapsed)
633 pull_times.append(pulltime)
634 create_times.append(createtime)
635 run_times.append(runtime)
636 print 'ITERATION %s:' % i
637 print 'elapsed %s' % elapsed
638 print 'pull %s' % pulltime
639 print 'create %s' % createtime
640 print 'run %s' % runtime
641
642 if profile > 0 and time.time() - for_start > profile:
643 break
644
645 row = {'mode':'%s' % runner.mode, 'repo':bench.name, 'bench':bench.name, 'elapsed':sum(elapsed_times) / len(elapsed_times), 'elapsed_pull':sum(pull_times) / len(pull_times), 'elapsed_create':sum(create_times) / len(create_times), 'elapsed_run':sum(run_times) / len(run_times)}
646 js = json.dumps(row)
647 print '%s%s,' % (BENCHMARKOUT_MARK, js)
648 sys.stdout.flush()
649
650 if __name__ == '__main__':
651 main()
652 exit(0)