Run a playbook.

        :param playbook: An Ansible playbook to run.
        :param ansibleArgs: Arguments to pass to the playbook.
        :param wait: Wait for the play to finish if true.
        :param tags: Control tags for the play.
352081
def callPlaybook(self, playbook, ansibleArgs, wait=True, tags=["all"]):
        
        playbook = os.path.join(self.playbooks, playbook)  # Path to playbook being executed
        verbosity = "-vvvvv" if logger.isEnabledFor(logging.DEBUG) else "-v"
        command = ["ansible-playbook", verbosity, "--tags", ",".join(tags), "--extra-vars"]
        command.append(" ".join(["=".join(i) for i in ansibleArgs.items()]))  # Arguments being passed to playbook
        command.append(playbook)

        logger.debug("Executing Ansible call `%s`", " ".join(command))
        p = subprocess.Popen(command)
        if wait:
            p.communicate()
            if p.returncode != 0:
                # FIXME: parse error codes
                raise RuntimeError("Ansible reported an error when executing playbook %s" % playbook)
1190697
func RunPlaybooks(args *def.DeployArgs, playbooks []string, logger *logging.Logger) (int, error) {
	// if bin and abi paths are default cli settings then use the
	//   stated defaults of do.Path plus bin|abi
	if args.Path == "" {
		var err error
		args.Path, err = os.Getwd()
		if err != nil {
			panic(fmt.Sprintf("failed to get current directory %v", err))
		}
	}

	// useful for debugging
	logger.InfoMsg("Using chain", "Chain", args.Chain, "Signer", args.KeysService)

	workQ := make(chan playbookWork, 100)
	resultQ := make(chan playbookResult, 100)

	for i := 1; i <= args.Jobs; i++ {
		go worker(workQ, resultQ, args, logger)
	}

	for i, playbook := range playbooks {
		workQ <- playbookWork{jobNo: i, playbook: playbook}
	}
	close(workQ)

	// work queued, now read the results
	results := make([]*playbookResult, len(playbooks))
	printed := 0
	failures := 0
	successes := 0

	for range playbooks {
		jobResult := <-resultQ
		results[jobResult.jobNo] = &jobResult
		for results[printed] != nil {
			res := results[printed]
			os.Stderr.Write(res.log.Bytes())
			if res.err != nil {
				fmt.Fprintf(os.Stderr, "ERROR: %v", res.err)
			}
			res.log.Truncate(0)
			if jobResult.err != nil {
				failures++
			} else {
				successes++
			}
			printed++
			if printed >= len(playbooks) {
				break
			}
		}
	}
	close(resultQ)

	if successes > 0 {
		logger.InfoMsg("JOBS THAT SUCCEEEDED", "count", successes)
		for i, playbook := range playbooks {
			res := results[i]
			if res.err != nil {
				continue
			}
			logger.InfoMsg("Playbook result",
				"jobNo", i,
				"file", playbook,
				"time", res.duration.String())
		}
	}

	if failures > 0 {
		logger.InfoMsg("JOBS THAT FAILED", "count", failures)
		for i, playbook := range playbooks {
			res := results[i]
			if res.err == nil {
				continue
			}
			logger.InfoMsg("Playbook result",
				"jobNo", i,
				"file", playbook,
				"error", res.err,
				"time", res.duration.String())
		}
	}

	return failures, nil
}
951743
def run(self):
        
        elapsed = 0
        run_time = self.config['run_time']
        start_time = time.time()
        t = time.time
        self.turrets_manager.start(self.transaction_context)
        self.started = True

        while elapsed <= run_time:
            try:
                self._run_loop_action()
                self._print_status(elapsed)
                elapsed = t() - start_time
            except (Exception, KeyboardInterrupt):
                print("\nStopping test, sending stop command to turrets")
                self.turrets_manager.stop()
                self.stats_handler.write_remaining()
                traceback.print_exc()
                break

        self.turrets_manager.stop()
        print("\n\nProcessing all remaining messages... This could take time depending on message volume")
        t = time.time()
        self.result_collector.unbind(self.result_collector.LAST_ENDPOINT)
        self._clean_queue()
        print("took %s" % (time.time() - t))
374036
def post(self):
        """"""
        run_payload = utils.uni_to_str(json.loads(request.get_data()))
        run_payload['id'] = str(uuid.uuid4())
        LOG.info('Triggering new ansible run %s', run_payload['id'])
        run = self.manager.create_run(run_payload)
        return run_model.format_response(run), http_client.CREATED
976448
def _run_automation(self, conf):
        
        self._fill_form(self._find_form(conf))
        self._run_scenario(conf)
        self._delay(conf)
