-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcaasp
More file actions
executable file
·4293 lines (3392 loc) · 134 KB
/
Copy pathcaasp
File metadata and controls
executable file
·4293 lines (3392 loc) · 134 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/env python3
import argparse
import glob as gb
import json
import logging
import os
import os.path as op
import re
import readline
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import traceback
from cmd import Cmd
from contextlib import contextmanager
from datetime import datetime, timedelta
from tempfile import NamedTemporaryFile
from threading import Timer
if sys.version_info <= (3, 0):
sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n")
sys.exit(1)
CURR_DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
# default prefix for the VMs
VMS_PREFIX = 'caasp'
# default name for the admin node and nodes
VM_ADMIN_SUFFIX = '-admin'
VM_NODES_REGEX_SUFFIX = '-node.*'
# caaspctl executable in the VMs, and some important commands
CAASPCTL = '/tmp/caasp/caaspctl'
CAASPCTL_GEN_KUBECONFIG = 'kubeconfig'
CAASPCTL_GET_PILLAR = 'pillar get {key} {where}'
CAASPCTL_SET_PILLAR = 'pillar set {key} {value}'
CAASPCTL_SALT_SYNC = 'salt sync'
CAASPCTL_MINIONS_ACCEPT = 'minions accept {num}'
CAASPCTL_ENABLE_RW = 'rw 1'
CONTAINER_START_TIMEOUT = 300
# timeout for "virsh snapshot-create"
VIRSH_SNAPSHOT_TIMEOUT = 9000
# where the pillar.lst file is copied to
PILLARS_FILE_REM = '/tmp/caasp/pillar.lst'
# default terraform definition and state file
DEFAULT_TF = 'terraform.tf'
DEFAULT_TF_STATE = 'terraform.tfstate'
DEFAULT_TF_OUTPUTS = 'terraform-outputs.tf'
# default terraform profiles directory
DEFAULT_TFVARS_DIR = 'terraform'
DEFAULT_TF_DEVEL_PROFILE = os.path.join(DEFAULT_TFVARS_DIR, 'profile-devel.tf')
# default Terraform parallelist
DEFAULT_TF_PAR = 1
# directory where the kubeconfig can be fodun in the remote machines
DEFAULT_KUBECONFIG_REM = '/root/.kube/config'
# directory where Salt/manifests is copied to (in the Admin Node)
DEFAULT_SALT_REM = '/usr/share/salt/kubernetes/'
DEFAULT_MANIFESTS_REM = '/usr/share/caasp-container-manifests/'
# the path to admin-node-setup.sh
ADMIN_NODE_SETUP = '/usr/share/caasp-container-manifests/admin-node-setup.sh'
# default dirs for local and remote RPMs (for installations)
DEFAULT_RPMS_SRC = 'rpms'
DEFAULT_RPMS_DST = '/tmp/caasp-rpms'
# rsync arguments
# Notes: follows symlinks
DEFAULT_RSYNC_ARGS = "-avz -L --delete --delete-after --force"
# directory for images configuration
DEFAULT_IMGAGES_CFG_DIR = 'configs/images'
# default environments directory
DEFAULT_ENV_DIR = 'configs/environments'
# the default environment
DEFAULT_ENV = 'localhost'
# logging format
# https://docs.python.org/2/library/logging.html#logrecord-attributes
FORMAT = '# %(asctime)s [%(levelname)s] %(message)s'
CAASP_USER_DIR = os.path.expanduser('~/.caasp')
CAASP_LAST_RUN_ARGS = os.path.join(CAASP_USER_DIR, 'caasp.yaml')
# default ssh arguments
SSH_ARGS = """\
-oStrictHostKeyChecking=no \
-oUserKnownHostsFile=/dev/null \
-oConnectTimeout=10 \
-oLogLevel=ERROR \
"""
EXCLUDE_ARGS = """ \
--exclude='*.tfstate*' \
--exclude='.git*' \
--exclude='.tox' \
--exclude='README.md' \
--exclude='*.sublime*' \
--exclude='__pycache__' \
--exclude='.idea' \
--exclude='Jenkins*' \
--exclude='.terraform' \
--exclude='test_*.py' \
--exclude='__init__.py' \
--exclude='.pyc' \
"""
EXCLUDE_BINS_ARGS = """ \
--exclude='*.tgz' \
--exclude='*.qcow2' \
--exclude='*.rpm' \
--exclude='docker-image*.tar.gz' \
"""
# default ssh password
DEFAULT_SSH_PASS = "linux"
# the version for this
VERSION = "0.1"
# default copies to perform
DEFAULT_COPIES = {
'admin': [
('resources/common/', '/tmp/caasp/'),
('resources/admin/', '/tmp/caasp/admin/')
],
'nodes': [
('resources/common/', '/tmp/caasp/'),
('resources/nodes/', '/tmp/caasp/nodes/')
],
}
# terraform variable used for pointing to libvirt
TERRAFORM_LIBVIRT_URI_VAR = 'libvirt_uri'
# extra variables we want to save in the Terraform state file
TFSTATE_OUTPUTS = [
TERRAFORM_LIBVIRT_URI_VAR,
'img',
'img_pool',
'prefix',
'nodes_count'
]
# variables in te terraform file for setting salt and manifests copies
TFVAR_SALT_DIR = 'salt_dir'
TFVAR_MANIFESTS_DIR = 'manifests_dir'
# default orchestration to run
DEFAULT_ORCHESTRATION = 'kubernetes'
# delay _after_ creating snapshot
DEFAULT_SNAP_DELAY = 30
# delay after creating the VMs
DEFAULT_TERRAFORM_APPLY_DELAY = 60
DATE_FMT = '%Y-%m-%d %H:%M:%S'
# commands to run in nodes before runing an orchestration
ORCH_PREPARE_NODES_SHELL_CMDS = [
# it seems the original hostname is saved in /etc/hostname
# so we must fix the hostname: it could be broken by libvirt's dnsmasq
'cat /etc/hostname | xargs hostname',
# synchronize the times in all the VMs by setting the
# VMs' times here.
'systemctl stop ntpd',
'timedatectl set-ntp false',
# it seems this is enough, but maybe we must
# use virsh_sync_time)
'/sbin/hwclock --hctosys',
#"timedatectl set-time '{date}'",
"date"
]
# caaspctl commands to run a orchestration
# there will be some replacements like {orch} and {orch_args}
ORCH_PREPARE_CAASPCTL_CMDS = [
'pillar flush',
'pillar load ' + PILLARS_FILE_REM,
'pillar guess_dynamic'
]
K8S_DASHBOARD_HELM_CHART = 'stable/kubernetes-dashboard'
K8S_DASHBOARD_PORT = 8443
K8S_DASHBOARD_NAMESPACE = 'kube-system'
K8S_DASHBOARD_USER = 'cluster-admin'
# add the 'ca' and 'admin' Salt minions to the number of keys to wait for
SALT_KEYS_EXTRA_WAIT = 2
# directory for docker registry certificates
REGISTRY_CERTS_DIR = os.path.join(CURR_DIR, 'registry')
# configuration used for generating the certificates
REGISTRY_CERTS_CFG = '''
[req]
prompt = no
req_extensions = v3_req
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
countryName = US
stateOrProvinceName = Somewhere
localityName = Somewhere
organizationName = SUSE
commonName = {hostname}
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = {hostname}.local
DNS.2 = {hostname}
DNS.3 = {registry_hostname}
IP.1 = {ip}
'''
REGISTRY_PORT = 5000
REGISTRY_DOCKER_IMAGE = 'registry'
REGISTRY_DOCKER_IMAGE_TAG = 2
SCRIPT_REGISTRY_CERTS = '''
openssl genrsa -out "{ca_key}" 4096
openssl req -new -x509 -days 1826 -key "{ca_key}" -out "{ca_crt}" -config "{cnf}"
openssl genrsa -out "{reg_key}" 2048
openssl req -new -key "{reg_key}" -out "{reg_csr}" -subj "/CN={hostname}" -config "{cnf}"
openssl x509 -req -CA "{ca_crt}" -CAkey "{ca_key}" -CAcreateserial -in "{reg_csr}" -out "{reg_crt}" -days 365 -extensions v3_req -extfile "{cnf}"
'''
REGISTRY_DOCKER_CMD = '''
docker run -d -p {registry_port}:{registry_port} \
--restart=always --name registry \
-v {registry_certs_dir}:/certs \
-e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/{basename_reg_crt} \
-e REGISTRY_HTTP_TLS_KEY=/certs/{basename_reg_key} \
-e REGISTRY_STORAGE_DELETE_ENABLED=true \
{container_registry}:{container_registry_tag}
'''
# RC files that are automatically loaded on startup
# can be used for doing some actions or setting default values (ie, 'devel enable')
CAASP_RC_FILES = [
'.caasp.rc',
'.caasprc',
'caasp.rc',
'caasprc',
'.caasp.rc.local',
'.caasprc.local',
'caasp.rc.local',
'caasprc.local'
]
CAASP_RC_FILES_ABS = [
'~/.caasp.rc',
'~/.caasprc',
'~/caasp.rc',
'~/caasprc'
]
ENV_STAGE_RC_FILES = [
'{stage}.rc',
'{stage}.rc.local',
]
ENV_TFVARS_FILES = [
'preset-local.tfvars',
'preset.tfvars',
'preset-local.tfvars.local',
'preset.tfvars.local'
]
# directories where the Salt code and the manifests could be (relative to CURR_DIR)
MAYBE_DIRS_SALT = [
'./salt',
'../salt',
'./k8s-salt',
'../k8s-salt'
]
MAYBE_DIRS_MANIFESTS = [
'./caasp-container-manifests',
'../caasp-container-manifests',
'./manifests',
'../manifests'
]
# colors definitions
COLORS = {
'HEADER': '\033[95m',
'BLUE': '\033[94m',
'GREEN': '\033[92m',
'RED': '\033[91m',
'ENDC': '\033[0m',
'BOLD': '\033[1m',
'UNDERLINE': '\033[4m'
}
PROMPT_COLORS = ['UNDERLINE', 'BLUE']
####################################################################
# Command line arguments
####################################################################
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='A utility for creating/managing a CaaSP cluster with Terraform and libvirt',
epilog='''
Make sure you have Terraform installed and a valid libvirt instance running.
Then you can start by creating a cluster with 'cluster create'.
''')
parser.add_argument('args',
nargs=argparse.REMAINDER,
help=';-separated list of commands to run (get more info with "help")')
env_group = parser.add_argument_group(
title='Environment and images',
description='Environments for running the cluster')
env_group.add_argument('--env',
dest='env',
metavar='ENVIRONMENT',
default=DEFAULT_ENV,
help='environment to use')
env_group.add_argument('--env-dir',
dest='env_dir',
metavar='DIR',
default=DEFAULT_ENV_DIR,
help='environments directory')
env_group.add_argument('--last-env',
dest='last_env',
action='store_true',
default=False,
help='use the same environment used the last time')
img_group = parser.add_argument_group(
title='Images',
description='Images to use in the cluster')
img_group.add_argument('--image',
dest='image',
metavar='IMAGE',
default='',
help='image channel to use')
vms_group = parser.add_argument_group(
title='Virtual machines',
description='Arguments related to the virtual machines')
vms_group.add_argument('--vm-prefix',
dest='vm_prefix',
metavar='PREFIX',
default=VMS_PREFIX,
help='some distinctive prefix for the libvirt machines')
vms_group.add_argument('--vm-admin',
dest='vm_admin',
metavar='VM',
help='default name for the admin node (default: <PREFIX> + "-admin")')
vms_group.add_argument('--vm-nodes-regex',
dest='vm_nodes_regex',
metavar='REGEX',
help='regex for the recognizing nodes in the libvirt machines (default: <PREFIX> + "-node.*")')
vms_group.add_argument('--vm-caaspctl',
dest='vm_caaspctl',
metavar='EXE',
default=CAASPCTL,
help='caaspctl path in nodes')
tf_group = parser.add_argument_group(
title='Terraform',
description='Terraform low-level configuration')
tf_group.add_argument('--tf',
dest='tf',
metavar='TFFILE',
help='terraform tf file (default: <ENV>/terraform.tf)')
tf_group.add_argument('--tf-state',
dest='tf_state',
metavar='FILE',
help='Terraform state file (by default, will create a one in the environment directory)')
tf_group.add_argument('--tfvars-dir',
dest='tfvars_dir',
metavar='FILE',
default=DEFAULT_TFVARS_DIR,
help='default directory for looking for Terraform variables (.tfvars) files')
tf_group.add_argument('--tfvar',
dest='tfvar',
action='append',
metavar='VAR=VALUE',
default=[],
help='add a terraform variable.')
tf_group.add_argument('--tfvars',
dest='tfvars',
action='append',
metavar='FILE',
default=[],
help='add a terraform variables file.')
tf_group.add_argument('--tf-par',
dest='tf_par',
default=DEFAULT_TF_PAR,
metavar='NUM',
help='Terraform parallelism')
prio_group = parser.add_argument_group(
title='Privileges/passwords',
description='Password and privileges needed for running things')
prio_group.add_argument('--no-sudo-virsh',
dest='sudo_virsh',
default=True,
action='store_false',
help='do NOT use "sudo" for virsh')
prio_group.add_argument('--sudo-password',
dest='sudo_password',
metavar='PASS',
default='',
help='password for sudo commands')
prio_group.add_argument('--ssh-password',
dest='ssh_password',
metavar='PASS',
default=DEFAULT_SSH_PASS,
help='password for ssh')
prio_group.add_argument('--sshpass',
dest='sshpass',
metavar='EXE',
default='sshpass',
help='sshpass executable when using --ssh-password')
prio_group.add_argument('--ssh-multiplex',
dest='ssh_multiplex',
default=False,
action='store_true',
help='multiplex sessions on a ssh connection')
devel_group = parser.add_argument_group(
title='Development options',
description='Some options for developers')
devel_group.add_argument('--copy-salt-code',
dest='copy_salt_code',
default=False,
action='store_true',
help='copy the Salt code to the Admin Node')
devel_group.add_argument('--salt-src-dir',
dest='salt_dir',
metavar='DIR',
default='',
help='default Salt sources directory')
devel_group.add_argument('--salt-src-branch',
dest='salt_branch',
metavar='NAME',
default=None,
help='Salt code branch to copy to the Admin Node (NOTE: the local worktree will be used when specifing the current branch)')
devel_group.add_argument('--copy-manifests',
dest='copy_manifests',
default=False,
action='store_true',
help='copy the manifests to the Admin Node')
devel_group.add_argument('--manifests-dir',
dest='manifests_dir',
metavar='DIR',
default='',
help='default manifests directory')
devel_group.add_argument('--manifest-branch',
dest='manifests_branch',
metavar='NAME',
default=None,
help='manifests branch to copy to the Admin Node (NOTE: the local worktree will be used when specifing the current branch)')
devel_group.add_argument('--tf-copies',
dest='tf_copies',
default=False,
action='store_true',
help='perform an initial copy of the Salt/manifests with Terraform (copies will be performed anyway before orchestrations when "devel" mode is enabled)')
devel_group.add_argument('--tf-devel-profile',
dest='tf_devel_profile',
metavar='TF_FILE',
default=DEFAULT_TF_DEVEL_PROFILE,
help='Terraform development profile (.tf) file')
reg_group = parser.add_argument_group(
title='Registry',
description='Local Docker registry')
reg_group.add_argument('--reg-cert-dir',
dest='reg_certs_dir',
metavar='DIR',
default=REGISTRY_CERTS_DIR,
help='directory for the regstry certificates')
reg_group.add_argument('--reg-hostname',
dest='reg_hostname',
metavar='HOSTNAME',
default='registry.com',
help='exported registry name')
commands_group = parser.add_argument_group(
title='Commands processing',
description='How commands are processed from command line or from the loop')
commands_group.add_argument('--loop',
dest='loop',
default=False,
action='store_true',
help='the loop is only started when no commands are provided in command line. With this flag, the loop is started even when commands are provided as arguments')
commands_group.add_argument('--commands-pre',
dest='commands_pre',
default=False,
action='store_true',
help='process commands from arguments BEFORE processing scripts')
commands_group.add_argument('--exit-on-error',
dest='exit_on_err',
default=False,
action='store_true',
help='exit on any errors instead of just printing the error message')
commands_group.add_argument('--skip-rc-files',
dest='skip_rc_files',
default=False,
action='store_true',
help='do not load automatically the RC files')
script_group = parser.add_argument_group(
title='Loading commands from scripts')
script_group.add_argument('--script',
dest='script',
action='append',
metavar='FILE',
default=[],
help='read commands from a script(s). can be provided multiple times for loading scripts in order.')
script_group.add_argument('--script-only',
dest='script_only',
default=True,
action='store_true',
help='quit after running the script')
script_group.add_argument('--script-begin',
dest='script_begin',
metavar='STAGE',
default='',
help='process the script after stage <STAGE>')
script_group.add_argument('--script-stage',
action='append',
dest='script_stage',
metavar='STAGE',
default=[],
help='process only the stage <STAGE> in the script (can be provided multiple times)')
files_group = parser.add_argument_group(
title='Copies and Files',
description='Local and remote paths necessary for performing copies from/to VMs')
files_group.add_argument('--kubeconfig',
dest='kubeconfig',
metavar='FILE',
default=os.environ.get('KUBECONFIG', 'kubeconfig'),
help='local kubeconfig (downloaded from the Admin Node after orchestrating)')
files_group.add_argument('--kubeconfig-remote',
dest='DEFAULT_KUBECONFIG_REM',
metavar='FILE',
default=DEFAULT_KUBECONFIG_REM,
help='the kubeconfig in the nodes of the cluster')
files_group.add_argument('--rpms',
dest='default_rpms_src',
metavar='DIR',
default=DEFAULT_RPMS_SRC,
help='default local directory for RPMs')
files_group.add_argument('--rpms-remote',
dest='default_rpms_dst',
metavar='DIR',
default=DEFAULT_RPMS_DST,
help='default remote directory for RPMs')
verbose_group = parser.add_argument_group(
title='Logging/verbosity')
verbose_group.add_argument('--debug',
dest='debug',
default=False,
action='store_true',
help='use debug logging')
args = parser.parse_args()
loglevel = (logging.DEBUG if args.debug else logging.INFO)
log = logging.getLogger(__name__)
logging.basicConfig(stream=sys.stderr,
format=FORMAT,
level=loglevel)
try:
import coloredlogs
# By default the install() function installs a handler on the root logger,
# this means that log messages from your code and log messages from the
# libraries that you use will all show up on the terminal.
coloredlogs.install(fmt=FORMAT, level=loglevel)
except ImportError:
log.debug('"coloredlogs" not available')
readline.set_completer_delims(' \t\n')
if args.ssh_multiplex:
SSH_ARGS += " -oControlmaster=auto -oControlpath='/tmp/ssh-%r@%h:%p'"
####################################################################
# Aux
####################################################################
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
def replace_pattern(pat, replacer, line):
for t in re.finditer(pat, line):
txt = str(t.group())
out = replacer(txt)
line = line.replace(txt, out)
return line
def reset_loglevel(level):
'''
Usage: reset_loglevel(logging.DEBUG)
'''
log.setLevel(level)
for handler in log.handlers:
handler.setLevel(level)
def get_local_ip_for(remote_ip='10.255.255.255'):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect((remote_ip, 1))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
return IP
def load_caasp_last_run():
if not os.path.exists(CAASP_USER_DIR):
log.debug('Creating %s', CAASP_USER_DIR)
os.makedirs(CAASP_USER_DIR)
if os.path.exists(CAASP_LAST_RUN_ARGS):
import yaml
log.debug('Loading %s', CAASP_LAST_RUN_ARGS)
with open(CAASP_LAST_RUN_ARGS, 'r') as stream:
try:
return yaml.load(stream)
except yaml.YAMLError as exc:
log.error('could not load saved args: %s',exc)
def save_caasp_last_run(saved_args):
if not os.path.exists(CAASP_USER_DIR):
log.debug('Creating %s', CAASP_USER_DIR)
os.makedirs(CAASP_USER_DIR)
import yaml
with open(CAASP_LAST_RUN_ARGS, 'w') as outfile:
log.debug('Saving %s', CAASP_LAST_RUN_ARGS)
yaml.dump(saved_args, outfile, default_flow_style=False)
def value_to_native(val):
if isinstance(val, str):
try:
return int(val)
except ValueError:
pass
if val.lower() in ["true", "yes", "on"]:
return True
elif val.lower() in ["false", "no", "off"]:
return False
val = os.path.expandvars(val)
# in case it is a quoted string, remove them
if val[0] in ['\'', '"']:
return val[1:-1]
return val
def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def get_regular_container(name):
for line in run('docker ps'):
fields = re.split('\s{2,}', line.strip())
cid = fields[0]
cname = fields[-1]
if name in cname:
return cid
def notify(body='', summary='CaaSP', icon=None):
'''
(Try to) Send a desktop notification.
Checkout the number of icons in /usr/share/icons/gnome/32x32/actions
ie, 'up', 'down', 'start', 'finish'
'''
cmd = ['notify-send']
cmd += ['--app-name=caasp']
if icon:
cmd += ['--icon=' + icon]
cmd += [summary, body]
try:
subprocess.call(cmd)
except Exception as e:
log.debug('could not send notification: %s', e)
def expandvars(path):
return re.sub(r'(?<!\\)\$[A-Za-z_][A-Za-z0-9_]*', '', os.path.expandvars(path))
def get_assign_from_str(line):
res = {}
if len(line) == 0:
return res
try:
assert(isinstance(line, str))
for assign in line.split(','):
var = assign.split('=')
variable = var[0].strip()
value = var[1].strip()
value = value_to_native(value)
res[variable] = value
except IndexError as e:
log.debug('could not parse assignments in "%s": %s', line, e)
return res
def create_link(orig, dest):
''' (re)create a symbolik link orig->dest '''
if os.path.exists(orig):
if os.path.islink(orig):
log.debug('os: removing previous symbolic link %s', orig)
os.remove(orig)
log.debug('os: creating symbolic link from %s-> %s', orig, dest)
try:
os.symlink(dest, orig)
except FileExistsError:
log.debug('os: symbolic link already exists')
def on_color(color, txt):
res = ''
if isinstance(color, list):
res += ''.join([COLORS[x] for x in color])
else:
res += COLORS[color]
return res + txt + COLORS['ENDC']
def prompt(txt):
return on_color(PROMPT_COLORS, '{} >'.format(txt)) + ' '
def is_ip(name):
try:
socket.inet_aton(name)
return True
except socket.error:
return False
class cd:
"""Context manager for changing the current working directory"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(newPath)
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, etype, value, traceback):
os.chdir(self.savedPath)
def run(cmd, sudo=False, password=None, timeout=None):
''' Execute a command, yielding the stdout lines '''
assert(isinstance(cmd, str))
if sudo:
if password:
cmd = "echo %s | sudo -S %s" % (password, cmd)
else:
cmd = "sudo -S %s" % (cmd)
log.debug('exec: running "%s"', cmd)
popen = subprocess.Popen(
cmd, shell=True, stdout=subprocess.PIPE, universal_newlines=True)
if timeout:
timer = Timer(timeout, popen.kill)
try:
if timeout:
timer.start()
for stdout_line in iter(popen.stdout.readline, ""):
yield stdout_line
popen.stdout.close()
return_code = popen.wait()
if return_code:
raise subprocess.CalledProcessError(return_code, cmd)
finally:
if timeout:
timer.cancel()
def run_interactive(cmd, sudo=False, password=None):
''' Execute an interactive command, returning the `retcode` '''
assert(isinstance(cmd, str))
if sudo:
cmd = "echo %s | sudo -S %s" % (password, cmd)
log.debug('exec: starting interactive command "%s"', cmd)
return subprocess.call(cmd, shell=True)
def print_iterator(it, **kwargs):
if it:
for line in it:
print(line, end='', **kwargs)
####################################################################
# Terraform
####################################################################
class TerraformError(Exception):
pass
class InvalidMachineError(Exception):
pass
def get_work_dir():
if args.env:
return os.path.abspath(os.path.join(args.env_dir, args.env))
else:
return os.path.abspath(args.env_dir)
def get_tfstate_filename(tfstate=None):
if tfstate:
return os.path.abspath(tfstate)
if args.tf_state:
return os.path.abspath(args.tf_state)
return os.path.abspath(os.path.join(get_work_dir(), DEFAULT_TF_STATE))
def get_tfstatex_filename(tfstate=None):
return get_tfstate_filename(tfstate) + 'x'
def tf_load_state(filename=None):
'''
Load the Terraform ".state" file for getting IP addresses
for the VMs.
'''
res = {}
filename = filename or get_tfstate_filename()
if not os.path.exists(filename):
log.warning('state: "%s" does not exist', filename)
return res
with open(filename, "r") as tfstate:
try:
json_data = tfstate.read()
data = json.loads(json_data)
except ValueError as e:
log.error('state: parsing tfstate file: %s', e)
sys.exit(1)
for resource_name, resource_contents in data['modules'][0]['resources'].items():
if re.search('libvirt_domain\..*', resource_name):
try:
attrs = resource_contents['primary']['attributes']
name = attrs['name']
ipaddr = attrs['network_interface.0.addresses.0']
# if args.regex and not re.search(args.regex, name):
# continue
# else:
res[name] = ipaddr
except KeyError as e:
log.warning(
'state: cannot parse IP address for "%s" from %s: "%s" field not found', resource_name, filename, e)
res[name] = None
return res
def tf_load_statex(vars={}, vars_files=[], tfstate=None):
'''
Get things stuff from the statex file.
'''
res = {
'vars': vars,
'vars_files': list(vars_files)
}
tfstatex_filename = get_tfstatex_filename(tfstate)
if os.path.exists(tfstatex_filename):
log.debug('statex: trying to load from "%s"', tfstatex_filename)
with open(tfstatex_filename, 'r') as tfstatex:
try:
res_stored = json.load(tfstatex)
except ValueError as e:
log.error('statex: could not decode the JSON in %s: %s',
tfstatex_filename, e)
else:
log.debug('statex: file loaded successfully')
res['vars'].update(res_stored['vars'])
res['vars_files'] = list(res_stored['vars_files'])
else:
log.debug('statex: no file found at "%s"', tfstatex_filename)
return res
def tf_save_statex(vars={}, vars_files=[], tfstate=None):
'''
Use a tfstatex file for saving thigs like:
* the vars
* vars_files
we used for creating the cluster
'''
tfstatex_filename = get_tfstatex_filename(tfstate)
log.debug('statex: saving file as %s', tfstatex_filename)
with open(tfstatex_filename, 'w') as tfstatex:
tfstatex_contents = {
'vars': vars,
'vars_files': list(vars_files)
}
json.dump(tfstatex_contents, tfstatex, indent=2)