Internal method
        workaround for systemd-run without --wait option
        see  _run_systemdrun_decide method

        :param machine:
        :param unit:
        :return:
333105
def _systemctl_wait_until_finish(self, machine, unit):
        
        while True:
            metadata = convert_kv_to_dict(
                run_cmd(
                    ["systemctl", "--no-pager", "show", "-M", machine, unit],
                    return_output=True))
            if not metadata["SubState"] in ["exited", "failed"]:
                time.sleep(0.1)
            else:
                break
        run_cmd(["systemctl", "--no-pager", "-M", machine, "stop", unit], ignore_status=True)
        return metadata["ExecMainStatus"]
1174954
def rack_options # :nodoc:
      symbolized_options(:port, :host, :server, :daemonize, :pid).tap do |rack_options|
        rack_options[:environment] = environment
        rack_options[:Port] = rack_options.delete :port
        rack_options[:Host] = rack_options.delete :host
        rack_options[:app] = machined
      end
    end
873893
@Override
	public boolean isMachineRunning( TargetHandlerParameters parameters, String machineId )
	throws TargetException {

		NovaApi novaApi = novaApi( parameters.getTargetProperties());
		String zoneName = findZoneName( novaApi, parameters.getTargetProperties());
		Server server = novaApi.getServerApiForZone( zoneName ).get( machineId );

		boolean running = false;
		if( server != null )
			running = server.getStatus() == Status.ACTIVE || server.getStatus() == Status.REBOOT;

		return running;
	}
563547
def wait_for_state_machine_finished(state_machine):
    
    global _user_abort

    from rafcon.core.states.execution_state import ExecutionState
    if not isinstance(state_machine.root_state, ExecutionState):
        while len(state_machine.execution_histories[0]) < 1:
            time.sleep(0.1)
    else:
        time.sleep(0.5)

    while state_machine.root_state.state_execution_status is not StateExecutionStatus.INACTIVE:
        try:
            state_machine.root_state.concurrency_queue.get(timeout=1)
            # this check triggers if the state machine could not be stopped in the signal handler
            if _user_abort:
                return
        except Empty:
            pass
        # no logger output here to make it easier for the parser
        logger.verbose("RAFCON live signal")
