def do_finalize(shutit): """Runs finalize phase; run after all builds are complete and all modules have been stopped. """ cfg = shutit.cfg # Stop all the modules if cfg['build']['interactive'] >= 3: print('\nStopping all modules before finalize phase' + shutit_util.colour('32', '\n\n[Hit return to continue]\n')) shutit_util.util_raw_input(shutit=shutit) stop_all(shutit) # Finalize in reverse order shutit.log('PHASE: finalize', code='32') if cfg['build']['interactive'] >= 3: print('\nNow doing finalize phase, which we do when all builds are ' + 'complete and modules are stopped' + shutit_util.colour('32', '\n\n[Hit return to continue]\n')) shutit_util.util_raw_input(shutit=shutit) # Login at least once to get the exports. for module_id in shutit_util.module_ids(shutit, rev=True): # Only finalize if it's thought to be installed. if shutit_util.is_installed(shutit, shutit.shutit_map[module_id]): shutit.login(prompt_prefix=module_id,command='bash') if not shutit.shutit_map[module_id].finalize(shutit): shutit.fail(module_id + ' failed on finalize', child=shutit.pexpect_children['target_child']) shutit.logout()
def do_finalize(shutit): """Runs finalize phase; run after all builds are complete and all modules have been stopped. """ cfg = shutit.cfg # Stop all the modules if cfg['build']['interactive'] >= 3: print('\nStopping all modules before finalize phase' + shutit_util.colour('32', '\n\n[Hit return to continue]\n')) shutit_util.util_raw_input(shutit=shutit) stop_all(shutit) # Finalize in reverse order shutit.log('PHASE: finalize', code='32') if cfg['build']['interactive'] >= 3: print('\nNow doing finalize phase, which we do when all builds are ' + 'complete and modules are stopped' + shutit_util.colour('32', '\n\n[Hit return to continue]\n')) shutit_util.util_raw_input(shutit=shutit) # Login at least once to get the exports. for module_id in module_ids(shutit, rev=True): # Only finalize if it's thought to be installed. if is_installed(shutit, shutit.shutit_map[module_id]): shutit.login(prompt_prefix=module_id, command='bash') if not shutit.shutit_map[module_id].finalize(shutit): shutit.fail(module_id + ' failed on finalize', child=shutit.pexpect_children['target_child']) shutit.logout()
def do_finalize(shutit): """Runs finalize phase; run after all builds are complete and all modules have been stopped. """ cfg = shutit.cfg # Stop all the modules if cfg["build"]["interactive"] >= 3: print ( "\nStopping all modules before finalize phase" + shutit_util.colour("32", "\n\n[Hit return to continue]\n") ) shutit_util.util_raw_input(shutit=shutit) stop_all(shutit) # Finalize in reverse order shutit.log("PHASE: finalize", code="32") if cfg["build"]["interactive"] >= 3: print ( "\nNow doing finalize phase, which we do when all builds are " + "complete and modules are stopped" + shutit_util.colour("32", "\n\n[Hit return to continue]\n") ) shutit_util.util_raw_input(shutit=shutit) # Login at least once to get the exports. for module_id in module_ids(shutit, rev=True): # Only finalize if it's thought to be installed. if is_installed(shutit, shutit.shutit_map[module_id]): shutit.login(prompt_prefix=module_id, command="bash") if not shutit.shutit_map[module_id].finalize(shutit): shutit.fail(module_id + " failed on finalize", child=shutit.pexpect_children["target_child"]) shutit.logout()
def do_test(shutit): """Runs test phase, erroring if any return false. """ cfg = shutit.cfg if not cfg['build']['dotest']: shutit.log('Tests configured off, not running') return # Test in reverse order shutit.log('PHASE: test', code='32') if cfg['build']['interactive'] >= 3: print '\nNow doing test phase' + shutit_util.colour( '32', '\n\n[Hit return to continue]\n') shutit_util.util_raw_input(shutit=shutit) stop_all(shutit) start_all(shutit) for module_id in module_ids(shutit, rev=True): module = shutit.shutit_map[module_id] # Only test if it's installed. if is_installed(shutit, shutit.shutit_map[module_id]): shutit.log('RUNNING TEST ON: ' + module_id, code='32') shutit.login(prompt_prefix=module_id, command='bash') if not shutit.shutit_map[module_id].test(shutit): shutit.fail(module_id + ' failed on test', child=shutit.pexpect_children['target_child']) shutit.logout()
def do_test(shutit): """Runs test phase, erroring if any return false. """ cfg = shutit.cfg if not cfg['build']['dotest']: shutit.log('Tests configured off, not running') return # Test in reverse order shutit.log('PHASE: test', code='32') if cfg['build']['interactive'] >= 3: print '\nNow doing test phase' + shutit_util.colour('32', '\n\n[Hit return to continue]\n') shutit_util.util_raw_input(shutit=shutit) stop_all(shutit) start_all(shutit) for module_id in module_ids(shutit, rev=True): module = shutit.shutit_map[module_id] # Only test if it's installed. if is_installed(shutit, shutit.shutit_map[module_id]): shutit.log('RUNNING TEST ON: ' + module_id, code='32') shutit.login(prompt_prefix=module_id,command='bash') if not shutit.shutit_map[module_id].test(shutit): shutit.fail(module_id + ' failed on test', child=shutit.pexpect_children['target_child']) shutit.logout()
def build(self, shutit): """Sets up the machine ready for building. """ cfg = shutit.cfg ssh_host = cfg[self.module_id]['ssh_host'] ssh_port = cfg[self.module_id]['ssh_port'] ssh_user = cfg[self.module_id]['ssh_user'] ssh_pass = cfg[self.module_id]['password'] ssh_key = cfg[self.module_id]['ssh_key'] ssh_cmd = cfg[self.module_id]['ssh_cmd'] opts = [ '-t', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no' ] if ssh_pass == '': opts += ['-o', 'PasswordAuthentication=no'] if ssh_port != '': opts += ['-p', ssh_port] if ssh_key != '': opts += ['-i', ssh_key] host_arg = ssh_host if host_arg == '': shutit.fail('No host specified for sshing', throw_exception=False) if ssh_user != '': host_arg = ssh_user + '@' + host_arg cmd_arg = ssh_cmd if cmd_arg == '': cmd_arg = 'sudo su -s /bin/bash -' ssh_command = ['ssh'] + opts + [host_arg, cmd_arg] if cfg['build']['interactive'] >= 3: print('\n\nAbout to connect to host.' + '\n\n' + shutit_util.colour('32', '\n[Hit return to continue]')) shutit_util.util_raw_input(shutit=shutit) cfg['build']['ssh_command'] = ' '.join(ssh_command) shutit.log('\n\nCommand being run is:\n\n' + cfg['build']['ssh_command'], force_stdout=True, prefix=False) target_child = pexpect.spawn(ssh_command[0], ssh_command[1:]) expect = ['assword', cfg['expect_prompts']['base_prompt'].strip()] res = target_child.expect(expect, 10) while True: shutit.log(target_child.before + target_child.after, prefix=False, force_stdout=True) if res == 0: shutit.log('...') res = shutit.send(ssh_pass, child=target_child, expect=expect, timeout=10, check_exit=False, fail_on_empty_before=False) elif res == 1: shutit.log('Prompt found, breaking out') break self._setup_prompts(shutit, target_child) self._add_begin_build_info(shutit, ssh_command) return True
def init_shutit_map(shutit): """Initializes the module map of shutit based on the modules we have gathered. Checks we have core modules Checks for duplicate module details. Sets up common config. Sets up map of modules. """ cfg = shutit.cfg modules = shutit.shutit_modules # Have we got anything to process outside of special modules? if len([mod for mod in modules if mod.run_order > 0]) < 1: shutit.log(modules,level=logging.DEBUG) path = ':'.join(cfg['host']['shutit_module_path']) shutit.log('\nIf you are new to ShutIt, see:\n\n\thttp://ianmiell.github.io/shutit/\n\nor try running\n\n\tshutit skeleton\n\n',code=32,level=logging.INFO) if path == '': shutit.fail('No ShutIt modules aside from core ones found and no ShutIt module path given.\nDid you set --shutit_module_path/-m wrongly?\n') elif path == '.': shutit.fail('No modules aside from core ones found and no ShutIt module path given apart from default (.).\n\n- Did you set --shutit_module_path/-m?\n- Is there a STOP* file in your . dir?') else: shutit.fail('No modules aside from core ones found and no ShutIt modules in path:\n\n' + path + '\n\nor their subfolders. Check your --shutit_module_path/-m setting and check that there are ShutIt modules below without STOP* files in any relevant directories.') shutit.log('PHASE: base setup', level=logging.DEBUG) if cfg['build']['interactive'] >= 3: shutit.log('\nChecking to see whether there are duplicate module ids or run orders in the visible modules.\nModules I see are:\n',level=logging.DEBUG) for module in modules: shutit.log(module.module_id, level=logging.DEBUG) shutit.log('\n',level=logging.DEBUG) run_orders = {} has_core_module = False for module in modules: assert isinstance(module, ShutItModule) if module.module_id in shutit.shutit_map: shutit.fail('Duplicated module id: ' + module.module_id + '\n\nYou may want to check your --shutit_module_path setting') if module.run_order in run_orders: shutit.fail('Duplicate run order: ' + str(module.run_order) + ' for ' + module.module_id + ' and ' + run_orders[module.run_order].module_id + '\n\nYou may want to check your --shutit_module_path setting') if module.run_order == 0: has_core_module = True shutit.shutit_map[module.module_id] = run_orders[module.run_order] = module if not has_core_module: shutit.fail('No module with run_order=0 specified! This is required.') if cfg['build']['interactive'] >= 3: print(shutit_util.colour('32', 'Module id and run order checks OK\n\n[Hit return to continue]\n')) shutit_util.util_raw_input(shutit=shutit)
def stop_all(shutit, run_order=-1): """Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc. """ cfg = shutit.cfg if cfg['build']['interactive'] >= 3: print('\nRunning stop on all modules' + shutit_util.colour('32', '\n\n[Hit return to continue]')) shutit_util.util_raw_input(shutit=shutit) # sort them so they're stopped in reverse order for module_id in shutit_util.module_ids(shutit, rev=True): shutit_module_obj = shutit.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if shutit_util.is_installed(shutit, shutit_module_obj): if not shutit_module_obj.stop(shutit): shutit.fail('failed to stop: ' + module_id, shutit_pexpect_child=shutit.get_shutit_pexpect_session_from_id('target_child').shutit_pexpect_child)
def stop_all(shutit, run_order=-1): """Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc. """ cfg = shutit.cfg if cfg["build"]["interactive"] >= 3: print ("\nRunning stop on all modules" + shutit_util.colour("32", "\n\n[Hit return to continue]")) shutit_util.util_raw_input(shutit=shutit) # sort them so they're stopped in reverse order for module_id in module_ids(shutit, rev=True): shutit_module_obj = shutit.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if is_installed(shutit, shutit_module_obj): if not shutit_module_obj.stop(shutit): shutit.fail("failed to stop: " + module_id, child=shutit.pexpect_children["target_child"])
def start_all(shutit, run_order=-1): """Runs start method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we can export a clean target and still depended-on modules running if necessary. """ cfg = shutit.cfg if cfg["build"]["interactive"] >= 3: print ("\nRunning start on all modules" + shutit_util.colour("32", "\n\n[Hit return to continue]\n")) shutit_util.util_raw_input(shutit=shutit) # sort them so they're started in order for module_id in module_ids(shutit): shutit_module_obj = shutit.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if is_installed(shutit, shutit_module_obj): if not shutit_module_obj.start(shutit): shutit.fail("failed to start: " + module_id, child=shutit.pexpect_children["target_child"])
def start_all(shutit, run_order=-1): """Runs start method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we can export a clean target and still depended-on modules running if necessary. """ cfg = shutit.cfg if cfg['build']['interactive'] >= 3: print('\nRunning start on all modules' + shutit_util.colour('32', '\n\n[Hit return to continue]\n')) shutit_util.util_raw_input(shutit=shutit) # sort them so they're started in order for module_id in shutit_util.module_ids(shutit): shutit_module_obj = shutit.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if shutit_util.is_installed(shutit, shutit_module_obj): if not shutit_module_obj.start(shutit): shutit.fail('failed to start: ' + module_id, shutit_pexpect_child=shutit.get_shutit_pexpect_session_from_id('target_child').shutit_pexpect_child)
def do_build(shutit): """Runs build phase, building any modules that we've determined need building. """ cfg = shutit.cfg shutit.log('PHASE: build, repository work', code='32') shutit.log(shutit_util.print_config(cfg)) if cfg['build']['interactive'] >= 3: print ('\nNow building any modules that need building' + shutit_util.colour('32', '\n\n[Hit return to continue]\n')) shutit_util.util_raw_input(shutit=shutit) module_id_list = shutit_util.module_ids(shutit) if cfg['build']['deps_only']: module_id_list_build_only = filter(lambda x: cfg[x]['shutit.core.module.build'], module_id_list) for module_id in module_id_list: module = shutit.shutit_map[module_id] shutit.log('considering whether to build: ' + module.module_id, code='32') if cfg[module.module_id]['shutit.core.module.build']: if cfg['build']['delivery'] not in module.ok_delivery_methods: shutit.fail('Module: ' + module.module_id + ' can only be built with one of these --delivery methods: ' + str(module.ok_delivery_methods) + '\nSee shutit build -h for more info, or try adding: --delivery <method> to your shutit invocation') if shutit_util.is_installed(shutit,module): cfg['build']['report'] = (cfg['build']['report'] + '\nBuilt already: ' + module.module_id + ' with run order: ' + str(module.run_order)) else: # We move to the module directory to perform the build, returning immediately afterwards. if cfg['build']['deps_only'] and module_id == module_id_list_build_only[-1]: # If this is the last module, and we are only building deps, stop here. cfg['build']['report'] = (cfg['build']['report'] + '\nSkipping: ' + module.module_id + ' with run order: ' + str(module.run_order) + '\n\tas this is the final module and we are building dependencies only') else: revert_dir = os.getcwd() cfg['environment'][cfg['build']['current_environment_id']]['module_root_dir'] = os.path.dirname(module.__module_file) shutit.chdir(cfg['environment'][cfg['build']['current_environment_id']]['module_root_dir']) shutit.login(prompt_prefix=module_id,command='bash') build_module(shutit, module) shutit.logout() shutit.chdir(revert_dir) if shutit_util.is_installed(shutit, module): shutit.log('Starting module') if not module.start(shutit): shutit.fail(module.module_id + ' failed on start', child=shutit.pexpect_children['target_child'])
def stop_all(shutit, run_order=-1): """Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc. """ cfg = shutit.cfg if cfg['build']['interactive'] >= 3: print('\nRunning stop on all modules' + \ shutit_util.colour('32', '\n\n[Hit return to continue]')) shutit_util.util_raw_input(shutit=shutit) # sort them so they're stopped in reverse order for module_id in module_ids(shutit, rev=True): shutit_module_obj = shutit.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if is_installed(shutit, shutit_module_obj): if not shutit_module_obj.stop(shutit): shutit.fail('failed to stop: ' + \ module_id, child=shutit.pexpect_children['target_child'])
def start_all(shutit, run_order=-1): """Runs start method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we can export a clean target and still depended-on modules running if necessary. """ cfg = shutit.cfg if cfg['build']['interactive'] >= 3: print('\nRunning start on all modules' + shutit_util.colour('32', '\n\n[Hit return to continue]\n')) shutit_util.util_raw_input(shutit=shutit) # sort them so they're started in order for module_id in module_ids(shutit): shutit_module_obj = shutit.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if is_installed(shutit, shutit_module_obj): if not shutit_module_obj.start(shutit): shutit.fail('failed to start: ' + module_id, \ child=shutit.pexpect_children['target_child'])
def conn_target(shutit): """Connect to the target. """ cfg = shutit.cfg conn_module = None cfg = shutit.cfg for mod in shutit.conn_modules: if mod.module_id == cfg['build']['conn_module']: conn_module = mod break if conn_module is None: shutit.fail('Couldn\'t find conn_module ' + cfg['build']['conn_module']) # Set up the target in pexpect. if cfg['build']['interactive'] >= 3: print('\nRunning the conn module (' + shutit.shutit_main_dir + '/shutit_setup.py)' + shutit_util.colour('32', '\n\n[Hit return to continue]\n')) shutit_util.util_raw_input(shutit=shutit) conn_module.get_config(shutit) conn_module.build(shutit)
def do_test(shutit): """Runs test phase, erroring if any return false. """ cfg = shutit.cfg if not cfg["build"]["dotest"]: shutit.log("Tests configured off, not running") return # Test in reverse order shutit.log("PHASE: test", code="32") if cfg["build"]["interactive"] >= 3: print "\nNow doing test phase" + shutit_util.colour("32", "\n\n[Hit return to continue]\n") shutit_util.util_raw_input(shutit=shutit) stop_all(shutit) start_all(shutit) for module_id in module_ids(shutit, rev=True): module = shutit.shutit_map[module_id] # Only test if it's installed. if is_installed(shutit, shutit.shutit_map[module_id]): shutit.log("RUNNING TEST ON: " + module_id, code="32") shutit.login(prompt_prefix=module_id, command="bash") if not shutit.shutit_map[module_id].test(shutit): shutit.fail(module_id + " failed on test", child=shutit.pexpect_children["target_child"]) shutit.logout()
def conn_target(shutit): """Connect to the target. """ cfg = shutit.cfg conn_module = None cfg = shutit.cfg for mod in shutit.conn_modules: if mod.module_id == cfg["build"]["conn_module"]: conn_module = mod break if conn_module is None: shutit.fail("Couldn't find conn_module " + cfg["build"]["conn_module"]) # Set up the target in pexpect. if cfg["build"]["interactive"] >= 3: print ( "\nRunning the conn module (" + shutit.shutit_main_dir + "/shutit_setup.py)" + shutit_util.colour("32", "\n\n[Hit return to continue]\n") ) shutit_util.util_raw_input(shutit=shutit) conn_module.get_config(shutit) conn_module.build(shutit)
def do_build(shutit): """Runs build phase, building any modules that we've determined need building. """ cfg = shutit.cfg shutit.log("PHASE: build, repository work", code="32") shutit.log(shutit_util.print_config(cfg)) if cfg["build"]["interactive"] >= 3: print ( "\nNow building any modules that need building" + shutit_util.colour("32", "\n\n[Hit return to continue]\n") ) shutit_util.util_raw_input(shutit=shutit) module_id_list = module_ids(shutit) if cfg["build"]["deps_only"]: module_id_list_build_only = filter(lambda x: cfg[x]["shutit.core.module.build"], module_id_list) for module_id in module_id_list: module = shutit.shutit_map[module_id] shutit.log("considering whether to build: " + module.module_id, code="32") if cfg[module.module_id]["shutit.core.module.build"]: if cfg["build"]["delivery"] not in module.ok_delivery_methods: shutit.fail( "Module: " + module.module_id + " can only be built with one of these --delivery methods: " + str(module.ok_delivery_methods) + "\nSee shutit build -h for more info, or try adding: --delivery <method> to your shutit invocation" ) if is_installed(shutit, module): cfg["build"]["report"] = ( cfg["build"]["report"] + "\nBuilt already: " + module.module_id + " with run order: " + str(module.run_order) ) else: # We move to the module directory to perform the build, returning immediately afterwards. if cfg["build"]["deps_only"] and module_id == module_id_list_build_only[-1]: # If this is the last module, and we are only building deps, stop here. cfg["build"]["report"] = ( cfg["build"]["report"] + "\nSkipping: " + module.module_id + " with run order: " + str(module.run_order) + "\n\tas this is the final module and we are building dependencies only" ) else: revert_dir = os.getcwd() cfg["environment"][cfg["build"]["current_environment_id"]]["module_root_dir"] = os.path.dirname( module.__module_file ) shutit.chdir(cfg["environment"][cfg["build"]["current_environment_id"]]["module_root_dir"]) shutit.login(prompt_prefix=module_id, command="bash") build_module(shutit, module) shutit.logout() shutit.chdir(revert_dir) if is_installed(shutit, module): shutit.log("Starting module") if not module.start(shutit): shutit.fail(module.module_id + " failed on start", child=shutit.pexpect_children["target_child"])
def init_shutit_map(shutit): """Initializes the module map of shutit based on the modules we have gathered. Checks we have core modules Checks for duplicate module details. Sets up common config. Sets up map of modules. """ cfg = shutit.cfg modules = shutit.shutit_modules # Have we got anything to process outside of special modules? if len([mod for mod in modules if mod.run_order > 0]) < 1: shutit.log(modules) path = ":".join(cfg["host"]["shutit_module_path"]) shutit.log( "\nIf you are new to ShutIt, see:\n\n\thttp://ianmiell.github.io/shutit/\n\nor try running\n\n\tshutit skeleton\n\n", code=31, prefix=False, force_stdout=True, ) if path == "": shutit.fail( "No ShutIt modules aside from core ones found and no ShutIt" + " module path given. " + "\nDid you set --shutit_module_path/-m wrongly?\n" ) elif path == ".": shutit.fail( "No modules aside from core ones found and no ShutIt" + " module path given apart from default (.).\n\n- Did you" + " set --shutit_module_path/-m?\n- Is there a STOP* file" + " in your . dir?\n" ) else: shutit.fail( "No modules aside from core ones found and no ShutIt " + "modules in path:\n\n" + path + "\n\nor their subfolders. Check your " + "--shutit_module_path/-m setting and check that there are " + "ShutIt modules below without STOP* files in any relevant " + "directories.\n" ) shutit.log("PHASE: base setup", code="32") if cfg["build"]["interactive"] >= 3: shutit.log( "\nChecking to see whether there are duplicate module ids " + "or run orders in the visible modules.", force_stdout=True, ) shutit.log("\nModules I see are:\n", force_stdout=True) for module in modules: shutit.log(module.module_id, force_stdout=True, code="32") shutit.log("\n", force_stdout=True) run_orders = {} has_core_module = False for module in modules: assert isinstance(module, ShutItModule) if module.module_id in shutit.shutit_map: shutit.fail( "Duplicated module id: " + module.module_id + "\n\nYou may want to check your --shutit_module_path setting" ) if module.run_order in run_orders: shutit.fail( "Duplicate run order: " + str(module.run_order) + " for " + module.module_id + " and " + run_orders[module.run_order].module_id + "\n\nYou may want to check your --shutit_module_path setting" ) if module.run_order == 0: has_core_module = True shutit.shutit_map[module.module_id] = run_orders[module.run_order] = module if not has_core_module: shutit.fail("No module with run_order=0 specified! This is required.") if cfg["build"]["interactive"] >= 3: print (shutit_util.colour("32", "Module id and run order checks OK" + "\n\n[Hit return to continue]\n")) shutit_util.util_raw_input(shutit=shutit)
def build(self, shutit): """Sets up the target ready for building. """ # Uncomment for testing for "failure" cases. #sys.exit(1) while not self._check_docker(shutit): pass cfg = shutit.cfg docker = cfg['host']['docker_executable'].split(' ') # Always-required options if not os.path.exists(cfg['build']['shutit_state_dir'] + '/cidfiles'): os.makedirs(cfg['build']['shutit_state_dir'] + '/cidfiles') cfg['build']['cidfile'] = cfg['build']['shutit_state_dir'] + '/cidfiles/' + cfg['host']['username'] +\ '_cidfile_' + cfg['build']['build_id'] cidfile_arg = '--cidfile=' + cfg['build']['cidfile'] # Singly-specified options privileged_arg = '' lxc_conf_arg = '' name_arg = '' hostname_arg = '' volume_arg = '' rm_arg = '' net_arg = '' mount_docker_arg = '' shell_arg = '/bin/bash' if cfg['build']['privileged']: privileged_arg = '--privileged=true' if cfg['build']['lxc_conf'] != '': lxc_conf_arg = '--lxc-conf=' + cfg['build']['lxc_conf'] if cfg['target']['name'] != '': name_arg = '--name=' + cfg['target']['name'] if cfg['target']['hostname'] != '': hostname_arg = '-h=' + cfg['target']['hostname'] if cfg['host']['artifacts_dir'] != '': volume_arg = '-v=' + cfg['host']['artifacts_dir'] + ':/artifacts' if cfg['build']['net'] != '': net_arg = '--net="' + cfg['build']['net'] + '"' if cfg['build']['mount_docker']: mount_docker_arg = '-v=/var/run/docker.sock:/var/run/docker.sock' # Incompatible with do_repository_work if cfg['target']['rm']: rm_arg = '--rm=true' if cfg['build']['base_image'] in ('alpine'): shell_arg = '/bin/ash' # Multiply-specified options port_args = [] dns_args = [] ports_list = cfg['target']['ports'].strip().split() dns_list = cfg['host']['dns'].strip().split() for portmap in ports_list: port_args.append('-p=' + portmap) for dns in dns_list: dns_args.append('--dns=' + dns) docker_command = docker + [ arg for arg in [ 'run', cidfile_arg, privileged_arg, lxc_conf_arg, name_arg, hostname_arg, volume_arg, rm_arg, net_arg, mount_docker_arg, ] + port_args + dns_args + [ '-t', '-i', cfg['target']['docker_image'], shell_arg ] if arg != '' ] if cfg['build']['interactive'] >= 3: print('\n\nAbout to start container. ' + 'Ports mapped will be: ' + ', '.join(port_args) + '\n\n[host]\nports:<value>\n\nconfig, building on the ' + 'configurable base image passed in in:\n\n --image <image>\n' + '\nor config:\n\n [target]\n docker_image:<image>)\n\n' + 'Base image in this case is:\n\n ' + cfg['target']['docker_image'] + '\n\n' + shutit_util.colour('32', '\n[Hit return to continue]')) shutit_util.util_raw_input(shutit=shutit) cfg['build']['docker_command'] = ' '.join(docker_command) shutit.log('\n\nCommand being run is:\n\n' + cfg['build']['docker_command'], force_stdout=True, prefix=False) shutit.log('\n\nThis may download the image, please be patient\n\n', force_stdout=True, prefix=False) target_child = pexpect.spawn(docker_command[0], docker_command[1:]) expect = ['assword', cfg['expect_prompts']['base_prompt'].strip(), \ 'Waiting', 'ulling', 'endpoint', 'Download'] res = target_child.expect(expect, 9999) while True: shutit.log(target_child.before + target_child.after, prefix=False, force_stdout=True) if res == 0: shutit.log('...') res = shutit.send(cfg['host']['password'], \ child=target_child, expect=expect, timeout=9999, \ check_exit=False, fail_on_empty_before=False) elif res == 1: shutit.log('Prompt found, breaking out') break else: res = target_child.expect(expect, 9999) continue # Get the cid while True: try: cid = open(cfg['build']['cidfile']).read() break except: sleep(1) if cid == '' or re.match('^[a-z0-9]+$', cid) == None: shutit.fail('Could not get container_id - quitting. ' + 'Check whether ' + 'other containers may be clashing on port allocation or name.' + '\nYou might want to try running: sudo docker kill ' + cfg['target']['name'] + '; sudo docker rm ' + cfg['target']['name'] + '\nto resolve a name clash or: ' + cfg['host']['docker_executable'] + ' ps -a | grep ' + cfg['target']['ports'] + ' | awk \'{print $1}\' | ' + 'xargs ' + cfg['host']['docker_executable'] + ' kill\nto + ' 'resolve a port clash\n') shutit.log('cid: ' + cid) cfg['target']['container_id'] = cid self._setup_prompts(shutit, target_child) self._add_begin_build_info(shutit, docker_command) return True
def start_container(self, shutit, shutit_session_name, loglevel=logging.DEBUG): cfg = shutit.cfg docker = cfg['host']['docker_executable'].split(' ') # Always-required options if not os.path.exists(cfg['build']['shutit_state_dir'] + '/cidfiles'): os.makedirs(cfg['build']['shutit_state_dir'] + '/cidfiles') cfg['build']['cidfile'] = cfg['build']['shutit_state_dir'] + '/cidfiles/' + cfg['host']['username'] + '_cidfile_' + cfg['build']['build_id'] cidfile_arg = '--cidfile=' + cfg['build']['cidfile'] # Singly-specified options privileged_arg = '' name_arg = '' hostname_arg = '' rm_arg = '' net_arg = '' mount_docker_arg = '' shell_arg = '/bin/bash' if cfg['build']['privileged']: privileged_arg = '--privileged=true' if cfg['target']['name'] != '': name_arg = '--name=' + cfg['target']['name'] if cfg['target']['hostname'] != '': hostname_arg = '-h=' + cfg['target']['hostname'] if cfg['build']['net'] != '': net_arg = '--net="' + cfg['build']['net'] + '"' if cfg['build']['mount_docker']: mount_docker_arg = '-v=/var/run/docker.sock:/var/run/docker.sock' # Incompatible with do_repository_work if cfg['target']['rm']: rm_arg = '--rm=true' if cfg['build']['base_image'] in ('alpine','busybox'): shell_arg = '/bin/ash' # Multiply-specified options port_args = [] dns_args = [] volume_args = [] volumes_from_args = [] volumes_list = cfg['target']['volumes'].strip().split() volumes_from_list = cfg['target']['volumes_from'].strip().split() ports_list = cfg['target']['ports'].strip().split() dns_list = cfg['host']['dns'].strip().split() for portmap in ports_list: port_args.append('-p=' + portmap) for dns in dns_list: dns_args.append('--dns=' + dns) for volume in volumes_list: volume_args.append('-v=' + volume) for volumes_from in volumes_from_list: volumes_from_args.append('--volumes-from=' + volumes_from) docker_command = docker + [ arg for arg in [ 'run', cidfile_arg, privileged_arg, name_arg, hostname_arg, rm_arg, net_arg, mount_docker_arg, ] + volume_args + volumes_from_args + port_args + dns_args + [ '-t', '-i', cfg['target']['docker_image'], shell_arg ] if arg != '' ] if cfg['build']['interactive'] >= 3: print('\n\nAbout to start container. Ports mapped will be: ' + ', '.join(port_args) + '\n\n[host]\nports:<value>\n\nconfig, building on the configurable base image passed in in:\n\n --image <image>\n\nor config:\n\n [target]\n docker_image:<image>)\n\nBase image in this case is:\n\n ' + cfg['target']['docker_image'] + '\n\n' + shutit_util.colour('32', '\n[Hit return to continue]')) shutit_util.util_raw_input(shutit=shutit) cfg['build']['docker_command'] = ' '.join(docker_command) shutit.log('Command being run is: ' + cfg['build']['docker_command'],level=logging.DEBUG) shutit.log('Downloading image, please be patient',level=logging.INFO) shutit_pexpect_session = shutit_pexpect.ShutItPexpectSession(shutit_session_name, docker_command[0], docker_command[1:]) target_child = shutit_pexpect_session.pexpect_child expect = ['assword', cfg['expect_prompts']['base_prompt'].strip(), 'Waiting', 'ulling', 'endpoint', 'Download'] res = shutit_pexpect_session.expect(expect, timeout=9999) while True: shutit.log(target_child.before + target_child.after,level=loglevel) if res == 0: res = shutit.send(cfg['host']['password'], child=target_child, expect=expect, timeout=9999, check_exit=False, fail_on_empty_before=False, echo=False, loglevel=loglevel) elif res == 1: shutit.log('Prompt found, breaking out',level=logging.DEBUG) break else: res = shutit_pexpect_session.expect(expect, timeout=9999) continue # Get the cid while True: try: cid = open(cfg['build']['cidfile']).read() break except Exception: time.sleep(1) if cid == '' or re.match('^[a-z0-9]+$', cid) == None: shutit.fail('Could not get container_id - quitting. Check whether other containers may be clashing on port allocation or name.\nYou might want to try running: sudo docker kill ' + cfg['target']['name'] + '; sudo docker rm ' + cfg['target']['name'] + '\nto resolve a name clash or: ' + cfg['host']['docker_executable'] + ' ps -a | grep ' + cfg['target']['ports'] + " | awk '{print $1}' | " + 'xargs ' + cfg['host']['docker_executable'] + ' kill\nto ' + 'resolve a port clash\n') shutit.log('cid: ' + cid,level=logging.DEBUG) cfg['target']['container_id'] = cid return target_child
def do_build(shutit): """Runs build phase, building any modules that we've determined need building. """ cfg = shutit.cfg shutit.log('PHASE: build, repository work', code='32') shutit.log(shutit_util.print_config(cfg)) if cfg['build']['interactive'] >= 3: print('\nNow building any modules that need building' + shutit_util.colour('32', '\n\n[Hit return to continue]\n')) shutit_util.util_raw_input(shutit=shutit) module_id_list = module_ids(shutit) if cfg['build']['deps_only']: module_id_list_build_only = filter( lambda x: cfg[x]['shutit.core.module.build'], module_id_list) for module_id in module_id_list: module = shutit.shutit_map[module_id] shutit.log('considering whether to build: ' + module.module_id, code='32') if cfg[module.module_id]['shutit.core.module.build']: if cfg['build']['delivery'] not in module.ok_delivery_methods: shutit.fail( 'Module: ' + module.module_id + ' can only be built with one of these --delivery methods: ' + str(module.ok_delivery_methods) + '\nSee shutit build -h for more info, or try adding: --delivery <method> to your shutit invocation' ) if is_installed(shutit, module): cfg['build']['report'] = (cfg['build']['report'] + '\nBuilt already: ' + module.module_id + ' with run order: ' + str(module.run_order)) else: # We move to the module directory to perform the build, returning immediately afterwards. if cfg['build'][ 'deps_only'] and module_id == module_id_list_build_only[ -1]: # If this is the last module, and we are only building deps, stop here. cfg['build']['report'] = ( cfg['build']['report'] + '\nSkipping: ' + module.module_id + ' with run order: ' + str(module.run_order) + '\n\tas this is the final module and we are building dependencies only' ) else: revert_dir = os.getcwd() cfg['environment'][cfg['build']['current_environment_id']][ 'module_root_dir'] = os.path.dirname( module.__module_file) shutit.chdir(cfg['environment'][cfg['build'][ 'current_environment_id']]['module_root_dir']) shutit.login(prompt_prefix=module_id, command='bash') build_module(shutit, module) shutit.logout() shutit.chdir(revert_dir) if is_installed(shutit, module): shutit.log('Starting module') if not module.start(shutit): shutit.fail(module.module_id + ' failed on start', child=shutit.pexpect_children['target_child'])
def init_shutit_map(shutit): """Initializes the module map of shutit based on the modules we have gathered. Checks we have core modules Checks for duplicate module details. Sets up common config. Sets up map of modules. """ cfg = shutit.cfg modules = shutit.shutit_modules # Have we got anything to process outside of special modules? if len([mod for mod in modules if mod.run_order > 0]) < 1: shutit.log(modules) path = ':'.join(cfg['host']['shutit_module_path']) shutit.log( '\nIf you are new to ShutIt, see:\n\n\thttp://ianmiell.github.io/shutit/\n\nor try running\n\n\tshutit skeleton\n\n', code=31, prefix=False, force_stdout=True) if path == '': shutit.fail( 'No ShutIt modules aside from core ones found and no ShutIt' + ' module path given. ' + '\nDid you set --shutit_module_path/-m wrongly?\n') elif path == '.': shutit.fail( 'No modules aside from core ones found and no ShutIt' + ' module path given apart from default (.).\n\n- Did you' + ' set --shutit_module_path/-m?\n- Is there a STOP* file' + ' in your . dir?\n') else: shutit.fail( 'No modules aside from core ones found and no ShutIt ' + 'modules in path:\n\n' + path + '\n\nor their subfolders. Check your ' + '--shutit_module_path/-m setting and check that there are ' + 'ShutIt modules below without STOP* files in any relevant ' + 'directories.\n') shutit.log('PHASE: base setup', code='32') if cfg['build']['interactive'] >= 3: shutit.log( '\nChecking to see whether there are duplicate module ids ' + 'or run orders in the visible modules.', force_stdout=True) shutit.log('\nModules I see are:\n', force_stdout=True) for module in modules: shutit.log(module.module_id, force_stdout=True, code='32') shutit.log('\n', force_stdout=True) run_orders = {} has_core_module = False for module in modules: assert isinstance(module, ShutItModule) if module.module_id in shutit.shutit_map: shutit.fail( 'Duplicated module id: ' + module.module_id + '\n\nYou may want to check your --shutit_module_path setting') if module.run_order in run_orders: shutit.fail( 'Duplicate run order: ' + str(module.run_order) + ' for ' + module.module_id + ' and ' + run_orders[module.run_order].module_id + '\n\nYou may want to check your --shutit_module_path setting') if module.run_order == 0: has_core_module = True shutit.shutit_map[module.module_id] = run_orders[ module.run_order] = module if not has_core_module: shutit.fail('No module with run_order=0 specified! This is required.') if cfg['build']['interactive'] >= 3: print( shutit_util.colour( '32', 'Module id and run order checks OK' + '\n\n[Hit return to continue]\n')) shutit_util.util_raw_input(shutit=shutit)