-
Notifications
You must be signed in to change notification settings - Fork 144
/
hammer.py
executable file
·3237 lines (2704 loc) · 135 KB
/
hammer.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
#!/usr/bin/env python3
# Copyright (C) 2018-2024 Internet Systems Consortium, Inc. ("ISC")
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# pylint: disable=broad-exception-caught
"""Hammer - Kea development environment management tool."""
from __future__ import print_function
import os
import random
import re
import sys
import glob
import time
import json
import logging
import datetime
import platform
import binascii
import argparse
import textwrap
import functools
import multiprocessing
import grp
import pwd
import getpass
import urllib.request
from urllib.parse import urljoin
# [B404:blacklist] Consider possible security implications associated with subprocess module.
import subprocess # nosec B404
# Issue: [B405:blacklist] Using xml.etree.ElementTree to parse untrusted XML data is known to be vulnerable to XML
# attacks. Replace xml.etree.ElementTree with the equivalent defusedxml package, or make sure
# defusedxml.defuse_stdlib() is called.
import xml.etree.ElementTree as ET # nosec B405
# SYSTEMS = {
# 'os': {
# 'version': True if supported else False,
# ...
# },
# ...
# }
SYSTEMS = {
'fedora': {
'27': False,
'28': False,
'29': False,
'30': False,
'31': False,
'32': False,
'33': False,
'34': False,
'35': False,
'36': False,
'37': False,
'38': True,
'39': True,
'40': True,
},
'centos': {
'7': False,
'8': False,
'9': False,
},
'rhel': {
'8': True,
'9': True,
},
'rocky': {
'9': True,
},
'ubuntu': {
'16.04': False,
'18.04': True,
'18.10': False,
'19.04': False,
'19.10': False,
'20.04': True,
'20.10': False,
'21.04': False,
'22.04': True,
'24.04': True,
},
'debian': {
'8': False,
'9': False,
'10': True,
'11': True,
'12': True,
},
'freebsd': {
'11.2': False,
'11.4': False,
'12.0': False,
'12.1': False,
'13.0': True,
'14.0': True,
},
'alpine': {
'3.10': False,
'3.11': False,
'3.12': False,
'3.13': False,
'3.14': False,
'3.15': False,
'3.16': True,
'3.17': True,
'3.18': True,
'3.19': True,
'3.20': True,
},
'arch': {},
}
IMAGE_TEMPLATES = {
# fedora
'fedora-27-lxc': {'bare': 'lxc-fedora-27', 'kea': 'godfryd/kea-fedora-27'},
'fedora-27-virtualbox': {'bare': 'generic/fedora27', 'kea': 'godfryd/kea-fedora-27'},
'fedora-28-lxc': {'bare': 'godfryd/lxc-fedora-28', 'kea': 'godfryd/kea-fedora-28'},
'fedora-28-virtualbox': {'bare': 'generic/fedora28', 'kea': 'godfryd/kea-fedora-28'},
'fedora-29-lxc': {'bare': 'godfryd/lxc-fedora-29', 'kea': 'godfryd/kea-fedora-29'},
'fedora-29-virtualbox': {'bare': 'generic/fedora29', 'kea': 'godfryd/kea-fedora-29'},
'fedora-30-lxc': {'bare': 'godfryd/lxc-fedora-30', 'kea': 'godfryd/kea-fedora-30'},
'fedora-30-virtualbox': {'bare': 'generic/fedora30', 'kea': 'godfryd/kea-fedora-30'},
'fedora-31-lxc': {'bare': 'isc/lxc-fedora-31', 'kea': 'isc/kea-fedora-31'},
'fedora-31-virtualbox': {'bare': 'isc/vbox-fedora-31', 'kea': 'isc/kea-fedora-31'},
'fedora-32-lxc': {'bare': 'isc/lxc-fedora-32', 'kea': 'isc/kea-fedora-32'},
'fedora-33-lxc': {'bare': 'isc/lxc-fedora-33', 'kea': 'isc/kea-fedora-33'},
'fedora-34-lxc': {'bare': 'isc/lxc-fedora-34', 'kea': 'isc/kea-fedora-34'},
'fedora-35-lxc': {'bare': 'isc/lxc-fedora-35', 'kea': 'isc/kea-fedora-35'},
'fedora-36-lxc': {'bare': 'isc/lxc-fedora-36', 'kea': 'isc/kea-fedora-36'},
'fedora-37-lxc': {'bare': 'isc/lxc-fedora-37', 'kea': 'isc/kea-fedora-37'},
# centos
'centos-7-lxc': {'bare': 'isc/lxc-centos-7', 'kea': 'isc/kea-centos-7'},
'centos-7-virtualbox': {'bare': 'generic/centos7', 'kea': 'godfryd/kea-centos-7'},
'centos-8-lxc': {'bare': 'isc/lxc-centos-8', 'kea': 'isc/kea-centos-8'},
'centos-8-virtualbox': {'bare': 'generic/centos8', 'kea': 'isc/kea-centos-8'},
# rhel
'rhel-8-virtualbox': {'bare': 'generic/rhel8', 'kea': 'generic/rhel8'},
# ubuntu
'ubuntu-16.04-lxc': {'bare': 'godfryd/lxc-ubuntu-16.04', 'kea': 'godfryd/kea-ubuntu-16.04'},
'ubuntu-16.04-virtualbox': {'bare': 'ubuntu/xenial64', 'kea': 'godfryd/kea-ubuntu-16.04'},
'ubuntu-18.04-lxc': {'bare': 'isc/lxc-ubuntu-18.04', 'kea': 'isc/kea-ubuntu-18.04'},
'ubuntu-18.04-virtualbox': {'bare': 'ubuntu/bionic64', 'kea': 'godfryd/kea-ubuntu-18.04'},
'ubuntu-18.10-lxc': {'bare': 'godfryd/lxc-ubuntu-18.10', 'kea': 'godfryd/kea-ubuntu-18.10'},
'ubuntu-18.10-virtualbox': {'bare': 'ubuntu/cosmic64', 'kea': 'godfryd/kea-ubuntu-18.10'},
'ubuntu-19.04-lxc': {'bare': 'godfryd/lxc-ubuntu-19.04', 'kea': 'godfryd/kea-ubuntu-19.04'},
'ubuntu-19.04-virtualbox': {'bare': 'ubuntu/disco64', 'kea': 'godfryd/kea-ubuntu-19.04'},
'ubuntu-19.10-lxc': {'bare': 'isc/lxc-ubuntu-19.10', 'kea': 'isc/kea-ubuntu-19.10'},
'ubuntu-19.10-virtualbox': {'bare': 'generic/ubuntu1910', 'kea': 'isc/kea-ubuntu-19.10'},
'ubuntu-20.04-lxc': {'bare': 'isc/lxc-ubuntu-20.04', 'kea': 'isc/kea-ubuntu-20.04'},
'ubuntu-20.10-lxc': {'bare': 'isc/lxc-ubuntu-20.10', 'kea': 'isc/kea-ubuntu-20.10'},
'ubuntu-21.04-lxc': {'bare': 'isc/lxc-ubuntu-21.04', 'kea': 'isc/kea-ubuntu-21.04'},
'ubuntu-22.04-lxc': {'bare': 'isc/lxc-ubuntu-22.04', 'kea': 'isc/lxc-ubuntu-22.04'},
# debian
'debian-8-lxc': {'bare': 'godfryd/lxc-debian-8', 'kea': 'godfryd/kea-debian-8'},
'debian-8-virtualbox': {'bare': 'debian/jessie64', 'kea': 'godfryd/kea-debian-8'},
'debian-9-lxc': {'bare': 'isc/lxc-debian-9', 'kea': 'isc/kea-debian-9'},
'debian-9-virtualbox': {'bare': 'debian/stretch64', 'kea': 'godfryd/kea-debian-9'},
'debian-10-lxc': {'bare': 'isc/lxc-debian-10', 'kea': 'isc/kea-debian-10'},
'debian-10-virtualbox': {'bare': 'debian/buster64', 'kea': 'godfryd/kea-debian-10'},
'debian-11-lxc': {'bare': 'isc/lxc-debian-11', 'kea': 'isc/kea-debian-11'},
'debian-12-lxc': {'bare': 'isc/lxc-debian-12', 'kea': 'isc/kea-debian-12'},
# freebsd
'freebsd-11.2-virtualbox': {'bare': 'generic/freebsd11', 'kea': 'godfryd/kea-freebsd-11.2'},
'freebsd-12.0-virtualbox': {'bare': 'generic/freebsd12', 'kea': 'godfryd/kea-freebsd-12.0'},
'freebsd-13.0-virtualbox': {'bare': 'isc/vbox-freebsd-13.0', 'kea': 'isc/kea-freebsd-13.0'},
# alpine
'alpine-3.10-lxc': {'bare': 'godfryd/lxc-alpine-3.10', 'kea': 'godfryd/kea-alpine-3.10'},
'alpine-3.11-lxc': {'bare': 'isc/lxc-alpine-3.11', 'kea': 'isc/kea-alpine-3.11'},
'alpine-3.12-lxc': {'bare': 'isc/lxc-alpine-3.12', 'kea': 'isc/kea-alpine-3.12'},
'alpine-3.13-lxc': {'bare': 'isc/lxc-alpine-3.13', 'kea': 'isc/kea-alpine-3.13'},
'alpine-3.14-lxc': {'bare': 'isc/lxc-alpine-3.14', 'kea': 'isc/kea-alpine-3.14'},
'alpine-3.15-lxc': {'bare': 'isc/lxc-alpine-3.15', 'kea': 'isc/kea-alpine-3.15'},
'alpine-3.16-lxc': {'bare': 'isc/lxc-alpine-3.16', 'kea': 'isc/kea-alpine-3.16'},
'alpine-3.17-lxc': {'bare': 'isc/lxc-alpine-3.17', 'kea': 'isc/kea-alpine-3.17'},
}
# NOTES
# ** Alpine **
# 1. Extracting rootfs is failing:
# It requires commenting out checking if rootfs has been extracted as it checks for file /bin/true which is a link.
# Comment out in ~/.vagrant.d/gems/2.X.Y/gems/vagrant-lxc-1.4.3/scripts/lxc-template near 'Failed to extract rootfs'
LXC_VAGRANTFILE_TPL = """# -*- mode: ruby -*-
# vi: set ft=ruby :
ENV["LC_ALL"] = "C"
Vagrant.configure("2") do |config|
{hostname}
config.vm.box = "{image_tpl}"
{box_version}
config.vm.provider "lxc" do |lxc|
lxc.container_name = "{name}"
lxc.customize 'rootfs.path', "/var/lib/lxc/{name}/rootfs"
end
config.vm.synced_folder '.', '/vagrant', disabled: true
config.vm.synced_folder '{ccache_dir}', '/ccache'
end
"""
VBOX_VAGRANTFILE_TPL = """# -*- mode: ruby -*-
# vi: set ft=ruby :
ENV["LC_ALL"] = "C"
Vagrant.configure("2") do |config|
config.vm.hostname = "{name}"
config.vm.box = "{image_tpl}"
{box_version}
config.vm.provider "virtualbox" do |v|
v.name = "{name}"
v.memory = 8192
nproc = Etc.nprocessors
if nproc > 8
nproc -= 2
elsif nproc > 1
nproc -= 1
end
v.cpus = nproc
end
config.vm.synced_folder '.', '/vagrant', disabled: true
end
"""
RECOMMENDED_VAGRANT_VERSION = '2.2.16'
log = logging.getLogger()
def red(txt):
"""Return colorized (if the terminal supports it) or plain text."""
if sys.stdout.isatty():
return '\033[1;31m%s\033[0;0m' % txt
return txt
def green(txt):
"""Return colorized (if the terminal supports it) or plain text."""
if sys.stdout.isatty():
return '\033[0;32m%s\033[0;0m' % txt
return txt
def blue(txt):
"""Return colorized (if the terminal supports it) or plain text."""
if sys.stdout.isatty():
return '\033[0;34m%s\033[0;0m' % txt
return txt
def get_system_revision():
"""Return tuple containing system name and its revision."""
system = platform.system()
if system == 'Linux':
system, revision = None, None
if not os.path.exists('/etc/os-release'):
raise UnexpectedError('/etc/os-release does not exist. Cannot determine system or its revision.')
vals = {}
with open('/etc/os-release', encoding='utf-8') as f:
for line in f.readlines():
if '=' in line:
key, val = line.split('=', 1)
vals[key.strip()] = val.strip().replace('"', '')
for i in ['ID', 'ID_LIKE']:
if i in vals:
system_candidates = vals[i].strip('"').split()
for system_candidate in system_candidates:
if system_candidate in SYSTEMS:
system = system_candidate
break
else:
continue
break
if system is None:
raise UnexpectedError('cannot determine system')
for i in ['VERSION_ID', 'BUILD_ID']:
if i in vals:
revision = vals[i]
break
if revision is None:
raise UnexpectedError('cannot determine revision')
if system in ['alpine', 'rhel', 'rocky']:
revision = revision.rsplit('.', 1)[0]
elif system == 'FreeBSD':
system = system.lower()
revision = platform.release()
if '"' in revision:
revision = revision.replace('"', '')
if '"' in system:
system = system.replace('"', '')
system = system.lower()
return system, revision
class ExecutionError(Exception):
"""Exception thrown when execution encountered an error."""
class UnexpectedError(Exception):
"""Exception thrown when an unexpected error occurred that hammer does not know how to recover from."""
def execute(cmd, timeout=60, cwd=None, env=None, raise_error=True, dry_run=False, log_file_path=None,
quiet=False, check_times=False, capture=False, interactive=False, attempts=1,
sleep_time_after_attempt=None, super_quiet=False):
"""Execute a command in shell.
:param str cmd: a command to be executed
:param int timeout: timeout in number of seconds, after that time the command is terminated
but only if check_times is True
:param str cwd: current working directory for the command
:param dict env: dictionary with environment variables
:param bool raise_error: if False then in case of error exception is not raised,
default: True ie exception is raise
:param bool dry_run: if True then the command is not executed
:param str log_file_path: if provided then all traces from the command are stored in indicated file
:param bool quiet: if True then the command's traces are not printed to stdout
:param bool check_times: if True then timeout is taken into account
:param bool capture: if True then the command's traces are captured and returned by the function
:param bool interactive: if True then stdin and stdout are not redirected, traces handling is disabled,
used for e.g. SSH
:param int attempts: number of attempts to run the command if it fails
:param int sleep_time_after_attempt: number of seconds to sleep before taking next attempt
:param bool super_quiet: if True, set quiet to True and don't log command
"""
if super_quiet:
quiet = True
if cwd and "~/" in cwd:
# replace relative home directory
cwd = cwd.replace('~', os.environ['HOME'])
if not super_quiet:
log.info('>>>>> Executing %s in %s', cmd, cwd if cwd else os.getcwd())
if not check_times:
timeout = None
if dry_run:
return 0
if 'sudo' in cmd and env:
# if sudo is used and env is overridden then to preserve env add -E to sudo
cmd = cmd.replace('sudo', 'sudo -E')
if log_file_path:
with open(log_file_path, "wb", encoding='utf-8') as file:
log_file = file.read()
for attempt in range(attempts):
if interactive:
# Issue: [B602:subprocess_popen_with_shell_equals_true] subprocess call with shell=True identified,
# security issue.
with subprocess.Popen(cmd, cwd=cwd, env=env, shell=True) as pipe: # nosec: B602
pipe.communicate()
exitcode = pipe.returncode
else:
# Issue: [B602:subprocess_popen_with_shell_equals_true] subprocess call with shell=True identified,
# security issue.
with subprocess.Popen(cmd, cwd=cwd, env=env, shell=True, # nosec: B602
stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as pipe:
try:
if timeout is not None:
pipe.wait(timeout)
stdout, _ = pipe.communicate()
except subprocess.TimeoutExpired as e:
pipe.kill()
stdout2, _ = pipe.communicate()
stdout += stdout2
raise ExecutionError(f'Execution timeout: {e}, cmd: {cmd}') from e
exitcode = pipe.returncode
if capture:
output = stdout.decode('utf-8')
if not quiet:
print(stdout.decode('utf-8'))
if log_file_path is not None:
log_file.write(stdout)
if exitcode == 0:
break
if attempt < attempts - 1:
txt = 'command failed, retry, attempt %d/%d' % (attempt, attempts)
if log_file_path:
txt_to_file = '\n\n[HAMMER] %s\n\n\n' % txt
log_file.write(txt_to_file.encode('ascii'))
log.info(txt)
if sleep_time_after_attempt:
time.sleep(sleep_time_after_attempt)
if log_file_path:
log_file.close()
if exitcode != 0 and raise_error:
if capture and quiet:
log.error(output)
raise ExecutionError("The command return non-zero exitcode %s, cmd: '%s'" % (exitcode, cmd))
if capture:
return exitcode, output
return exitcode
def wait_for_process_to_start(process_name):
for _ in range(10):
exit_code = execute(f'sudo pidof {process_name}', raise_error=False)
if exit_code == 0:
# Process is there.
break
time.sleep(1)
def wait_for_process_to_exit(process_name):
for _ in range(100):
exit_code = execute(f'sudo pidof {process_name}', raise_error=False)
if exit_code != 0:
# Process exited or there was no process to begin with.
break
time.sleep(1)
def _append_to_file(file_name, line):
with open(file_name, encoding='utf-8', mode='a') as f:
f.write(line + '\n')
def _prepare_installed_packages_cache_for_debs():
pkg_cache = {}
_, out = execute("dpkg -l", timeout=15, capture=True, quiet=True)
for line in out.splitlines():
line = line.strip()
m = re.search(r'^([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+(.+)', line)
if not m:
continue
status, name, version, arch, descr = m.groups()
name = name.split(':')[0]
pkg_cache[name] = {
'status': status,
'version': version,
'arch': arch,
'descr': descr,
}
return pkg_cache
def _prepare_installed_packages_cache_for_rpms():
pkg_cache = {}
_, out = execute("rpm -qa --qf '%{NAME}\\n'", timeout=15, capture=True, quiet=True)
for line in out.splitlines():
name = line.strip()
pkg_cache[name] = {'status': 'ii'}
return pkg_cache
def _prepare_installed_packages_cache_for_alpine():
pkg_cache = {}
_, out = execute("apk list -I\\n'", timeout=15, capture=True, quiet=True)
for line in out.splitlines():
name = line.strip()
pkg_cache[name] = {'status': 'ii'}
return pkg_cache
def install_pkgs(pkgs, timeout=60, env=None, check_times=False, pkg_cache=None):
"""Install native packages in a system.
:param dict pkgs: specifies a list of packages to be installed
:param int timeout: timeout in number of seconds, after that time the command
is terminated but only if check_times is True
:param dict env: dictionary with environment variables (optional)
:param bool check_times: specifies if timeouts should be enabled (optional)
"""
system, revision = get_system_revision()
if not isinstance(pkgs, list):
pkgs = pkgs.split()
if pkg_cache is None:
pkg_cache = {}
# prepare cache if needed
if not pkg_cache and system in ['centos', 'rhel', 'fedora', 'debian', 'ubuntu',
'rocky']: # , 'alpine']: # TODO: complete caching support for alpine
if system in ['centos', 'rhel', 'fedora', 'rocky']:
pkg_cache.update(_prepare_installed_packages_cache_for_rpms())
elif system in ['debian', 'ubuntu']:
pkg_cache.update(_prepare_installed_packages_cache_for_debs())
elif system in ['alpine']:
pkg_cache.update(_prepare_installed_packages_cache_for_alpine())
# check if packages actually need to be installed
if pkg_cache:
pkgs_to_install = []
pkgs_installed = []
for pkg in pkgs:
if pkg not in pkg_cache or pkg_cache[pkg]['status'] != 'ii':
pkgs_to_install.append(pkg)
else:
pkgs_installed.append(pkg)
if pkgs_installed:
log.info('packages already installed: %s', ', '.join(pkgs_installed))
pkgs = pkgs_to_install
if not pkgs:
log.info('all packages already installed')
return
if system in ['centos', 'fedora', 'rhel', 'rocky']:
if system in ['centos', 'rhel'] and revision == '7':
execute('sudo yum install -y dnf')
cmd = 'sudo dnf -y install'
elif system in ['debian', 'ubuntu']:
# prepare the command for ubuntu/debian
if not env:
env = os.environ.copy()
env['DEBIAN_FRONTEND'] = 'noninteractive'
cmd = 'sudo apt install --no-install-recommends -y'
elif system == 'freebsd':
cmd = 'sudo pkg install -y'
elif system == 'alpine':
cmd = 'sudo apk add'
elif system == 'arch':
cmd = 'sudo pacman -S --needed --noconfirm --overwrite \'*\''
else:
raise NotImplementedError('no implementation for %s' % system)
pkgs = ' '.join(pkgs)
cmd += ' ' + pkgs
execute(cmd, timeout=timeout, env=env, check_times=check_times, attempts=3, sleep_time_after_attempt=10)
def get_image_template(key, variant):
if key not in IMAGE_TEMPLATES:
print('ERROR: Image {} is not available.'.format(key), file=sys.stderr)
sys.exit(1)
if variant not in IMAGE_TEMPLATES[key]:
print('ERROR: Variant {} is not available for image {}.'.format(variant, key), file=sys.stderr)
sys.exit(1)
return IMAGE_TEMPLATES[key][variant]
def _get_full_repo_url(repository_url, system, revision):
if not repository_url:
return None
repo_name = 'kea-%s-%s' % (system, revision)
repo_url = urljoin(repository_url, 'repository')
repo_url += '/%s/' % repo_name
return repo_url
class VagrantEnv():
"""Helper class that makes interacting with Vagrant easier.
It creates Vagrantfile according to specified system. It exposes basic Vagrant functions
like up, upload, destroy, ssh. It also provides more complex function for preparing system
for Kea build and building Kea.
"""
def __init__(self, provider, system, revision, features, image_template_variant,
dry_run, quiet=False, check_times=False, ccache_dir=None):
"""VagrantEnv initializer.
:param str provider: indicate backend type: virtualbox or lxc
:param str system: name of the system eg. ubuntu
:param str revision: revision of the system e.g. 18.04
:param list features: list of requested features
:param str image_template_variant: variant of images' templates: bare or kea
:param bool dry_run: if False then system commands are not really executed
:param bool quiet: if True then commands will not trace to stdout
:param bool check_times: if True then commands will be terminated after given timeout
"""
self.provider = provider
self.system = system
self.revision = revision
self.features = features
self.dry_run = dry_run
self.quiet = quiet
self.check_times = check_times
# set properly later
self.features_arg = None
self.nofeatures_arg = None
self.python = None
self.key = key = "%s-%s-%s" % (system, revision, provider)
self.image_tpl = get_image_template(key, image_template_variant)
self.repo_dir = os.getcwd()
sys_dir = "%s-%s" % (system, revision)
if provider == "virtualbox":
self.vagrant_dir = os.path.join(self.repo_dir, 'hammer', sys_dir, 'vbox')
elif provider == "lxc":
self.vagrant_dir = os.path.join(self.repo_dir, 'hammer', sys_dir, 'lxc')
if ccache_dir is None:
self.ccache_dir = '/'
self.ccache_enabled = False
else:
self.ccache_dir = ccache_dir
self.ccache_enabled = True
self.init_files()
def init_files(self):
if not os.path.exists(self.vagrant_dir):
os.makedirs(self.vagrant_dir)
vagrantfile_path = os.path.join(self.vagrant_dir, "Vagrantfile")
crc = binascii.crc32(self.vagrant_dir.encode())
self.name = "hmr-%s-%s-kea-srv-%08d" % (self.system, self.revision.replace('.', '-'), crc)
if '/' in self.image_tpl:
self.latest_version = self._get_latest_cloud_version()
box_version = 'config.vm.box_version = "%s"' % self.latest_version
else:
self.latest_version = None
box_version = ""
# alpine has a problem with setting hostname so skip it
if self.system == 'alpine':
hostname = ''
else:
hostname = 'config.vm.hostname = "%s"' % self.name
if self.provider == "virtualbox":
vagrantfile_tpl = VBOX_VAGRANTFILE_TPL
elif self.provider == "lxc":
vagrantfile_tpl = LXC_VAGRANTFILE_TPL
vagrantfile = vagrantfile_tpl.format(image_tpl=self.image_tpl,
name=self.name,
ccache_dir=self.ccache_dir,
box_version=box_version,
hostname=hostname)
with open(vagrantfile_path, "w", encoding='utf-8') as f:
f.write(vagrantfile)
log.info('Prepared vagrant system %s in %s', self.name, self.vagrant_dir)
def up(self):
"""Do Vagrant up."""
exitcode, out = execute("vagrant up --no-provision --provider %s" % self.provider,
cwd=self.vagrant_dir, timeout=15 * 60, dry_run=self.dry_run,
capture=True, raise_error=False)
if exitcode != 0:
if 'There is container on your system' in out and 'lxc-destroy' in out:
m = re.search(r'`lxc-destroy.*?`', out)
if m:
# destroy some old container
cmd = m.group(0)[1:-1]
cmd = 'sudo ' + cmd + ' -f'
execute(cmd, timeout=60)
# try again spinning up new
execute("vagrant up --no-provision --provider %s" % self.provider,
cwd=self.vagrant_dir, timeout=15 * 60, dry_run=self.dry_run)
return
raise ExecutionError('There is a problem with putting up a system')
def _get_cloud_meta(self, image_tpl=None):
if '/' not in self.image_tpl:
return {}
url = 'https://app.vagrantup.com/api/v1/box/' + (image_tpl if image_tpl else self.image_tpl)
try:
# Issue: [B310:blacklist] Audit url open for permitted schemes.
# Allowing use of file:/ or custom schemes is often unexpected.
# Reason for nosec: it is clearly a https link.
with urllib.request.urlopen(url) as response: # nosec B310
data = response.read()
except Exception as e:
log.exception('ignored exception: %s', e)
return {}
data = json.loads(data)
return data
def _get_local_meta(self):
meta_file = os.path.join(self.vagrant_dir, '.vagrant/machines/default', self.provider, 'box_meta')
if not os.path.exists(meta_file):
return {}
with open(meta_file, encoding='utf-8') as f:
data = f.read()
data = json.loads(data)
return data
def _get_latest_cloud_version(self, image_tpl=None):
cloud_meta = self._get_cloud_meta(image_tpl)
if not cloud_meta and 'versions' not in cloud_meta:
return 0
latest_version = 0
for ver in cloud_meta['versions']:
provider_found = False
for p in ver['providers']:
if p['name'] == self.provider:
provider_found = True
break
if provider_found:
try:
v = int(ver['number'])
except ValueError:
return ver['number']
if v > latest_version:
latest_version = v
return latest_version
def get_status(self):
"""Return system status.
Status can be: 'not created', 'running', 'stopped', etc.
"""
if not os.path.exists(self.vagrant_dir):
return "not created"
_, out = execute("vagrant status", cwd=self.vagrant_dir, timeout=15, capture=True, quiet=True)
m = re.search(r'default\s+(.+)\(', out)
if not m:
raise UnexpectedError('cannot get status in:\n%s' % out)
return m.group(1).strip()
def bring_up_latest_box(self):
if self.get_status() == 'running':
self.reload()
else:
self.up()
def reload(self):
"""Do Vagrant reload."""
execute("vagrant reload --no-provision --force",
cwd=self.vagrant_dir, timeout=15 * 60, dry_run=self.dry_run)
def package(self):
"""Package Vagrant system into Vagrant box."""
execute('vagrant halt', cwd=self.vagrant_dir, dry_run=self.dry_run, raise_error=False, attempts=3)
box_path = os.path.join(self.vagrant_dir, 'kea-%s-%s.box' % (self.system, self.revision))
if os.path.exists(box_path):
os.unlink(box_path)
if self.provider == 'virtualbox':
cmd = "vagrant package --output %s" % box_path
execute(cmd, cwd=self.vagrant_dir, timeout=4 * 60, dry_run=self.dry_run)
elif self.provider == 'lxc':
lxc_box_dir = os.path.join(self.vagrant_dir, 'lxc-box')
if os.path.exists(lxc_box_dir):
execute('sudo rm -rf %s' % lxc_box_dir)
os.mkdir(lxc_box_dir)
lxc_container_path = os.path.join('/var/lib/lxc', self.name)
# add vagrant universal key to accepted keys
execute('sudo sh -c \'echo "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8ia'
'llvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ'
'6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTB'
'ckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6k'
'ivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmB'
'YSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYC'
'zRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key"'
'> %s/rootfs/home/vagrant/.ssh/authorized_keys\'' % lxc_container_path)
# reset machine-id
execute('sudo rm -f %s/rootfs/var/lib/dbus/machine-id' % lxc_container_path)
# execute('sudo truncate -s 0 %s/rootfs/etc/machine-id' % lxc_container_path)
execute('sudo rm -f %s/rootfs/etc/machine-id' % lxc_container_path)
# pack rootfs
cmd = 'sudo sh -c "'
cmd += 'cd %s '
cmd += '&& tar --numeric-owner --anchored --exclude=./rootfs/dev/log -czf %s/rootfs.tar.gz ./rootfs/*'
cmd += '"'
execute(cmd % (lxc_container_path, lxc_box_dir))
# copy lxc config from runtime container
execute('sudo cp %s/config %s/lxc-config' % (lxc_container_path, lxc_box_dir))
# remove mac address from eth0 - it should be dynamically assigned
execute("sudo sed -i '/lxc.net.0.hwaddr/d' %s/lxc-config" % lxc_box_dir)
# correct files ownership
execute('sudo chown `id -un`:`id -gn` *', cwd=lxc_box_dir)
# and other metadata
with open(os.path.join(lxc_box_dir, 'metadata.json'), 'w', encoding='utf-8') as f:
now = datetime.datetime.now()
f.write('{\n')
f.write(' "provider": "lxc",\n')
f.write(' "version": "1.0.0",\n')
f.write(' "built-on": "%s"\n' % now.strftime('%c'))
f.write('}\n')
# pack vagrant box with metadata and config
execute('tar -czf %s ./*' % box_path, cwd=lxc_box_dir)
execute('sudo rm -rf %s' % lxc_box_dir)
return box_path
def upload_to_cloud(self, box_path):
image_tpl = get_image_template(self.key, 'kea')
if '/' not in image_tpl:
return
latest_version = self._get_latest_cloud_version(image_tpl)
new_version = latest_version + 1
cmd = "vagrant cloud publish --no-private -f -r %s %s %s %s"
cmd = cmd % (image_tpl, new_version, self.provider, box_path)
execute(cmd, cwd=self.vagrant_dir, timeout=60 * 60)
def upload(self, src):
"""Upload src to Vagrant system, home folder."""
attempt = 4
while attempt > 0:
exitcode = execute('vagrant upload %s' % src, cwd=self.vagrant_dir, dry_run=self.dry_run, raise_error=False)
if exitcode == 0:
break
attempt -= 1
if exitcode != 0:
msg = 'cannot upload %s' % src
log.error(msg)
raise ExecutionError(msg)
def run_build_and_test(self, tarball_path, jobs, pkg_version, pkg_isc_version, upload, repository_url):
"""Run build and unit tests inside Vagrant system."""
if self.dry_run:
return 0, 0
# prepare tarball if needed and upload it to vagrant system
if not tarball_path:
execute('mkdir -p ~/.hammer-tmp')
name_ver = 'kea-%s' % pkg_version
cmd = 'tar --transform "flags=r;s|^|%s/|" --exclude hammer ' % name_ver
cmd += ' --exclude "*~" --exclude .git --exclude .libs '
cmd += ' --exclude .deps --exclude \'*.o\' --exclude \'*.lo\' '
cmd += ' -zcf ~/.hammer-tmp/%s.tar.gz .' % name_ver
execute(cmd)
tarball_path = '~/.hammer-tmp/%s.tar.gz' % name_ver
self.upload(tarball_path)
execute('rm -rf ~/.hammer-tmp')
log_file_path = os.path.join(self.vagrant_dir, 'build.log')
log.info('Build log file stored to %s', log_file_path)
t0 = time.time()
# run build command
bld_cmd = "{python} hammer.py build -p local {features} {nofeatures} {check_times} {ccache}"
bld_cmd += " {tarball} {jobs} {pkg_version} {pkg_isc_version} {repository_url}"
bld_cmd = bld_cmd.format(python=self.python,
features=self.features_arg,
nofeatures=self.nofeatures_arg,
check_times='-i' if self.check_times else '',
ccache='--ccache-dir /ccache' if self.ccache_enabled else '',
tarball='-t ~/%s.tar.gz' % name_ver,
jobs='-j %d' % jobs,
pkg_version='--pkg-version %s' % pkg_version,
pkg_isc_version='--pkg-isc-version %s' % pkg_isc_version,
repository_url=('--repository-url %s' % repository_url) if repository_url else '')
timeout = _calculate_build_timeout(self.features) + 5 * 60
# executes hammer.py inside LXC container
self.execute(bld_cmd, timeout=timeout, log_file_path=log_file_path, quiet=self.quiet) # timeout: 40 minutes
ssh_cfg_path = self.dump_ssh_config()
if 'native-pkg' in self.features:
pkgs_dir = os.path.join(self.vagrant_dir, 'pkgs')
if os.path.exists(pkgs_dir):
execute('rm -rf %s' % pkgs_dir)
os.makedirs(pkgs_dir)
# copy results of _build_native_pkg
execute('scp -F %s -r default:~/kea-pkg/* .' % ssh_cfg_path, cwd=pkgs_dir)
if upload:
repo_url = _get_full_repo_url(repository_url, self.system, self.revision)
if repo_url is None:
raise ValueError('repo_url is None')
upload_cmd = 'curl -v --netrc -f'
if self.system in ['ubuntu', 'debian']:
upload_cmd += ' -X POST -H "Content-Type: multipart/form-data" --data-binary "@%s" '
file_ext = 'deb' # include both '.deb' and '.ddeb' files
elif self.system in ['fedora', 'centos', 'rhel', 'rocky']:
upload_cmd += ' --upload-file %s '
file_ext = '.rpm'
elif self.system == 'alpine':
upload_cmd += ' --upload-file %s '
file_ext = ''
_, arch = self.execute('arch', raise_error=False, capture=True)
arch = arch.strip()
repo_url = urljoin(repo_url, f'{pkg_isc_version}/v{self.revision}/{arch}/')
upload_cmd += ' ' + repo_url
for fn in os.listdir(pkgs_dir):
if file_ext and not fn.endswith(file_ext):
continue
fp = os.path.join(pkgs_dir, fn)
cmd = upload_cmd % fp
exit_code, txt = execute(cmd, raise_error=False, capture=True, attempts=3)
log.info('code: %s, txt: %s', exit_code, txt)
# debian doc packages is arch "all" in both x86 and aarch so we want to ignore error
# while second is uploaded
if exit_code != 0 and "Repository does not allow updating assets" in txt:
continue
t1 = time.time()
dt = int(t1 - t0)
log.info('Build log file stored to %s', log_file_path)
log.info("")
log.info(">>>>>> Build time %s:%s", dt // 60, dt % 60)
log.info("")
# run unit tests if requested
total = 0
passed = 0
try:
if 'unittest' in self.features:
cmd = 'scp -F %s -r default:/home/vagrant/unit-test-results.json .' % ssh_cfg_path
execute(cmd, cwd=self.vagrant_dir)
results_file = os.path.join(self.vagrant_dir, 'unit-test-results.json')
if os.path.exists(results_file):
with open(results_file, encoding='utf-8') as f:
txt = f.read()
results = json.loads(txt)
total = results['grand_total']
passed = results['grand_passed']
cmd = 'scp -F %s -r default:/home/vagrant/aggregated_tests.xml .' % ssh_cfg_path
execute(cmd, cwd=self.vagrant_dir)
except Exception as e:
log.exception('ignored issue with parsing unit test results: %s', e)
return total, passed
def destroy(self):
"""Remove the VM completely."""
if os.path.exists(self.vagrant_dir):
cmd = 'vagrant destroy --force'
execute(cmd, cwd=self.vagrant_dir, timeout=3 * 60, dry_run=self.dry_run) # timeout: 3 minutes
execute('rm -rf %s' % self.vagrant_dir)
def ssh(self):
"""Open interactive session to the VM."""
execute('vagrant ssh', cwd=self.vagrant_dir, timeout=None, dry_run=self.dry_run, interactive=True)
def dump_ssh_config(self):
"""Dump ssh config that allows getting into Vagrant system via SSH."""
ssh_cfg_path = os.path.join(self.vagrant_dir, 'ssh.cfg')
execute('vagrant ssh-config > %s' % ssh_cfg_path, cwd=self.vagrant_dir)
return ssh_cfg_path
def execute(self, cmd, timeout=None, raise_error=True, log_file_path=None, quiet=False, env=None, capture=False,
attempts=1, sleep_time_after_attempt=None):
"""Execute provided command inside Vagrant system."""
if not env:
env = os.environ.copy()
env['LANGUAGE'] = env['LANG'] = env['LC_ALL'] = 'C'
return execute('vagrant ssh -c "%s"' % cmd, env=env, cwd=self.vagrant_dir, timeout=timeout,
raise_error=raise_error, dry_run=self.dry_run, log_file_path=log_file_path,
quiet=quiet, check_times=self.check_times, capture=capture,
attempts=attempts, sleep_time_after_attempt=sleep_time_after_attempt)
def prepare_system(self):