forked from ianmiell/shutit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shutit_util.py
1889 lines (1725 loc) · 76.5 KB
/
shutit_util.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 pythen
"""ShutIt utility functions.
"""
# The MIT License (MIT)
#
# Copyright (C) 2014 OpenBet Limited
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# ITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
try:
from StringIO import StringIO
except ImportError: # pragma: no cover
from io import StringIO
import argparse
import base64
import binascii
import getpass
import glob
import hashlib
import imp
import json
import logging
import operator
import os
import random
import re
import readline
import stat
import string
import sys
import threading
import time
import subprocess
import textwrap
try:
import ConfigParser
except ImportError: # pragma: no cover
import configparser as ConfigParser
import texttable
import pexpect
import shutit
import shutit_assets
import shutit_skeleton
import shutit_exam
import shutit_global
from shutit_module import ShutItFailException
from shutit_module import ShutItModule
PY3 = (sys.version_info[0] >= 3)
allowed_delivery_methods = ['ssh','dockerfile','bash','docker','vagrant']
class LayerConfigParser(ConfigParser.RawConfigParser):
def __init__(self):
ConfigParser.RawConfigParser.__init__(self)
self.layers = []
def read(self, filenames):
if not isinstance(filenames, list):
filenames = [filenames]
for filename in filenames:
cp = ConfigParser.RawConfigParser()
cp.read(filename)
self.layers.append((cp, filename, None))
return ConfigParser.RawConfigParser.read(self, filenames)
def readfp(self, fp, filename=None):
cp = ConfigParser.RawConfigParser()
fp.seek(0)
cp.readfp(fp, filename)
self.layers.append((cp, filename, fp))
fp.seek(0)
ret = ConfigParser.RawConfigParser.readfp(self, fp, filename)
return ret
def whereset(self, section, option):
for cp, filename, fp in reversed(self.layers):
fp = fp # pylint
if cp.has_option(section, option):
return filename
raise ShutItFailException('[%s]/%s was never set' % (section, option)) # pragma: no cover
def get_config_set(self, section, option):
"""Returns a set with each value per config file in it.
"""
values = set()
for cp, filename, fp in self.layers:
filename = filename # pylint
fp = fp # pylint
if cp.has_option(section, option):
values.add(cp.get(section, option))
return values
def reload(self):
"""
Re-reads all layers again. In theory this should overwrite all the old
values with any newer ones.
It assumes we never delete a config item before reload.
"""
oldlayers = self.layers
self.layers = []
for cp, filename, fp in oldlayers:
cp = cp # pylint
if fp is None:
self.read(filename)
else:
self.readfp(fp, filename)
def remove_section(self, *args, **kwargs):
raise NotImplementedError('''Layer config parsers aren't directly mutable''') # pragma: no cover
def remove_option(self, *args, **kwargs):
raise NotImplementedError('''Layer config parsers aren't directly mutable''') # pragma: no cover
def set(self, *args, **kwargs):
raise NotImplementedError('''Layer config parsers aren\'t directly mutable''') # pragma: no cover
def is_file_secure(file_name):
"""Returns false if file is considered insecure, true if secure.
If file doesn't exist, it's considered secure!
"""
if not os.path.isfile(file_name):
return True
file_mode = os.stat(file_name).st_mode
if file_mode & (stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH):
return False
return True
def colourise(code, msg):
"""Colourize the given string for a terminal.
"""
if code == '' or code is None:
return msg # pragma: no cover
return '\033[%sm%s\033[0m' % (code, msg)
def get_configs(shutit, configs):
"""Reads config files in, checking their security first
(in case passwords/sensitive info is in them).
"""
cp = LayerConfigParser()
fail_str = ''
files = []
for config_file in configs:
if isinstance(config_file, tuple):
continue
if not is_file_secure(config_file):
fail_str = fail_str + '\nchmod 0600 ' + config_file
files.append(config_file)
if fail_str != '':
if shutit.build['interactive'] > 1:
fail_str = 'Files are not secure, mode should be 0600. Running the following commands to correct:\n' + fail_str + '\n'
# Actually show this to the user before failing...
shutit.log(fail_str)
shutit.log('Do you want me to run this for you? (input y/n)')
if shutit.build['interactive'] == 0 or util_raw_input(shutit, default='y') == 'y':
for f in files:
shutit.log('Correcting insecure file permissions on: ' + f)
os.chmod(f,0o600)
# recurse
return get_configs(shutit, configs)
else:
for f in files:
shutit.log('Correcting insecure file permissions on: ' + f)
os.chmod(f,0o600)
# recurse
return get_configs(shutit, configs)
shutit.fail(fail_str) # pragma: no cover
for config in configs:
if isinstance(config, tuple):
cp.readfp(config[1], filename=config[0])
else:
cp.read(config)
# Treat allowed_images as a special, additive case
shutit.build['shutit.core.module.allowed_images'] = cp.get_config_set('build', 'shutit.core.module.allowed_images')
return cp
def random_id(size=8, chars=string.ascii_letters + string.digits):
"""Generates a random string of given size from the given chars.
@param size: The size of the random string.
@param chars: Constituent pool of characters to draw random characters from.
@type size: number
@type chars: string
@rtype: string
@return: The string of random characters.
"""
return ''.join(random.choice(chars) for _ in range(size))
def random_word(size=6):
"""Returns a random word in lower case.
"""
words = shutit_assets.get_words().splitlines()
word = ''
while len(word) != size or word.find("'") > -1:
word = words[int(random.random() * (len(words) - 1))]
return word.lower()
def find_asset(shutit, filename):
(head,filename) = os.path.split(filename)
if head == '':
dirs = ['/usr/share/dict',
sys.prefix,
os.path.join(sys.prefix,'local'),
shutit.shutit_main_dir,
os.path.join(shutit.shutit_main_dir,'../../..'),
shutit.host['shutit_path'],
'/usr/local'
]
dirs = dirs + sys.path
else:
dirs = ['/usr/share/dict' + '/' + head,
sys.prefix + '/' + head,
os.path.join(sys.prefix,'local') + '/' + head,
shutit.shutit_main_dir + '/' + head,
os.path.join(shutit.shutit_main_dir,'../../..') + '/' + head,
shutit.host['shutit_path'] + '/' + head,
'/usr/local' + '/' + head
]
dirs = dirs + sys.path
for iter_dir in dirs:
if os.access(os.path.join(iter_dir,filename),os.F_OK):
return os.path.join(iter_dir,filename)
if os.access(os.path.join(os.path.join(iter_dir,'assets'),filename),os.F_OK):
return os.path.join(os.path.join(iter_dir,'assets'),filename)
if os.access(os.path.join(os.path.join(iter_dir,'shutit_assets'),filename),os.F_OK):
return os.path.join(os.path.join(iter_dir,'shutit_assets'),filename)
return filename
# Set up logging
#
def setup_logging(shutit):
# If loglevel is an int, this has already been set up.
if isinstance(shutit.build['loglevel'], int):
return
logformat='%(asctime)s %(levelname)s: %(message)s'
logging.addLevelName(5, 'FORENSIC')
if shutit_global.shutit_global_object.logfile == '':
if not os.access(shutit.build['shutit_state_dir_base'],os.F_OK):
os.mkdir(shutit.build['shutit_state_dir_base'])
if not os.access(shutit.build['shutit_state_dir'],os.F_OK):
os.mkdir(shutit.build['shutit_state_dir'])
os.chmod(shutit.build['shutit_state_dir_base'],0o777)
os.chmod(shutit.build['shutit_state_dir'],0o777)
shutit.build['loglevel'] = shutit.build['loglevel'].upper()
if shutit.build['loglevel'] == 'DEBUG':
logging.basicConfig(format=logformat,level=logging.DEBUG)
elif shutit.build['loglevel'] == 'ERROR':
logging.basicConfig(format=logformat,level=logging.ERROR)
elif shutit.build['loglevel'] in ('WARN','WARNING'):
logging.basicConfig(format=logformat,level=logging.WARNING)
elif shutit.build['loglevel'] == 'CRITICAL':
logging.basicConfig(format=logformat,level=logging.CRITICAL)
elif shutit.build['loglevel'] == 'INFO':
logging.basicConfig(format=logformat,level=logging.INFO)
elif shutit.build['loglevel'] == 'FORENSIC':
logging.basicConfig(format=logformat,filename=shutit_global.shutit_global_object.logfile,level=logging.FORENSIC)
else:
logging.basicConfig(format=logformat,level=logging.INFO)
else:
shutit.build['loglevel'] = shutit.build['loglevel'].upper()
if shutit.build['loglevel'] == 'DEBUG':
logging.basicConfig(format=logformat,filename=shutit_global.shutit_global_object.logfile,level=logging.DEBUG)
elif shutit.build['loglevel'] == 'ERROR':
logging.basicConfig(format=logformat,filename=shutit_global.shutit_global_object.logfile,level=logging.ERROR)
elif shutit.build['loglevel'] in ('WARN','WARNING'):
logging.basicConfig(format=logformat,filename=shutit_global.shutit_global_object.logfile,level=logging.WARNING)
elif shutit.build['loglevel'] == 'CRITICAL':
logging.basicConfig(format=logformat,filename=shutit_global.shutit_global_object.logfile,level=logging.CRITICAL)
elif shutit.build['loglevel'] == 'INFO':
logging.basicConfig(format=logformat,filename=shutit_global.shutit_global_object.logfile,level=logging.INFO)
elif shutit.build['loglevel'] == 'FORENSIC':
logging.basicConfig(format=logformat,filename=shutit_global.shutit_global_object.logfile,level=logging.FORENSIC)
else:
logging.basicConfig(format=logformat,filename=shutit_global.shutit_global_object.logfile,level=logging.INFO)
shutit.build['loglevel'] = logging.getLogger().getEffectiveLevel()
# Manage config settings, returning a dict representing the settings
# that have been sanity-checked.
def get_base_config(shutit, cfg_parser):
"""Responsible for getting core configuration from config files.
"""
shutit.config_parser = cp = cfg_parser
# BEGIN Read from config files
# build - details relating to the build
shutit.build['privileged'] = cp.getboolean('build', 'privileged')
shutit.build['base_image'] = cp.get('build', 'base_image')
shutit.build['dotest'] = cp.get('build', 'dotest')
shutit.build['net'] = cp.get('build', 'net')
shutit.build['completed'] = False
shutit.build['step_through'] = False
shutit.build['ctrlc_stop'] = False
shutit.build['ctrlc_passthrough'] = False
shutit.build['have_read_config_file'] = False
# Width of terminal to set up on login and assume for other cases.
shutit.build['stty_cols'] = 320
shutit.build['vagrant_run_dir'] = None
shutit.build['this_vagrant_run_dir'] = None
# Signals are set here, which is useful for context-switching callbacks.
shutit.shutit_signal['ID'] = 0 # TODO: global?
# Take a command-line arg if given, else default.
if shutit.build['conn_module'] is None:
shutit.build['conn_module'] = cp.get('build', 'conn_module')
# Whether to accept default configs
shutit.build['accept_defaults'] = None
# target - the target of the build, ie the container
shutit.target['hostname'] = cp.get('target', 'hostname')
shutit.target['locale'] = cp.get('target', 'locale')
shutit.target['ports'] = cp.get('target', 'ports')
shutit.target['volumes'] = cp.get('target', 'volumes')
shutit.target['volumes_from'] = cp.get('target', 'volumes_from')
shutit.target['name'] = cp.get('target', 'name')
shutit.target['rm'] = cp.getboolean('target', 'rm')
# host - the host on which the shutit script is run
shutit.host['add_shutit_to_path'] = cp.getboolean('host', 'add_shutit_to_path')
shutit.host['docker_executable'] = cp.get('host', 'docker_executable')
shutit.host['dns'] = cp.get('host', 'dns')
shutit.host['password'] = cp.get('host', 'password')
if isinstance(shutit.host['password'],str):
shutit_global.shutit_global_object.secret_words_set.add(shutit.host['password'])
shutit_global.shutit_global_object.logfile = cp.get('host', 'logfile')
shutit.host['shutit_module_path'] = cp.get('host', 'shutit_module_path').split(':')
# repository - information relating to repository/registry
shutit.repository['name'] = cp.get('repository', 'name')
shutit.repository['server'] = cp.get('repository', 'server')
shutit.repository['push'] = cp.getboolean('repository', 'push')
shutit.repository['tag'] = cp.getboolean('repository', 'tag')
shutit.repository['export'] = cp.getboolean('repository', 'export')
shutit.repository['save'] = cp.getboolean('repository', 'save')
shutit.repository['suffix_date'] = cp.getboolean('repository', 'suffix_date')
shutit.repository['suffix_format'] = cp.get('repository', 'suffix_format')
shutit.repository['user'] = cp.get('repository', 'user')
shutit.repository['password'] = cp.get('repository', 'password')
if isinstance(shutit.repository['password'],str):
shutit_global.shutit_global_object.secret_words_set.add(shutit.repository['password'])
shutit.repository['email'] = cp.get('repository', 'email')
shutit.repository['tag_name'] = cp.get('repository', 'tag_name')
# END Read from config files
# BEGIN Standard expects
# It's important that these have '.*' in them at the start, so that the matched data is reliably 'after' in the
# child object. Use these where possible to make things more consistent.
# Attempt to capture any starting prompt (when starting) with this regexp.
shutit.expect_prompts['base_prompt'] = '\r\n.*[@#$] '
# END Standard expects
if shutit.target['docker_image'] == '':
shutit.target['docker_image'] = shutit.build['base_image']
# END tidy configs up
# BEGIN warnings
# FAILS begins
# rm is incompatible with repository actions
if shutit.target['rm'] and (shutit.repository['tag'] or shutit.repository['push'] or shutit.repository['save'] or shutit.repository['export']): # pragma: no cover
print("Can't have [target]/rm and [repository]/(push/save/export) set to true")
handle_exit(shutit=shutit, exit_code=1)
if shutit.target['hostname'] != '' and shutit.build['net'] != '' and shutit.build['net'] != 'bridge': # pragma: no cover
print('\n\ntarget/hostname or build/net configs must be blank\n\n')
handle_exit(shutit=shutit, exit_code=1)
# FAILS ends
# Returns the config dict
def parse_args(shutit, set_loglevel=None):
r"""Responsible for parsing arguments.
Environment variables:
SHUTIT_OPTIONS:
Loads command line options from the environment (if set).
Behaves like GREP_OPTIONS:
- space separated list of arguments
- backslash before a space escapes the space separation
- backslash before a backslash is interpreted as a single backslash
- all other backslashes are treated literally
eg ' a\ b c\\ \\d \\\e\' becomes '', 'a b', 'c\', '\d', '\\e\'
SHUTIT_OPTIONS is ignored if we are creating a skeleton
"""
shutit.host['real_user_id'] = pexpect.run('id -u ' + shutit.host['real_user'])
# These are in order of their creation
actions = ['build', 'run', 'list_configs', 'list_modules', 'list_deps', 'skeleton', 'version']
# COMPAT 2014-05-15 - build is the default if there is no action specified
# and we've not asked for help and we've called via 'shutit.py'
if len(sys.argv) == 1 or (len(sys.argv) > 1 and sys.argv[1] not in actions
and '-h' not in sys.argv and '--help' not in sys.argv):
sys.argv.insert(1, 'build')
parser = argparse.ArgumentParser(description='ShutIt - a tool for managing complex Docker deployments.\n\nTo view help for a specific subcommand, type ./shutit <subcommand> -h',prog="ShutIt")
subparsers = parser.add_subparsers(dest='action', help='''Action to perform - build=deploy to target, skeleton=construct a skeleton module, list_configs=show configuration as read in, list_modules=show modules available, list_deps=show dep graph ready for graphviz. Defaults to 'build'.''')
sub_parsers = dict()
for action in actions:
sub_parsers[action] = subparsers.add_parser(action)
sub_parsers['run'].add_argument('shutitfiles', nargs='*', default=['ShutItFile','Shutitfile','ShutItfile','ShutitFile','shutitfile'])
sub_parsers['skeleton'].add_argument('--name', help='Absolute path to new directory for module. Last part of path is taken as the module name.',default='')
sub_parsers['skeleton'].add_argument('--domain', help='Arbitrary but unique domain for namespacing your module, eg com.mycorp',default='')
sub_parsers['skeleton'].add_argument('--depends', help='Module id to depend on, default shutit.tk.setup (optional)', default='shutit.tk.setup')
sub_parsers['skeleton'].add_argument('--base_image', help='FROM image, default ubuntu:16.04 (optional)', default='ubuntu:16.04')
sub_parsers['skeleton'].add_argument('--script', help='Pre-existing shell script to integrate into module (optional)', nargs='?', default=None)
sub_parsers['skeleton'].add_argument('--output_dir', help='Just output the created directory', default=False, const=True, action='store_const')
sub_parsers['skeleton'].add_argument('--shutitfiles', nargs='+', default=None)
sub_parsers['skeleton'].add_argument('--vagrant_num_machines', default=None)
sub_parsers['skeleton'].add_argument('--vagrant_ssh_access', default=False, const=True, action='store_const')
sub_parsers['skeleton'].add_argument('--vagrant_machine_prefix', default=None)
sub_parsers['skeleton'].add_argument('--vagrant_docker', default=None, const=True, action='store_const')
sub_parsers['skeleton'].add_argument('--pattern', help='Pattern to use', default='')
sub_parsers['skeleton'].add_argument('--delivery', help='Delivery method, aka target. "docker" container (default), configured "ssh" connection, "bash" session', default=None, choices=('docker','dockerfile','ssh','bash'))
sub_parsers['skeleton'].add_argument('-a','--accept', help='Accept defaults', const=True, default=False, action='store_const')
sub_parsers['skeleton'].add_argument('--log','-l', help='Log level (DEBUG, INFO (default), WARNING, ERROR, CRITICAL)', default='')
sub_parsers['skeleton'].add_argument('-o','--logfile', help='Log output to this file', default='')
sub_parsers['build'].add_argument('--export', help='Perform docker export to a tar file', const=True, default=False, action='store_const')
sub_parsers['build'].add_argument('--save', help='Perform docker save to a tar file', const=True, default=False, action='store_const')
sub_parsers['build'].add_argument('--push', help='Push to a repo', const=True, default=False, action='store_const')
sub_parsers['build'].add_argument('--distro', help='Specify the distro type', default='', choices=('ubuntu','debian','alpine','steamos','red hat','centos','fedora','shutit'))
sub_parsers['build'].add_argument('--mount_docker', help='Mount the docker socket', default=False, action='store_const', const=True)
sub_parsers['build'].add_argument('-w','--walkthrough', help='Run in walkthrough mode', default=False, action='store_const', const=True)
sub_parsers['build'].add_argument('-c','--choose_config', help='Choose configuration interactively', default=False, action='store_const', const=True)
sub_parsers['build'].add_argument('--video', help='Run in video mode. Same as walkthrough, but waits n seconds rather than for input', nargs=1, default=-1)
sub_parsers['build'].add_argument('--training', help='Run in "training" mode, where correct input is required at key points', default=False, action='store_const', const=True)
sub_parsers['build'].add_argument('--exam', help='Run in "exam" mode, where correct input is required at key points and progress is tracked', default=False, action='store_const', const=True)
sub_parsers['list_configs'].add_argument('--history', help='Show config with history', const=True, default=False, action='store_const')
sub_parsers['list_modules'].add_argument('--long', help='Show extended module info, including ordering', const=True, default=False, action='store_const')
sub_parsers['list_modules'].add_argument('--sort', help='Order the modules seen, default to module id', default='id', choices=('id','run_order'))
for action in ['build', 'list_configs', 'list_modules', 'list_deps','run']:
sub_parsers[action].add_argument('-o','--logfile',default='', help='Log output to this file')
sub_parsers[action].add_argument('-l','--log',default='', help='Log level (DEBUG, INFO (default), WARNING, ERROR, CRITICAL)',choices=('DEBUG','INFO','WARNING','ERROR','CRITICAL','debug','info','warning','error','critical'))
if action != 'run':
sub_parsers[action].add_argument('-d','--delivery', help='Delivery method, aka target. "docker" container (default), configured "ssh" connection, "bash" session', default=None, choices=('docker','dockerfile','ssh','bash'))
sub_parsers[action].add_argument('--config', help='Config file for setup config. Must be with perms 0600. Multiple arguments allowed; config files considered in order.', default=[], action='append')
sub_parsers[action].add_argument('-s', '--set', help='Override a config item, e.g. "-s target rm no". Can be specified multiple times.', default=[], action='append', nargs=3, metavar=('SEC', 'KEY', 'VAL'))
sub_parsers[action].add_argument('--image_tag', help='Build container from specified image - if there is a symbolic reference, please use that, eg localhost.localdomain:5000/myref', default='')
sub_parsers[action].add_argument('--tag_modules', help='''Tag each module after it's successfully built regardless of the module config and based on the repository config.''', default=False, const=True, action='store_const')
sub_parsers[action].add_argument('-m', '--shutit_module_path', default=None, help='List of shutit module paths, separated by colons. ShutIt registers modules by running all .py files in these directories.')
sub_parsers[action].add_argument('--trace', help='Trace function calls', const=True, default=False, action='store_const')
sub_parsers[action].add_argument('--interactive', help='Level of interactive. 0 = none, 1 = honour pause points and config prompting, 2 = query user on each module, 3 = tutorial mode', default='1')
sub_parsers[action].add_argument('--ignorestop', help='Ignore STOP files', const=True, default=False, action='store_const')
sub_parsers[action].add_argument('--ignoreimage', help='Ignore disallowed images', const=True, default=None, action='store_const')
sub_parsers[action].add_argument('--imageerrorok', help='Exit without error if allowed images fails (used for test scripts)', const=True, default=False, action='store_const')
sub_parsers[action].add_argument('--deps_only', help='build deps only, tag with suffix "_deps"', const=True, default=False, action='store_const')
sub_parsers[action].add_argument('--echo', help='Always echo output', const=True, default=False, action='store_const')
args_list = sys.argv[1:]
if os.environ.get('SHUTIT_OPTIONS', None) and args_list[0] != 'skeleton':
env_args = os.environ['SHUTIT_OPTIONS'].strip()
# Split escaped backslashes
env_args_split = re.split(r'(\\\\)', env_args)
# Split non-escaped spaces
env_args_split = [re.split(r'(?<!\\)( )', item) for item in env_args_split]
# Flatten
env_args_split = [item for sublist in env_args_split for item in sublist]
# Split escaped spaces
env_args_split = [re.split(r'(\\ )', item) for item in env_args_split]
# Flatten
env_args_split = [item for sublist in env_args_split for item in sublist]
# Trim empty strings
env_args_split = [item for item in env_args_split if item != '']
# We know we don't have to deal with an empty env argument string
env_args_list = ['']
# Interpret all of the escape sequences
for item in env_args_split:
if item == ' ':
env_args_list.append('')
elif item == '\\ ':
env_args_list[-1] += ' '
elif item == '\\\\':
env_args_list[-1] += '\\'
else:
env_args_list[-1] += item
args_list[1:1] = env_args_list
args = parser.parse_args(args_list)
process_args(shutit, args, set_loglevel=set_loglevel)
def process_args(shutit, args, set_loglevel):
"""Process the args we have.
"""
if args.action == 'version':
print('ShutIt version: ' + shutit.shutit_version)
handle_exit(shutit=shutit, exit_code=0)
# What are we asking shutit to do?
shutit.action['list_configs'] = args.action == 'list_configs'
shutit.action['list_modules'] = args.action == 'list_modules'
shutit.action['list_deps'] = args.action == 'list_deps'
shutit.action['skeleton'] = args.action == 'skeleton'
shutit.action['build'] = args.action == 'build'
shutit.action['run'] = args.action == 'run'
# Logging
shutit_global.shutit_global_object.logfile = args.logfile
shutit.build['exam'] = False
shutit.build['loglevel'] = args.log
if shutit.build['loglevel'] in ('', None):
shutit.build['loglevel'] = set_loglevel
if shutit.build['loglevel'] in ('', None):
shutit.build['loglevel'] = 'INFO'
setup_logging(shutit)
# This mode is a bit special - it's the only one with different arguments
if shutit.action['skeleton']:
delivery_method = args.delivery
accept_defaults = args.accept
# Looks through the arguments given for valid shutitfiles, and adds their names to _new_shutitfiles.
if args.shutitfiles and args.script:
shutit.fail('Cannot have any two of script, -d/--shutitfiles <files> as arguments') # pragma: no cover
_new_shutitfiles = None
if args.shutitfiles:
cwd = os.getcwd()
_new_shutitfiles = []
_delivery_methods_seen = set()
for shutitfile in args.shutitfiles:
if shutitfile[0] != '/':
shutitfile = cwd + '/' + shutitfile
if os.path.isfile(shutitfile):
candidate_shutitfile_fh = open(shutitfile,'r')
candidate_shutitfile_contents = candidate_shutitfile_fh.read()
candidate_shutitfile_fh.close()
try:
shutitfile_representation, ok = shutit_skeleton.process_shutitfile(shutit, candidate_shutitfile_contents)
if not ok or candidate_shutitfile_contents.strip() == '':
print('Ignoring file (failed to parse candidate shutitfile): ' + shutitfile)
else:
_new_shutitfiles.append(shutitfile)
if len(shutitfile_representation['shutitfile']['delivery']) > 0:
_delivery_methods_seen.add(shutitfile_representation['shutitfile']['delivery'][0][1])
except Exception as e:
print('')
print(e)
print('Ignoring file (failed to parse candidate shutitfile): ' + shutitfile)
elif os.path.isdir(shutitfile):
for root, subfolders, files in os.walk(shutitfile):
subfolders.sort()
files.sort()
for fname in files:
candidate_shutitfile = os.path.join(root, fname)
try:
if os.path.isfile(candidate_shutitfile):
candidate_shutitfile_fh = open(candidate_shutitfile,'r')
candidate_shutitfile_contents = candidate_shutitfile_fh.read()
candidate_shutitfile_fh.close()
shutitfile_representation, ok = shutit_skeleton.process_shutitfile(shutit, candidate_shutitfile_contents)
if not ok or candidate_shutitfile_contents.strip() == '':
print('Ignoring file (failed to parse candidate shutitfile): ' + candidate_shutitfile)
else:
_new_shutitfiles.append(candidate_shutitfile)
if len(shutitfile_representation['shutitfile']['delivery']) > 0:
_delivery_methods_seen.add(shutitfile_representation['shutitfile']['delivery'][0][1])
else:
print('Ignoring filename (not a normal file): ' + fname)
except:
print('Ignoring file (failed to parse candidate shutitfile): ' + candidate_shutitfile)
if _new_shutitfiles:
if len(_delivery_methods_seen) == 0 and delivery_method is None:
delivery_method = 'bash'
elif len(_delivery_methods_seen) == 0:
pass
elif len(_delivery_methods_seen) == 1 and delivery_method is None:
delivery_method = _delivery_methods_seen.pop()
elif len(_delivery_methods_seen) == 1:
shutitfile_delivery_method = _delivery_methods_seen.pop()
if delivery_method != shutitfile_delivery_method:
print('Conflicting delivery methods passed in vs. from shutitfile.\nPassed-in: ' + delivery_method + '\nShutitfile: ' + shutitfile_delivery_method)
handle_exit(shutit=shutit, exit_code=1)
else:
print('Too many delivery methods seen in shutitfiles: ' + str(_new_shutitfiles))
print('Delivery methods: ' + str(_delivery_methods_seen))
print('Delivery method passed in: ' + delivery_method)
handle_exit(shutit=shutit, exit_code=1)
else:
print('ShutItFiles: ' + str(_new_shutitfiles) + ' appear to not exist.')
handle_exit(shutit=shutit, exit_code=1)
module_directory = args.name
if module_directory == '':
default_dir = shutit.host['calling_path'] + '/shutit_' + random_word()
if accept_defaults:
module_directory = default_dir
else:
module_directory = util_raw_input(shutit, prompt='# Input a name for this module.\n# Default: ' + default_dir + '\n', default=default_dir)
if module_directory[0] != '/':
module_directory = shutit.host['calling_path'] + '/' + module_directory
module_name = module_directory.split('/')[-1].replace('-','_')
if args.domain == '':
default_domain_name = os.getcwd().split('/')[-1] + '.' + module_name
#if accept_defaults:
domain = default_domain_name
#else:
# domain = util_raw_input(shutit, prompt='# Input a unique domain, eg (com.yourcorp).\n# Default: ' + default_domain_name + '\n', default=default_domain_name)
else:
domain = args.domain
# Figure out defaults.
# If no pattern supplied, then assume it's the same as delivery.
default_pattern = 'bash'
if args.pattern == '':
if accept_defaults or _new_shutitfiles:
if _new_shutitfiles:
default_pattern = delivery_method
pattern = default_pattern
else:
pattern = util_raw_input(shutit, prompt='''# Input a ShutIt pattern.
Default: ''' + default_pattern + '''
bash: a shell script
docker: a docker image build
vagrant: a vagrant setup
docker_tutorial: a docker-based tutorial
shutitfile: a shutitfile-based project (can be docker, bash, vagrant)
''',default=default_pattern)
else:
pattern = args.pattern
# Sort out delivery method.
if delivery_method is None:
take_this_default = False
default_delivery = 'bash'
if pattern in ('docker','docker_tutorial', 'shutitfile'):
if pattern in ('docker','docker_tutorial'):
take_this_default = True
default_delivery = 'docker'
elif pattern in ('vagrant','bash'):
take_this_default = True
default_delivery = 'bash'
else:
default_delivery = 'bash'
if accept_defaults or take_this_default:
delivery = default_delivery
else:
delivery = ''
while delivery not in allowed_delivery_methods:
delivery = util_raw_input(shutit, prompt=textwrap.dedent('''
# Input a delivery method from: bash, docker, vagrant.
# Default: ' + default_delivery + '
docker: build within a docker image
bash: run commands directly within bash
vagrant: build an n-node vagrant cluster
'''), default=default_delivery)
else:
delivery = delivery_method
shutit.cfg['skeleton'] = {
'path': module_directory,
'module_name': module_name,
'base_image': args.base_image,
'domain': domain,
'domain_hash': str(get_hash(domain)),
'depends': args.depends,
'script': args.script,
'shutitfiles': _new_shutitfiles,
'output_dir': args.output_dir,
'delivery': delivery,
'pattern': pattern,
'vagrant_num_machines': args.vagrant_num_machines,
'vagrant_ssh_access': args.vagrant_ssh_access,
'vagrant_machine_prefix': args.vagrant_machine_prefix,
'vagrant_docker': args.vagrant_docker
}
# set defaults to allow config to work
shutit.build['extra_configs'] = []
shutit.build['config_overrides'] = []
shutit.build['conn_module'] = None
shutit.build['delivery'] = 'bash'
shutit.target['docker_image'] = ''
elif shutit.action['run']:
module_name = random_id(chars=string.ascii_letters)
module_dir = "/tmp/shutit_built/" + module_name
module_domain = module_name + '.' + module_name
argv_new = [sys.argv[0],'skeleton','--shutitfile'] + args.shutitfiles + ['--name', module_dir,'--domain',module_domain,'--pattern','bash']
retdir = os.getcwd()
subprocess.call(argv_new)
os.chdir(module_dir)
subprocess.call('./run.sh')
os.chdir(retdir)
sys.exit(0)
else:
shutit_home = shutit.host['shutit_path'] = os.path.expanduser('~/.shutit')
# We're not creating a skeleton, so make sure we have the infrastructure
# in place for a user-level storage area
if not os.path.isdir(shutit_home):
os.mkdir(shutit_home, 0o700)
if not os.path.isfile(os.path.join(shutit_home, 'config')):
f = os.open(os.path.join(shutit_home, 'config'), os.O_WRONLY | os.O_CREAT, 0o600)
if PY3:
os.write(f,bytes(_default_cnf,'utf-8'))
else:
os.write(f,_default_cnf)
os.close(f)
# Default this to False as it's not always set (mostly for debug logging).
shutit.list_configs['cfghistory'] = False
shutit.list_modules['long'] = False
shutit.list_modules['sort'] = None
shutit.build['video'] = False
shutit.build['training'] = False
shutit.build['exam_object'] = None
shutit.build['choose_config'] = False
# Persistence- and build-related arguments.
if shutit.action['build']:
shutit.repository['push'] = args.push
shutit.repository['export'] = args.export
shutit.repository['save'] = args.save
shutit.build['distro_override'] = args.distro
shutit.build['mount_docker'] = args.mount_docker
shutit.build['walkthrough'] = args.walkthrough
shutit.build['training'] = args.training
shutit.build['exam'] = args.exam
shutit.build['choose_config'] = args.choose_config
if shutit.build['exam'] and not shutit.build['training']:
# We want it to be quiet
#print('--exam implies --training, setting --training on!')
print('Exam starting up')
shutit.build['training'] = True
if (shutit.build['exam'] or shutit.build['training']) and not shutit.build['walkthrough']:
if not shutit.build['exam']:
print('--training or --exam implies --walkthrough, setting --walkthrough on!')
shutit.build['walkthrough'] = True
if isinstance(args.video, list) and args.video[0] >= 0:
shutit.build['walkthrough'] = True
shutit.build['walkthrough_wait'] = float(args.video[0])
shutit.build['video'] = True
if shutit.build['training']:
print('--video and --training mode incompatible')
handle_exit(shutit=shutit, exit_code=1)
if shutit.build['exam']:
print('--video and --exam mode incompatible')
handle_exit(shutit=shutit, exit_code=1)
# Create a test session object if needed.
if shutit.build['exam']:
shutit.build['exam_object'] = shutit_exam.ShutItExamSession(shutit)
elif shutit.action['list_configs']:
shutit.list_configs['cfghistory'] = args.history
elif shutit.action['list_modules']:
shutit.list_modules['long'] = args.long
shutit.list_modules['sort'] = args.sort
# What are we building on? Convert arg to conn_module we use.
if args.delivery == 'docker' or args.delivery is None:
shutit.build['conn_module'] = 'shutit.tk.conn_docker'
shutit.build['delivery'] = 'docker'
elif args.delivery == 'ssh':
shutit.build['conn_module'] = 'shutit.tk.conn_ssh'
shutit.build['delivery'] = 'ssh'
elif args.delivery == 'bash' or args.delivery == 'dockerfile':
shutit.build['conn_module'] = 'shutit.tk.conn_bash'
shutit.build['delivery'] = args.delivery
# If the image_tag has been set then ride roughshod over the ignoreimage value if not supplied
if args.image_tag != '' and args.ignoreimage is None:
args.ignoreimage = True
# If ignoreimage is still not set, then default it to False
if args.ignoreimage is None:
args.ignoreimage = False
# Get these early for this part of the build.
# These should never be config arguments, since they are needed before config is passed in.
if args.shutit_module_path is not None:
module_paths = args.shutit_module_path.split(':')
if '.' not in module_paths:
module_paths.append('.')
args.set.append(('host', 'shutit_module_path', ':'.join(module_paths)))
shutit.build['trace'] = args.trace
shutit.build['interactive'] = int(args.interactive)
shutit.build['extra_configs'] = args.config
shutit.build['config_overrides'] = args.set
shutit.build['ignorestop'] = args.ignorestop
shutit.build['ignoreimage'] = args.ignoreimage
shutit.build['imageerrorok'] = args.imageerrorok
shutit.build['tag_modules'] = args.tag_modules
shutit.build['deps_only'] = args.deps_only
shutit.build['always_echo'] = args.echo
shutit.target['docker_image'] = args.image_tag
if shutit.build['delivery'] in ('bash','ssh'):
if shutit.target['docker_image'] != '': # pragma: no cover
print('delivery method specified (' + shutit.build['delivery'] + ') and image_tag argument make no sense')
handle_exit(shutit=shutit, exit_code=1)
# Finished parsing args.
# Sort out config path
if shutit.action['list_configs'] or shutit.action['list_modules'] or shutit.action['list_deps'] or shutit.build['loglevel'] == logging.DEBUG:
shutit.build['log_config_path'] = shutit.build['shutit_state_dir'] + '/config/' + shutit.build['build_id']
if os.path.exists(shutit.build['log_config_path']):
print(shutit.build['log_config_path'] + ' exists. Please move and re-run.')
handle_exit(shutit=shutit, exit_code=1)
os.makedirs(shutit.build['log_config_path'])
os.chmod(shutit.build['log_config_path'],0o777)
else:
shutit.build['log_config_path'] = None
# Tutorial stuff. TODO: ditch tutorial mode
#The config is read in the following order:
#~/.shutit/config
# - Host- and username-specific config for this host.
#/path/to/this/shutit/module/configs/build.cnf
# - Config specifying what should be built when this module is invoked.
#/your/path/to/<configname>.cnf
# - Passed-in config (via --config, see --help)
#command-line overrides, eg -s com.mycorp.mymodule.module name value
# Set up trace as fast as possible.
if shutit.build['trace']:
def tracefunc(frame, event, arg, indent=[0]):
indent = indent # pylint
arg = arg # pylint
if event == 'call':
shutit.log('-> call function: ' + frame.f_code.co_name + ' ' + str(frame.f_code.co_varnames),level=logging.DEBUG)
elif event == 'return':
shutit.log('<- exit function: ' + frame.f_code.co_name,level=logging.DEBUG)
return tracefunc
sys.settrace(tracefunc)
def load_configs(shutit):
"""Responsible for loading config files into ShutIt.
Recurses down from configured shutit module paths.
"""
# Get root default config.
configs = [('defaults', StringIO(_default_cnf)), os.path.expanduser('~/.shutit/config'), os.path.join(shutit.host['shutit_path'], 'config'), 'configs/build.cnf']
# Add the shutit global host- and user-specific config file.
# Add the local build.cnf
# Get passed-in config(s)
for config_file_name in shutit.build['extra_configs']:
run_config_file = os.path.expanduser(config_file_name)
if not os.path.isfile(run_config_file):
print('Did not recognise ' + run_config_file + ' as a file - do you need to touch ' + run_config_file + '?')
handle_exit(shutit=shutit, exit_code=0)
configs.append(run_config_file)
# Image to use to start off. The script should be idempotent, so running it
# on an already built image should be ok, and is advised to reduce diff space required.
if shutit.action['list_configs'] or shutit.build['loglevel'] <= logging.DEBUG:
msg = ''
for c in configs:
if isinstance(c, tuple):
c = c[0]
msg = msg + ' \n' + c
shutit.log(' ' + c,level=logging.DEBUG)
# TODO: what if this does not exist?
if shutit.build['log_config_path']:
f = open(shutit.build['log_config_path'] + '/config_file_order.txt','w')
f.write(msg)
f.close()
# Interpret any config overrides, write to a file and add them to the
# list of configs to be interpreted
if shutit.build['config_overrides']:
# We don't need layers, this is a temporary configparser
override_cp = ConfigParser.RawConfigParser()
for o_sec, o_key, o_val in shutit.build['config_overrides']:
if not override_cp.has_section(o_sec):
override_cp.add_section(o_sec)
override_cp.set(o_sec, o_key, o_val)
override_fd = StringIO()
override_cp.write(override_fd)
override_fd.seek(0)
configs.append(('overrides', override_fd))
cfg_parser = get_configs(shutit, configs)
get_base_config(shutit, cfg_parser)
if shutit.build['loglevel'] <= logging.DEBUG:
# Set up the manhole.
try:
import manhole
manhole.install(
verbose=True,
patch_fork=True,
activate_on=None,
oneshot_on=None,
sigmask=manhole._ALL_SIGNALS,
socket_path=None,
reinstall_delay=0.5,
locals=None
)
except Exception:
shutit.log('No manhole package available, skipping import',level=logging.DEBUG)
def load_shutit_modules(shutit):
"""Responsible for loading the shutit modules based on the configured module
paths.
"""
if shutit.build['loglevel'] <= logging.DEBUG:
shutit.log('ShutIt module paths now: ',level=logging.DEBUG)
shutit.log(shutit.host['shutit_module_path'],level=logging.DEBUG)
for shutit_module_path in shutit.host['shutit_module_path']:
load_all_from_path(shutit, shutit_module_path)
def list_modules(shutit, long_output=None,sort_order=None):
"""Display a list of loaded modules.
Config items:
- shutit.list_modules['long']
If set, also print each module's run order value
- shutit.list_modules['sort']
Select the column by which the list is ordered:
- id: sort the list by module id
- run_order: sort the list by module run order
The output is also saved to ['build']['log_config_path']/module_order.txt
Dependencies: operator
"""
cfg = shutit.cfg
# list of module ids and other details
# will also contain column headers
table_list = []
if long_output is None:
long_output = shutit.list_modules['long']
if sort_order is None:
sort_order = shutit.list_modules['sort']
if long_output:
# --long table: sort modules by run order
table_list.append(["Order","Module ID","Description","Run Order","Built","Compatible"])
#table_list.append(["Order","Module ID","Description","Run Order","Built"])
else:
# "short" table ==> sort module by module_id
#table_list.append(["Module ID","Description","Built"])
table_list.append(["Module ID","Description","Built","Compatible"])
if sort_order == 'run_order':
d = {}
for m in shutit.shutit_modules:
d.update({m.module_id:m.run_order})
# sort dict by run_order; see http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
b = sorted(d.items(), key=operator.itemgetter(1))
count = 0
# now b is a list of tuples (module_id, run_order)
for pair in b:
# module_id is the first item of the tuple
k = pair[0]
for m in shutit.shutit_modules:
if m.module_id == k:
count += 1
compatible = True
if not cfg[m.module_id]['shutit.core.module.build']:
cfg[m.module_id]['shutit.core.module.build'] = True
compatible = determine_compatibility(shutit, m.module_id) == 0
cfg[m.module_id]['shutit.core.module.build'] = False
if long_output:
table_list.append([str(count),m.module_id,m.description,str(m.run_order),str(cfg[m.module_id]['shutit.core.module.build']),str(compatible)])
#table_list.append([str(count),m.module_id,m.description,str(m.run_order),str(cfg[m.module_id]['shutit.core.module.build'])])
else:
table_list.append([m.module_id,m.description,str(cfg[m.module_id]['shutit.core.module.build']),str(compatible)])
elif sort_order == 'id':
l = []
for m in shutit.shutit_modules:
l.append(m.module_id)
l.sort()
for k in l:
for m in shutit.shutit_modules:
if m.module_id == k:
count = 1
compatible = True
if not cfg[m.module_id]['shutit.core.module.build']:
cfg[m.module_id]['shutit.core.module.build'] = True
compatible = determine_compatibility(shutit, m.module_id) == 0
if long_output:
table_list.append([str(count),m.module_id,m.description,str(m.run_order),str(cfg[m.module_id]['shutit.core.module.build']),str(compatible)])
#table_list.append([str(count),m.module_id,m.description,str(m.run_order),str(cfg[m.module_id]['shutit.core.module.build'])])
else:
#table_list.append([m.module_id,m.description,str(cfg[m.module_id]['shutit.core.module.build'])])
table_list.append([m.module_id,m.description,str(cfg[m.module_id]['shutit.core.module.build']),str(compatible)])
# format table for display
table = texttable.Texttable()
table.add_rows(table_list)
# Base length of table on length of strings