344102
def run(self, conn, tmp, module_name, module_args, inject):
        '''  '''

        if not self.runner.is_playbook:
            raise errors.AnsibleError("in current versions of ansible, templates are only usable in playbooks")

        # load up options
        options  = utils.parse_kv(module_args)
        source   = options.get('src', None)
        dest     = options.get('dest', None)

        if (source is None and 'first_available_file' not in inject) or dest is None:
            result = dict(failed=True, msg="src and dest are required")
            return ReturnData(conn=conn, comm_ok=False, result=result)

        # if we have first_available_file in our vars
        # look up the files and use the first one we find as src
        if 'first_available_file' in inject:
            found = False
            for fn in self.runner.module_vars.get('first_available_file'):
                fnt = utils.template(self.runner.basedir, fn, inject)
                fnd = utils.path_dwim(self.runner.basedir, fnt)
                if os.path.exists(fnd):
                    source = fnt
                    found = True
                    break
            if not found:
                result = dict(failed=True, msg="could not find src in first_available_file list")
                return ReturnData(conn=conn, comm_ok=False, result=result)
        else:
            source = utils.template(self.runner.basedir, source, inject)

        if dest.endswith("/"):
            base = os.path.basename(source)
            dest = os.path.join(dest, base)

        # template the source data locally & transfer
        try:
            resultant = utils.template_from_file(self.runner.basedir, source, inject)
        except Exception, e:
            result = dict(failed=True, msg=str(e))
            return ReturnData(conn=conn, comm_ok=False, result=result)

        xfered = self.runner._transfer_str(conn, tmp, 'source', resultant)
        # fix file permissions when the copy is done as a different user
        if self.runner.sudo and self.runner.sudo_user != 'root':
            self.runner._low_level_exec_command(conn, "chmod a+r %s" % xfered, 
                tmp)

        # run the copy module
        module_args = "%s src=%s dest=%s" % (module_args, xfered, dest)
        return self.runner._execute_module(conn, tmp, 'copy', module_args, inject=inject)
1112604
def execute(self, payload, *args, flavour: ModuleType, **kwargs):
        
        if args or kwargs:
            payload = functools.partial(payload, *args, **kwargs)
        return self._meta_runner.run_payload(payload, flavour=flavour)
15054
def run
      options.staged = options.staged.nil? ? true : options.staged

      if options.skip_pre
        puts 'Skipping PreRun Executables'
      else
        run_externals('pre-run-execute')
      end

      if script && !(options.ignore_script || GitHooks.ignore_script)
        command = "#{script} #{Pathname.new($0)} #{Shellwords.join(ARGV)};"
        puts "Kernel#exec(#{command.inspect})" if GitHooks.verbose
        exec(command)
      elsif hook_path
        load_tests && start
      else
        puts %q"I can't figure out what to run! Specify either path or script to give me a hint..."
      end

      if options.skip_post
        puts 'Skipping PostRun Executables'
      else
        run_externals('post-run-execute')
      end
    rescue SystemStackError => e
      puts "#{e.class.name}: #{e.message}\n\t#{e.backtrace.join("\n\t")}"
    rescue GitHooks::Error::NotAGitRepo => e
      puts "Unable to find a valid git repo in #{repository}."
      puts 'Please specify path to repository via --repo <path>' if GitHooks::SCRIPT_NAME == 'githooks'
      raise e
    end
27698
def runlist_list(**kwargs):
    
    ctx = Context(**kwargs)
    ctx.execute_action('runlist:list', **{
        'storage': ctx.repo.create_secure_service('storage'),
    })
399410
public void run(String[] args) {
    LOG.info("Starting GA4GHPicardRunner");
    try {
      parseCmdLine(args);
      buildPicardCommand();
      startProcess();
      pumpInputData();
      waitForProcessEnd();
    } catch (Exception e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
    }
  }
811124
def run(*args)
      session, run_in_tx = session_and_run_in_tx_from_args(args)

      fail ArgumentError, 'Expected a block to run in Transaction.run' unless block_given?

      return yield(nil) unless run_in_tx

      tx = Neo4j::Transaction.new(session)
      yield tx
    rescue Exception => e # rubocop:disable Lint/RescueException
      # print_exception_cause(e)

      tx.mark_failed unless tx.nil?
      raise e
    ensure
      tx.close unless tx.nil?
    end
1248754
def run(self, args):
        
        super(ShellCommand, self).run(args)

        # load the application
        app = self.load_app()

        # prepare the locals
        locs = dict(__name__='pecan-admin')
        locs['wsgiapp'] = app
        locs['app'] = TestApp(app)

        model = self.load_model(app.config)
        if model:
            locs['model'] = model

        # insert the pecan locals
        from pecan import abort, conf, redirect, request, response
        locs['abort'] = abort
        locs['conf'] = conf
        locs['redirect'] = redirect
        locs['request'] = request
        locs['response'] = response

        # prepare the banner
        banner = '  The following objects are available:\n'
        banner += '  %-10s - This project\'s WSGI App instance\n' % 'wsgiapp'
        banner += '  %-10s - The current configuration\n' % 'conf'
        banner += '  %-10s - webtest.TestApp wrapped around wsgiapp\n' % 'app'
        if model:
            model_name = getattr(
                model,
                '__module__',
                getattr(model, '__name__', 'model')
            )
            banner += '  %-10s - Models from %s\n' % ('model', model_name)

        self.invoke_shell(locs, banner)
