forked from ianmiell/shutit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shutit_class.py
4539 lines (4056 loc) · 198 KB
/
shutit_class.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
"""Contains all the core ShutIt methods and functionality, and public interface
off to internal objects such as shutit_pexpect.
"""
try:
from StringIO import StringIO
except ImportError: # pragma: no cover
from io import StringIO
import argparse
import base64
import codecs
import getpass
import glob
import hashlib
import imp
import json
import logging
import operator
import os
import tarfile
import re
import string
import sys
import subprocess
import textwrap
import time
from distutils.dir_util import mkpath
from distutils import spawn
import texttable
import pexpect
import shutit
import shutit_util
import shutit_global
import shutit_skeleton
import shutit_exam
try:
import ConfigParser
except ImportError: # pragma: no cover
import configparser as ConfigParser
from shutit_sendspec import ShutItSendSpec
from shutit_module import ShutItFailException, ShutItModule
from shutit_pexpect import ShutItPexpectSession
PY3 = (sys.version_info[0] >= 3)
def get_module_file(shutit, module):
shutit.shutit_file_map[module.module_id] = module.__module_file
return shutit.shutit_file_map[module.module_id]
def do_finalize():
"""Runs finalize phase; run after all builds are complete and all modules
have been stopped.
"""
def _finalize(shutit):
# Stop all the modules
shutit.stop_all()
# Finalize in reverse order
shutit.log('PHASE: finalizing object ' + str(shutit), level=logging.DEBUG)
# Login at least once to get the exports.
for module_id in shutit.module_ids(rev=True):
# Only finalize if it's thought to be installed.
if shutit.is_installed(shutit.shutit_map[module_id]):
shutit.login(prompt_prefix=module_id,command='bash --noprofile --norc',echo=False)
if not shutit.shutit_map[module_id].finalize(shutit):
shutit.fail(module_id + ' failed on finalize', shutit_pexpect_child=shutit.get_shutit_pexpect_session_from_id('target_child').pexpect_child) # pragma: no cover
shutit.logout(echo=False)
for shutit in shutit_global.shutit_global_object.shutit_objects:
_finalize(shutit)
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
class ShutItInit(object):
"""Object used to initialise a shutit object.
"""
def __init__(self,
action,
logfile='',
log='',
delivery='bash',
accept=False,
shutitfiles=None,
script=None,
base_image='ubuntu:16.04',
depends='shutit.tk.setup',
name='',
domain='',
pattern='',
output_dir=False,
vagrant_ssh_access=False,
vagrant_num_machines=None,
vagrant_machine_prefix=None,
vagrant_docker=None,
vagrant_snapshot=None,
vagrant_image_name=None,
push=False,
export=False,
save=False,
distro='',
mount_docker=False,
walkthrough=False,
walkthrough_wait=-1,
training=False,
choose_config=False,
config=[],
set=[],
ignorestop=False,
ignoreimage=False,
imageerrorok=False,
tag_modules=False,
image_tag='',
video=-1,
deps_only=False,
echo=False,
history=False,
long=False,
sort='id',
interactive=1,
trace=False,
shutit_module_path=None,
exam=False):
assert isinstance(action,str)
assert isinstance(logfile,str)
assert isinstance(log,str)
self.action = action
self.logfile = logfile
self.log = log
if self.action == 'version':
return
elif self.action == 'skeleton':
self.accept = accept
self.shutitfiles = shutitfiles
self.script = script
self.base_image = base_image
self.depends = depends
self.name = name
self.domain = domain
self.pattern = pattern
self.output_dir = output_dir
self.vagrant_ssh_access = vagrant_ssh_access
self.vagrant_num_machines = vagrant_num_machines
self.vagrant_machine_prefix = vagrant_machine_prefix
self.vagrant_docker = vagrant_docker
self.vagrant_snapshot = vagrant_snapshot
self.vagrant_image_name = vagrant_image_name
self.delivery = delivery
assert self.accept in (True,False,None)
assert not (self.shutitfiles and self.script),'Cannot have any two of script, -d/--shutitfiles <files> as arguments'
assert isinstance(self.base_image,str)
assert isinstance(self.depends,str)
#assert isinstance(self.shutitfiles,list)
assert isinstance(self.name,str)
assert isinstance(self.domain,str)
assert isinstance(self.pattern,str)
assert isinstance(self.output_dir,bool)
assert isinstance(self.vagrant_ssh_access,bool)
#assert isinstance(self.delivery,str)
# TODO: other asserts in other things.
elif self.action == 'run':
self.shutitfiles = shutitfiles
self.delivery = delivery
#assert isinstance(self.delivery,str)
#assert isinstance(self.shutitfiles,list)
elif self.action == 'build' or self.action == 'list_configs' or self.action == 'list_modules':
self.push = push
self.export = export
self.save = save
self.distro = distro
self.mount_docker = mount_docker
self.walkthrough = walkthrough
self.walkthrough_wait = walkthrough_wait
self.training = training
self.choose_config = choose_config
self.config = config
self.set = set
self.ignorestop = ignorestop
self.ignoreimage = ignoreimage
self.imageerrorok = imageerrorok
self.tag_modules = tag_modules
self.image_tag = image_tag
self.video = video
self.deps_only = deps_only
self.echo = echo
self.delivery = delivery
self.interactive = interactive
self.trace = trace
self.shutit_module_path = shutit_module_path
self.exam = exam
self.history = history
self.sort = sort
self.long = long
# Video/exam/training logic
if self.exam and not self.training:
print('Exam starting up')
self.training = True
if (self.exam or self.training) and not self.walkthrough:
if not self.exam:
print('--training or --exam implies --walkthrough, setting --walkthrough on!')
self.walkthrough = True
if isinstance(self.video, list) and self.video[0] >= 0:
self.walkthrough = True
self.walkthrough_wait = self.video[0]
self.video = True
if (self.video != -1 and self.video) and self.training:
print('--video and --training mode incompatible')
shutit_global.shutit_global_object.handle_exit(exit_code=1)
if (self.video != -1 and self.video) and self.exam:
print('--video and --exam mode incompatible')
shutit_global.shutit_global_object.handle_exit(exit_code=1)
#assert isinstance(self.delivery,str)
# If the image_tag has been set then ride roughshod over the ignoreimage value if not supplied
if self.image_tag != '' and self.ignoreimage is None:
self.ignoreimage = True
# If ignoreimage is still not set, then default it to False
if self.ignoreimage is None:
self.ignoreimage = False
if self.delivery in ('bash',):
if self.image_tag != '': # pragma: no cover
print('delivery method specified (' + self.delivery + ') and image_tag argument make no sense')
shutit_global.shutit_global_object.handle_exit(exit_code=1)
class ShutIt(object):
"""ShutIt build class.
Represents an instance of a ShutIt run/session/build with associated config.
"""
def __init__(self,
standalone):
"""Constructor.
Sets up:
- shutit_modules - representation of loaded shutit modules
- shutit_main_dir - directory in which shutit is located
- cfg - dictionary of configuration of build
- shutit_map - maps module_ids to module objects
standalone - Whether this is a shutit object created dynamically (True)
within a python script, or as part of a shutit invocation (False).
If it's created dynamically, then this can make a difference to
how the configuration is collected.
"""
self.standalone = standalone
# Store the root directory of this application.
# http://stackoverflow.com/questions/5137497
self.build = {}
self.build['report'] = ''
self.build['mount_docker'] = False
self.build['distro_override'] = ''
self.build['shutit_command_history'] = []
self.build['walkthrough'] = False # Whether to honour 'walkthrough' requests
self.build['walkthrough_wait'] = -1 # mysterious problems setting this to 1 with fixterm
self.build['log_config_path'] = None
self.build['step_through'] = False
self.build['ctrlc_stop'] = False
self.build['ctrlc_passthrough'] = False
self.build['have_read_config_file'] = False
self.build['vagrant_run_dir'] = None
self.build['this_vagrant_run_dir'] = None
self.build['accept_defaults'] = None
self.build['exam'] = False
# Host information - move to global?
self.host = {}
self.host['shutit_path'] = sys.path[0]
self.host['calling_path'] = os.getcwd()
self.build['asciinema_session'] = None
self.build['asciinema_session_file'] = None
# These used to be in shutit_global, so we pass them in as args so
# the original reference can be put in shutit_global
self.repository = {}
self.expect_prompts = {}
self.list_configs = {}
self.target = {}
self.action = {}
self.shutit_pexpect_sessions = {}
self.shutit_map = {}
self.shutit_file_map = {}
self.list_modules = {} # list_modules' options
self.current_shutit_pexpect_session = None
self.config_parser = None
self.shutit_modules = set()
# These are new members we dont have to provide compatibility for
self.conn_modules = set()
self.shutit_main_dir = os.path.abspath(os.path.dirname(__file__))
# Needed for patterns
self.cfg = {} # used to store module information
self.shutitfile = {}
self.cfg['shutitfile'] = self.shutitfile # required for patterns
self.cfg['skeleton'] = {} # required for patterns
def __str__(self):
string = 'ShutIt Object:\n'
string += '==============\n'
string += str(self.current_shutit_pexpect_session.login_stack)
return string
def get_shutit_pexpect_session_environment(self, environment_id):
"""Returns the first shutit_pexpect_session object related to the given
environment-id
"""
if not isinstance(environment_id, str):
self.fail('Wrong argument type in get_shutit_pexpect_session_environment') # pragma: no cover
for env in shutit_global.shutit_global_object.shutit_pexpect_session_environments:
if env.environment_id == environment_id:
return env
return None
def get_current_shutit_pexpect_session_environment(self, note=None):
"""Returns the current environment from the currently-set default
pexpect child.
"""
self.handle_note(note)
res = self.get_current_shutit_pexpect_session().current_environment
self.handle_note_after(note)
return res
def get_current_shutit_pexpect_session(self, note=None):
"""Returns the currently-set default pexpect child.
@return: default shutit pexpect child object
"""
self.handle_note(note)
res = self.current_shutit_pexpect_session
self.handle_note_after(note)
return res
def get_default_shutit_pexpect_session_expect(self):
"""Returns the currently-set default pexpect string (usually a prompt).
@return: default pexpect string
"""
return self.current_shutit_pexpect_session.default_expect
def get_default_shutit_pexpect_session_check_exit(self):
"""Returns default value of check_exit. See send method.
@rtype: boolean
@return: Default check_exit value
"""
return self.current_shutit_pexpect_session.check_exit
def set_default_shutit_pexpect_session(self, shutit_pexpect_session):
"""Sets the default pexpect child.
@param shutit_pexpect_session: pexpect child to set as default
"""
assert isinstance(shutit_pexpect_session, ShutItPexpectSession)
self.current_shutit_pexpect_session = shutit_pexpect_session
return True
def set_default_shutit_pexpect_session_expect(self, expect=None):
"""Sets the default pexpect string (usually a prompt).
Defaults to the configured root prompt if no
argument is passed.
@param expect: String to expect in the output
@type expect: string
"""
if expect is None:
self.current_shutit_pexpect_session.default_expect = self.expect_prompts['root']
else:
self.current_shutit_pexpect_session.default_expect = expect
return True
# TODO: should this be in global? Or fail globally if there is only one un-failed shutit object?
def fail(self, msg, shutit_pexpect_child=None, throw_exception=False):
"""Handles a failure, pausing if a pexpect child object is passed in.
@param shutit_pexpect_child: pexpect child to work on
@param throw_exception: Whether to throw an exception.
@type throw_exception: boolean
"""
# Note: we must not default to a child here
if shutit_pexpect_child is not None:
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
shutit_pexpect_session.pause_point('Pause point on fail: ' + msg, colour='31')
if throw_exception:
sys.stderr.write('Error caught: ' + msg + '\n')
sys.stderr.write('\n')
raise ShutItFailException(msg)
else:
# This is an "OK" failure, ie we don't need to throw an exception.
# However, it's still a failure, so return 1
shutit_global.shutit_global_object.log(msg,level=logging.CRITICAL)
shutit_global.shutit_global_object.log('Error seen, exiting with status 1',level=logging.CRITICAL)
shutit_global.shutit_global_object.handle_exit(exit_code=1,msg=msg)
def get_current_environment(self, note=None):
"""Returns the current environment id from the current
shutit_pexpect_session
"""
self.handle_note(note)
res = self.get_current_shutit_pexpect_session_environment().environment_id
self.handle_note_after(note)
return res
def multisend(self,
send,
send_dict,
expect=None,
shutit_pexpect_child=None,
timeout=3600,
check_exit=None,
fail_on_empty_before=True,
record_command=True,
exit_values=None,
escape=False,
echo=None,
note=None,
secret=False,
nonewline=False,
loglevel=logging.DEBUG):
"""Multisend. Same as send, except it takes multiple sends and expects in a dict that are
processed while waiting for the end "expect" argument supplied.
@param send_dict: see shutit_sendspec
@param expect: String or list of strings of final expected output that returns from this function. See send()
@param send: See send()
@param shutit_pexpect_child: See send()
@param timeout: See send()
@param check_exit: See send()
@param fail_on_empty_before: See send()
@param record_command: See send()
@param exit_values: See send()
@param echo: See send()
@param note: See send()
"""
assert isinstance(send_dict, dict)
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
expect = expect or self.get_current_shutit_pexpect_session().default_expect
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
return shutit_pexpect_session.multisend(ShutItSendSpec(shutit_pexpect_session,send=send,
send_dict=send_dict,
expect=expect,
timeout=timeout,
check_exit=check_exit,
fail_on_empty_before=fail_on_empty_before,
record_command=record_command,
exit_values=exit_values,
escape=escape,
echo=echo,
note=note,
loglevel=loglevel,
secret=secret,
nonewline=nonewline))
def send_and_require(self,
send,
regexps,
not_there=False,
shutit_pexpect_child=None,
echo=None,
note=None,
loglevel=logging.INFO):
"""Send string and require the item in the output.
See send_until
"""
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
return shutit_pexpect_session.send_and_require(send,
regexps,
not_there=not_there,
echo=echo,
note=note,
loglevel=loglevel)
def send_until(self,
send,
regexps,
not_there=False,
shutit_pexpect_child=None,
cadence=5,
retries=100,
echo=None,
note=None,
debug_command=None,
pause_point_on_fail=True,
nonewline=False,
loglevel=logging.INFO):
"""Send string on a regular cadence until a string is either seen, or the timeout is triggered.
@param send: See send()
@param regexps: List of regexps to wait for.
@param not_there: If True, wait until this a regexp is not seen in the output. If False
wait until a regexp is seen in the output (default)
@param shutit_pexpect_child: See send()
@param echo: See send()
@param note: See send()
"""
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
return shutit_pexpect_session.send_until(send,
regexps,
not_there=not_there,
cadence=cadence,
retries=retries,
echo=echo,
note=note,
loglevel=loglevel,
debug_command=debug_command,
nonewline=nonewline,
pause_point_on_fail=pause_point_on_fail)
def challenge(self,
task_desc,
expect=None,
hints=[],
congratulations='OK',
failed='FAILED',
expect_type='exact',
challenge_type='command',
shutit_pexpect_child=None,
timeout=None,
check_exit=None,
fail_on_empty_before=True,
record_command=True,
exit_values=None,
echo=True,
escape=False,
pause=1,
loglevel=logging.DEBUG,
follow_on_context=None,
num_stages=None):
"""Set the user a task to complete, success being determined by matching the output.
Either pass in regexp(s) desired from the output as a string or a list, or an md5sum of the output wanted.
@param follow_on_context On success, move to this context. A dict of information about that context.
context = the type of context, eg docker, bash
ok_container_name = if passed, send user to this container
reset_container_name = if resetting, send user to this container
@param challenge_type Behaviour of challenge made to user
command = check for output of single command
golf = user gets a pause point, and when leaving, command follow_on_context['check_command'] is run to check the output
"""
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
return shutit_pexpect_session.challenge(self,
task_desc=task_desc,
expect=expect,
hints=hints,
congratulations=congratulations,
failed=failed,
expect_type=expect_type,
challenge_type=challenge_type,
timeout=timeout,
check_exit=check_exit,
fail_on_empty_before=fail_on_empty_before,
record_command=record_command,
exit_values=exit_values,
echo=echo,
escape=escape,
pause=pause,
loglevel=loglevel,
follow_on_context=follow_on_context,
num_stages=num_stages)
# Alternate names
practice = challenge
golf = challenge
def send(self,
send,
expect=None,
shutit_pexpect_child=None,
timeout=None,
check_exit=None,
fail_on_empty_before=True,
record_command=True,
exit_values=None,
echo=None,
escape=False,
retry=3,
note=None,
assume_gnu=True,
follow_on_commands=None,
searchwindowsize=None,
maxread=None,
delaybeforesend=None,
secret=False,
nonewline=False,
background=False,
wait=True,
block_other_commands=True,
loglevel=logging.INFO):
"""Send string as a shell command, and wait until the expected output
is seen (either a string or any from a list of strings) before
returning. The expected string will default to the currently-set
default expected string (see get_default_shutit_pexpect_session_expect)
Returns the pexpect return value (ie which expected string in the list
matched)
@param send: See shutit.ShutItSendSpec
@param expect: See shutit.ShutItSendSpec
@param shutit_pexpect_child: See shutit.ShutItSendSpec
@param timeout: See shutit.ShutItSendSpec
@param check_exit: See shutit.ShutItSendSpec
@param fail_on_empty_before:See shutit.ShutItSendSpec
@param record_command:See shutit.ShutItSendSpec
@param exit_values:See shutit.ShutItSendSpec
@param echo: See shutit.ShutItSendSpec
@param escape: See shutit.ShutItSendSpec
@param retry: See shutit.ShutItSendSpec
@param note: See shutit.ShutItSendSpec
@param assume_gnu: See shutit.ShutItSendSpec
@param wait: See shutit.ShutItSendSpec
@param block_other_commands: See shutit.ShutItSendSpec.block_other_commands
@return: The pexpect return value (ie which expected string in the list matched)
@rtype: string
"""
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
ignore_background = not wait
#print('SEND: ' + send)
return shutit_pexpect_session.send(ShutItSendSpec(shutit_pexpect_session,
send,
expect=expect,
timeout=timeout,
check_exit=check_exit,
fail_on_empty_before=fail_on_empty_before,
record_command=record_command,
exit_values=exit_values,
echo=echo,
escape=escape,
retry=retry,
note=note,
assume_gnu=assume_gnu,
loglevel=loglevel,
follow_on_commands=follow_on_commands,
searchwindowsize=searchwindowsize,
maxread=maxread,
delaybeforesend=delaybeforesend,
secret=secret,
nonewline=nonewline,
run_in_background=background,
ignore_background=ignore_background,
block_other_commands=block_other_commands))
def send_and_return_status(self,
send,
expect=None,
shutit_pexpect_child=None,
timeout=None,
check_exit=None,
fail_on_empty_before=True,
record_command=True,
exit_values=None,
echo=None,
escape=False,
retry=3,
note=None,
assume_gnu=True,
follow_on_commands=None,
loglevel=logging.INFO):
"""Returns true if a good exit code was received (usually 0)
"""
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
shutit_pexpect_session.send(ShutItSendSpec(shutit_pexpect_session,send=send,
expect=expect,
timeout=timeout,
check_exit=check_exit,
fail_on_empty_before=fail_on_empty_before,
record_command=record_command,
exit_values=exit_values,
echo=echo,
escape=escape,
retry=retry,
note=note,
assume_gnu=assume_gnu,
loglevel=loglevel,
follow_on_commands=follow_on_commands))
return shutit_pexpect_session.check_last_exit_values(send,
expect=expect,
exit_values=exit_values,
retry=retry,
retbool=True)
def handle_note(self, note, command='', training_input=''):
"""Handle notes and walkthrough option.
@param note: See send()
"""
if self.build['walkthrough'] and note != None and note != '':
assert isinstance(note, str)
wait = self.build['walkthrough_wait']
wrap = '\n' + 80*'=' + '\n'
message = wrap + note + wrap
if command != '':
message += 'Command to be run is:\n\t' + command + wrap
if wait >= 0:
self.pause_point(message, colour=31, wait=wait)
else:
if training_input != '' and self.build['training']:
if len(training_input.split('\n')) == 1:
print(shutit_util.colourise('31',message))
while shutit_util.util_raw_input(prompt=shutit_util.colourise('32','Enter the command to continue (or "s" to skip typing it in): ')) not in (training_input,'s'):
print('Wrong! Try again!')
print(shutit_util.colourise('31','OK!'))
else:
self.pause_point(message + '\nToo long to use for training, so skipping the option to type in!\nHit CTRL-] to continue', colour=31)
else:
self.pause_point(message + '\nHit CTRL-] to continue', colour=31)
return True
def handle_note_after(self, note, training_input=''):
if self.build['walkthrough'] and note != None:
wait = self.build['walkthrough_wait']
if wait >= 0:
time.sleep(wait)
if training_input != '' and self.build['training']:
self.pause_point('Training mode - pause point.\nDo what you like, but try not to disturb state too much,\neg by moving directories exiting the/entering a new shell.\nHit CTRL-] to continue.')
return True
def expect_allow_interrupt(self,
shutit_pexpect_child,
expect,
timeout,
iteration_s=1):
"""This function allows you to interrupt the run at more or less any
point by breaking up the timeout into interactive chunks.
"""
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
accum_timeout = 0
if isinstance(expect, str):
expect = [expect]
if timeout < 1:
timeout = 1
if iteration_s > timeout:
iteration_s = timeout - 1
if iteration_s < 1:
iteration_s = 1
timed_out = True
while accum_timeout < timeout:
res = shutit_pexpect_session.expect(expect, timeout=iteration_s)
if res == len(expect):
if self.build['ctrlc_stop']:
timed_out = False
self.build['ctrlc_stop'] = False
break
accum_timeout += iteration_s
else:
return res
if timed_out and not shutit_global.shutit_global_object.determine_interactive():
shutit_global.shutit_global_object.log('Command timed out, trying to get terminal back for you', level=logging.DEBUG)
self.fail('Timed out and could not recover') # pragma: no cover
else:
if shutit_global.shutit_global_object.determine_interactive():
shutit_pexpect_child.send('\x03')
res = shutit_pexpect_child.expect(expect,timeout=1)
if res == len(expect):
shutit_pexpect_child.send('\x1a')
res = shutit_pexpect_child.expect(expect,timeout=1)
if res == len(expect):
self.fail('CTRL-C sent by ShutIt following a timeout, and could not recover') # pragma: no cover
shutit_pexpect_session.pause_point('CTRL-C sent by ShutIt following a timeout; the command has been cancelled')
return res
else:
if timed_out:
self.fail('Timed out and interactive, but could not recover') # pragma: no cover
else:
self.fail('CTRL-C hit and could not recover') # pragma: no cover
self.fail('Should not get here (expect_allow_interrupt)') # pragma: no cover
return True
def run_script(self,
script,
shutit_pexpect_child=None,
in_shell=True,
note=None,
loglevel=logging.DEBUG):
"""Run the passed-in string as a script on the target's command line.
@param script: String representing the script. It will be de-indented
and stripped before being run.
@param shutit_pexpect_child: See send()
@param in_shell: Indicate whether we are in a shell or not. (Default: True)
@param note: See send()
@type script: string
@type in_shell: boolean
"""
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
return shutit_pexpect_session.run_script(script,in_shell=in_shell,note=note,loglevel=loglevel)
def send_file(self,
path,
contents,
shutit_pexpect_child=None,
truncate=False,
note=None,
user=None,
group=None,
loglevel=logging.INFO,
encoding=None):
"""Sends the passed-in string as a file to the passed-in path on the
target.
@param path: Target location of file on target.
@param contents: Contents of file as a string.
@param shutit_pexpect_child: See send()
@param note: See send()
@param user: Set ownership to this user (defaults to whoami)
@param group: Set group to this user (defaults to first group in groups)
@type path: string
@type contents: string
"""
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
return shutit_pexpect_session.send_file(path,
contents,
truncate=truncate,
note=note,
user=user,
group=group,
loglevel=loglevel,
encoding=encoding)
def chdir(self,
path,
shutit_pexpect_child=None,
timeout=3600,
note=None,
loglevel=logging.DEBUG):
"""How to change directory will depend on whether we are in delivery mode bash or docker.
@param path: Path to send file to.
@param shutit_pexpect_child: See send()
@param timeout: Timeout on response
@param note: See send()
"""
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
return shutit_pexpect_session.chdir(path,timeout=timeout,note=note,loglevel=loglevel)
def send_host_file(self,
path,
hostfilepath,
expect=None,
shutit_pexpect_child=None,
note=None,
user=None,
group=None,
loglevel=logging.INFO):
"""Send file from host machine to given path
@param path: Path to send file to.
@param hostfilepath: Path to file from host to send to target.
@param expect: See send()
@param shutit_pexpect_child: See send()
@param note: See send()
@param user: Set ownership to this user (defaults to whoami)
@param group: Set group to this user (defaults to first group in groups)
@type path: string
@type hostfilepath: string
"""
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
expect = expect or self.get_current_shutit_pexpect_session().default_expect
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
self.handle_note(note, 'Sending file from host: ' + hostfilepath + ' to target path: ' + path)
shutit_global.shutit_global_object.log('Sending file from host: ' + hostfilepath + ' to: ' + path, level=loglevel)
if user is None:
user = shutit_pexpect_session.whoami()
if group is None:
group = self.whoarewe()
# TODO: use gz for both
if os.path.isfile(hostfilepath):
shutit_pexpect_session.send_file(path,
codecs.open(hostfilepath,mode='rb',encoding='iso-8859-1').read(),
user=user,
group=group,
loglevel=loglevel,
encoding='iso-8859-1')
elif os.path.isdir(hostfilepath):
# Need a binary type encoding for gzip(?)
self.send_host_dir(path,
hostfilepath,
user=user,
group=group,
loglevel=loglevel)
else:
self.fail('send_host_file - file: ' + hostfilepath + ' does not exist as file or dir. cwd is: ' + os.getcwd(), shutit_pexpect_child=shutit_pexpect_child, throw_exception=False) # pragma: no cover
self.handle_note_after(note=note)
return True
def send_host_dir(self,
path,
hostfilepath,
expect=None,
shutit_pexpect_child=None,
note=None,
user=None,
group=None,
loglevel=logging.DEBUG):
"""Send directory and all contents recursively from host machine to
given path. It will automatically make directories on the target.