1191635
def _system3(cmd, verbose=False):
    
    
    # Init flag
    interrupted = False
    
    # Create progress
    if verbose > 0:
        progress = Progress()
    
    stdout = []
    def poll_process(p):
        while not interrupted:
            msg = p.stdout.readline().decode()
            if msg:
                stdout.append(msg)
                if 'error' in msg.lower():
                    print(msg.rstrip())
                    if verbose == 1:
                        progress.reset()
                elif verbose > 1:
                    print(msg.rstrip())
                elif verbose == 1:
                    progress.update(msg)
            else:
                break
            time.sleep(0.01)
        #print("thread exit")
    
    # Start process that runs the command
    p = subprocess.Popen(cmd, shell=True, 
                         stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    
    # Keep reading stdout from it
    # thread.start_new_thread(poll_process, (p,))  Python 2.x
    my_thread = threading.Thread(target=poll_process, args=(p,))
    my_thread.setDaemon(True)
    my_thread.start()
    
    # Wait here
    try:
        while p.poll() is None:
            time.sleep(0.01)
    except KeyboardInterrupt:
        # Set flag
        interrupted = True
        # Kill subprocess
        pid = p.pid
        if hasattr(os,'kill'):
            import signal
            os.kill(pid, signal.SIGKILL)
        elif sys.platform.startswith('win'):
            kernel32 = ctypes.windll.kernel32
            handle = kernel32.OpenProcess(1, 0, pid)
            kernel32.TerminateProcess(handle, 0)
            #os.system("TASKKILL /PID " + str(pid) + " /F")
    
    # All good?
    if interrupted:
        raise RuntimeError('Registration process interrupted by the user.')
    if p.returncode:
        stdout.append(p.stdout.read().decode())
        print(''.join(stdout))
        raise RuntimeError('An error occured during the registration.')
718717
def cli(env, identifier, immediate, comment, reason):
    """"""

    mgr = SoftLayer.HardwareManager(env.client)
    hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')

    if not (env.skip_confirmations or formatting.no_going_back(hw_id)):
        raise exceptions.CLIAbort('Aborted')

    mgr.cancel_hardware(hw_id, reason, comment, immediate)
119244
def run_systemdrun(
            self, command, internal_background=False, return_full_dict=False,
            **kwargs):
        
        internalkw = deepcopy(kwargs) or {}
        original_ignore_st = internalkw.get("ignore_status", False)
        original_return_st = internalkw.get("return_output", False)
        internalkw["ignore_status"] = True
        internalkw["return_output"] = False
        unit_name = constants.CONU_ARTIFACT_TAG + "unit_" + random_str()
        opts = ["-M", self.name, "--unit", unit_name]
        lpath = "/var/tmp/{}".format(unit_name)
        comout = {}
        if self._run_systemdrun_decide():
            add_wait_var = "--wait"
        else:
            # keep service exist after it finish, to be able to read exit code
            add_wait_var = "-r"
        if internal_background:
            add_wait_var = ""
        if add_wait_var:
            opts.append(add_wait_var)
        # TODO: behave move similar to run_cmd function, unable to work with clean subprocess objects because systemd-run
        # does not support return stderr, stdout, and return code directly
        # find way how to do this in better way, machinectl shell is not possible
        # https://github.com/systemd/systemd/issues/5879
        # https://github.com/systemd/systemd/issues/5878
        bashworkaround = [
            "/bin/bash",
            "-c",
            "({comm})>{path}.stdout 2>{path}.stderr".format(
                comm=" ".join(command),
                path=lpath)]
        whole_cmd = ["systemd-run"] + opts + bashworkaround
        comout['command'] = command
        comout['return_code'] = run_cmd(whole_cmd, **internalkw) or 0
        if not internal_background:
            if not self._run_systemdrun_decide():
                comout['return_code'] = self._systemctl_wait_until_finish(
                    self.name, unit_name)
            if self.is_running():
                self.copy_from(
                    "{pin}.stdout".format(
                        pin=lpath), "{pin}.stdout".format(
                        pin=lpath))
                with open("{pin}.stdout".format(pin=lpath)) as f:
                    comout['stdout'] = f.read()
                self.copy_from(
                    "{pin}.stderr".format(
                        pin=lpath), "{pin}.stderr".format(
                        pin=lpath))
                with open("{pin}.stderr".format(pin=lpath)) as f:
                    comout['stderr'] = f.read()
            logger.debug(comout)
        if not original_ignore_st and comout['return_code'] != 0:
            raise subprocess.CalledProcessError(comout['command'], comout)
        if return_full_dict:
            return comout
        if original_return_st:
            return comout['stdout']
        else:
            return comout['return_code']
557703
def run_on_ui_thread(f):
    '''
    '''
    def f2(*args, **kwargs):
        Runnable(f)(*args, **kwargs)
    return f2
787158
def _wait_for_process(self, pid, name):
        
        try:
            logging.debug("Waiting for process %s with pid %s", name, pid)
            unused_pid, exitcode, ru_child = os.wait4(pid, 0)
            return exitcode, ru_child
        except OSError as e:
            if self.PROCESS_KILLED and e.errno == errno.EINTR:
                # Interrupted system call seems always to happen
                # if we killed the process ourselves after Ctrl+C was pressed
                # We can try again to get exitcode and resource usage.
                logging.debug("OSError %s while waiting for termination of %s (%s): %s.",
                              e.errno, name, pid, e.strerror)
                try:
                    unused_pid, exitcode, ru_child = os.wait4(pid, 0)
                    return exitcode, ru_child
                except OSError:
                    pass # original error will be handled and this ignored

            logging.critical("OSError %s while waiting for termination of %s (%s): %s.",
                             e.errno, name, pid, e.strerror)
            return (0, None)
744011
@Override
	public boolean isMachineRunning( TargetHandlerParameters parameters, String machineId )
	throws TargetException {

		this.logger.fine( "Verifying the in-memory agent for " + machineId + " is running." );
		Map<String,String> targetProperties = preventNull( parameters.getTargetProperties());

		// No agent factory => no iPojo instance => not running
		boolean result = false;
		if( this.standardAgentFactory != null )
			result = this.standardAgentFactory.getInstancesNames().contains( machineId );

		// On restoration, in-memory agents will ALL have disappeared.
		// So, it makes sense to recreate them if they do not exist anymore.
		// To determine whether we should restore them or no, we look for the model in the manager.
		if( ! result && ! simulatePlugins( targetProperties )) {

			Map.Entry<String,String> ctx = parseMachineId( machineId );
			ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( ctx.getValue());
			Instance scopedInstance = InstanceHelpers.findInstanceByPath( ma.getApplication(), ctx.getKey());

			// Is it supposed to be running?
			if( scopedInstance.getStatus() != InstanceStatus.NOT_DEPLOYED ) {
				this.logger.fine( "In-memory agent for " + machineId + " is supposed to be running but is not. It will be restored." );
				Map<String,String> messagingConfiguration = this.manager.messagingMngr().getMessagingClient().getConfiguration();
				Factory factory = findIPojoFactory( parameters );
				createIPojo( targetProperties, messagingConfiguration, machineId, ctx.getKey(), ctx.getValue(), this.manager.getDomain(), factory );
				result = true;
				// The agent will restore its model by asking it to the DM.
			}
		}

		return result;
	}
672992
async def enter_rescue_mode(
            self, wait: bool = False, wait_interval: int = 5):
        
        try:
            self._data = await self._handler.rescue_mode(
                system_id=self.system_id)
        except CallError as error:
            if error.status == HTTPStatus.FORBIDDEN:
                message = "Not allowed to enter rescue mode"
                raise OperationNotAllowed(message) from error
            else:
                raise

        if not wait:
            return self
        else:
            # Wait for machine to finish entering rescue mode
            while self.status == NodeStatus.ENTERING_RESCUE_MODE:
                await asyncio.sleep(wait)
                self._data = await self._handler.read(system_id=self.system_id)
            if self.status == NodeStatus.FAILED_ENTERING_RESCUE_MODE:
                msg = "{hostname} failed to enter rescue mode.".format(
                    hostname=self.hostname
                )
                raise RescueModeFailure(msg, self)
            return self
246093
@Override
	public boolean isMachineRunning( TargetHandlerParameters parameters, String machineId )
	throws TargetException {
		// TODO remove next line when APIs get compatible...
		String postfix = (parameters.getTargetProperties().get(CloudautomationMixins.PROVIDER_ENDPOINT) != null ? "" : "/compute");
		return OcciVMUtils.isVMRunning(parameters.getTargetProperties().get(SERVER_IP_PORT) + postfix, machineId);
	}
459464
public void postUnit (Unit unit)
    {
        if (shutdownRequested()) {
            throw new IllegalStateException("Cannot post units to shutdown invoker.");
        }
        // note the time
        unit.queueStamp = System.currentTimeMillis();
        // and append it to the queue
        _queue.append(unit);
    }
172502
def sysidpath(ignore_options=False):
    
    # in the event we have to make our own
    # this should not be passed in a as a parameter
    # since we need these definitions to be more or less static
    failover = Path('/tmp/machine-id')

    if not ignore_options:
        options = (
            Path('/etc/machine-id'),
            failover,  # always read to see if we somehow managed to persist this
        )
        for option in options:
            if (option.exists() and
                os.access(option, os.R_OK) and
                option.stat().st_size > 0):
                    return option

    uuid = uuid4()
    with open(failover, 'wt') as f:
        f.write(uuid.hex)

    return failover
951087
def startDataStoreMachine(self, dataStoreItemName, machineName):
        
        url = self._url + "/items/enterpriseDatabases/%s/machines/%s/start" % (dataStoreItemName, machineName)
        params = {
            "f": "json"
        }
        return self._post(url=url, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
211063
def run(self, **options):
        
        shutdown_message = options.get('shutdown_message', '')

        self.stdout.write("Performing system checks...\n\n")
        self.check(display_num_errors=True)
        self.check_migrations()
        now = datetime.datetime.now().strftime(r'%B %d, %Y - %X')
        if six.PY2:
            now = now.decode(get_system_encoding())
        self.stdout.write(now)

        addr, port = self.addr, self.port
        addr = '[{}]'.format(addr) if self._raw_ipv6 else addr

        runner = GunicornRunner(addr, port, options)
        try:
            runner.run()
        except KeyboardInterrupt:
            runner.shutdown()
            if shutdown_message:
                self.stdout.write(shutdown_message)
            sys.exit(0)
        except:
            runner.shutdown()
            raise
334141
private static Runnable removeFileSystemRunnable(URI uri) {
    if (Jimfs.systemProvider == null) {
      // TODO(cgdecker): Use Runnables.doNothing() when it's out of @Beta
      return DO_NOTHING;
    }

    // We have to invoke the SystemJimfsFileSystemProvider.removeFileSystemRunnable(URI)
    // method reflectively since the system-loaded instance of it may be a different class
    // than the one we'd get if we tried to cast it and call it like normal here.
    try {
      Method method =
          Jimfs.systemProvider.getClass().getDeclaredMethod("removeFileSystemRunnable", URI.class);
      return (Runnable) method.invoke(null, uri);
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
      throw new RuntimeException(
          "Unable to get Runnable for removing the FileSystem from the cache when it is closed", e);
    }
  }