141785
public void run(){
		System.out.println("Starting tagging service!");
		try {
			this.socket = new ServerSocket(this.port);
		}
		catch (IOException ioe){
			System.out.println(ioe);
			System.exit(1);
		}
		
		init();
		System.out.println("Tagging service is started successfully");
		while (true){
			Socket incoming = null;
			try{
				incoming = this.socket.accept();
				Session w = null;
				synchronized (pool) {
					if (pool.isEmpty()){
						w = new Session(vnTextPro);
						w.setSocket(incoming); //additional sessions
						w.start();						
					} else{
						w = pool.elementAt(0);
						pool.removeElementAt(0);						
						w.setSocket(incoming);
					}
				}
			}
			catch (IOException e){
				System.out.println(e);
				e.printStackTrace();
			}
		}
	}
515725
def run(self, filename, wait_output=True):
        
        self._pyboard.enter_raw_repl()
        out = None
        if wait_output:
            # Run the file and wait for output to return.
            out = self._pyboard.execfile(filename)
        else:
            # Read the file and run it using lower level pyboard functions that
            # won't wait for it to finish or return output.
            with open(filename, "rb") as infile:
                self._pyboard.exec_raw_no_follow(infile.read())
        self._pyboard.exit_raw_repl()
        return out
307679
def do_run(self,args):
        """"""
        parser = CommandArgumentParser("run")
        parser.add_argument('-R','--replace-key',dest='replaceKey',default=False,action='store_true',help="Replace the host's key. This is useful when AWS recycles an IP address you've seen before.")
        parser.add_argument('-Y','--keyscan',dest='keyscan',default=False,action='store_true',help="Perform a keyscan to avoid having to say 'yes' for a new host. Implies -R.")
        parser.add_argument('-ii','--ignore-host-key',dest='ignore-host-key',default=False,action='store_true',help='Ignore host key')
        parser.add_argument('-ne','--no-echo',dest='no-echo',default=False,action='store_true',help='Do not echo command')
        parser.add_argument(dest='command',nargs='+',help="Command to run on all hosts.") # consider adding a filter option later
        parser.add_argument('-v',dest='verbosity',default=0,action=VAction,nargs='?',help='Verbosity. The more instances, the more verbose');        
        parser.add_argument('-j',dest='jobs',type=int,default=1,help='Number of hosts to contact in parallel');
        parser.add_argument('-s',dest='skip',type=int,default=0,help='Skip this many hosts');
        parser.add_argument('-m',dest='macro',default=False,action='store_true',help='{command} is a series of macros to execute, not the actual command to run on the host');
        args = vars(parser.parse_args(args))

        replaceKey = args['replaceKey']
        keyscan = args['keyscan']
        verbosity = args['verbosity']
        jobs = args['jobs']
        skip = args['skip']
        ignoreHostKey = args['ignore-host-key']
        noEcho = args['no-echo']

        instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances']
        instances = instances[skip:]
        # if replaceKey or keyscan:
        #     for instance in instances:
        #         stdplus.resetKnownHost(instance)

        if args['macro']:
            if len(args['command']) > 1:
                print("Only one macro may be specified with the -m switch.")
                return
            else:
                macro = args['command'][0]
                print("Macro:{}".format(macro))
                command = Config.config['ssh-macros'][macro]
        else:
            command = ' '.join(args['command'])
            
        Parallel(n_jobs=jobs)(
            delayed(ssh)(instance['InstanceId'],0,[],replaceKey,keyscan,False,verbosity,command,ignoreHostKey=ignoreHostKey,echoCommand=not noEcho,name="{}:{}: ".format(instance['index'],instance['InstanceId'])) for instance in instances
        )
132462
async def run(self, command, timeout=None):
        
        action = client.ActionFacade.from_connection(self.connection)

        log.debug(
            'Running `%s` on %s', command, self.name)

        if timeout:
            # Convert seconds to nanoseconds
            timeout = int(timeout * 1000000000)

        res = await action.Run(
            [],
            command,
            [],
            timeout,
            [self.name],
        )
        return await self.model.wait_for_action(res.results[0].action.tag)
1138494
def __git_tag_push():
        
        command = ['git', 'push', 'origin', '--tags']
        Shell.msg('Pushing tags...')

        if APISettings.DEBUG:
            Git.__debug(command, True)

        if not call(command):
            return True
        return False