Start the logging child process if it died.
189082
def live_log_child(self):
        ''''''
        if not (self.log_child and self.pid_is_alive(self.log_child)):
            self.start_log_child()
1191298
def die(self):
        """"""
        if self.process:
            _log(self.logging,
                 'Stopping {0} server with PID: {1} running at {2}.'
                     .format(self.__class__.__name__, self.process.pid,
                             self.check_url))

            self._kill()
1002366
def log(logger, level, message):
    """"""

    if logger.parent.name != 'root':
        logger.log(level, message)
    else:
        print(message, file=sys.stderr)
175330
def start(self):
        """"""

        if self.log_filename:
            print('Output will be logged to `%s`.' % self.log_filename)

        start_time = time.strftime(self.timestamp_fmt)
        print('Started %s' % start_time)

        if self.log_filename:
            orig_stdout = sys.stdout
            orig_stderr = sys.stderr

            sys.stdout = self.log_file
            sys.stderr = self.log_file

            print('Started %s' % start_time)

        doit_main = DoitMain(self)
        doit_main.run(['run'])

        stop_time = time.strftime(self.timestamp_fmt)

        if self.log_filename:
            print('Stopped %s' % stop_time)
            print()

            sys.stdout = orig_stdout
            sys.stderr = orig_stderr
            self.log_file.close()

        print('Stopped %s' % stop_time)
1362805
def Start(self):
    """"""
    try:

      self.stats = {}

      self.BeginProcessing()

      processed_count = 0

      if data_store.RelationalDBEnabled():
        for client_info_batch in _IterateAllClients(
            recency_window=self.recency_window):
          for client_info in client_info_batch:
            self.ProcessClientFullInfo(client_info)
          processed_count += len(client_info_batch)
          self.Log("Processed %d clients.", processed_count)
          self.HeartBeat()
      else:
        root_children = aff4.FACTORY.Open(
            aff4.ROOT_URN, token=self.token).OpenChildren(mode="r")
        for batch in collection.Batch(root_children, CLIENT_READ_BATCH_SIZE):
          for child in batch:
            if not isinstance(child, aff4_grr.VFSGRRClient):
              continue

            last_ping = child.Get(child.Schema.PING)

            self.ProcessLegacyClient(last_ping, child)
            processed_count += 1
            # This flow is not dead: we don't want to run out of lease time.
            self.HeartBeat()

      self.FinishProcessing()
      for fd in itervalues(self.stats):
        fd.Close()

      logging.info("%s: processed %d clients.", self.__class__.__name__,
                   processed_count)
    except Exception as e:  # pylint: disable=broad-except
      logging.exception("Error while calculating stats: %s", e)
      raise
835582
public function killChild()
    {
        if (is_null($this->child)) {
            return;
        }

        if ($this->child === 0) {
            throw new Exception\Shutdown('Job forced shutdown');
        }

        Event::fire(Event::WORKER_KILLCHILD, array($this, $this->child));

        if (posix_kill($this->child, 0)) {
            $this->log('Killing child process at pid:'.$this->child, Logger::DEBUG);

            posix_kill($this->child, SIGTERM);
        }

        $this->child = null;
    }
488836
def finished!(process_status)
      if process_status.nil? && ! @self_started
        log :debug, "(#{@pid}/#{@pids.inspect}/self_started=#{@self_started}/killed=#{@killed}) I am no longer blocked."
        @pid = nil
        @backoff.died unless @killed
      elsif ! process_status.nil? && @self_started
        log :debug, "(#{@pid}/#{@pids.inspect}/self_started=#{@self_started}/killed=#{@killed}) I exited: #{process_status}"
        @pid = nil
        @backoff.died unless @killed
      else
        log :debug, "(#{@pid}/#{@pids.inspect}/self_started=#{@self_started}/killed=#{@killed}) Reports of my death are highly exaggerated (#{process_status.inspect})"
      end
    end
137864
def kill(self):
        """"""
        if not self.is_dead():
            self.bundle_engine.warnline("{0} did not shut down cleanly, killing.".format(self.service.name))
            try:
                if hasattr(self.process, 'pid'):
                    for child in psutil.Process(self.process.pid).children(recursive=True):
                        os.kill(child.pid, signal.SIGKILL)
                    self.process.kill()
            except psutil.NoSuchProcess:
                pass
813902
def _run(self):  # pylint: disable=method-hidden
        
        try:
            self.event_stop.wait()
        except gevent.GreenletExit:  # killed without exception
            self.event_stop.set()
            gevent.killall(self.greenlets)  # kill children
            raise  # re-raise to keep killed status
        except Exception:
            self.stop()  # ensure cleanup and wait on subtasks
            raise
929592
def dump_to_log(self, logger):
        """"""
        logger.error("Execution ended in %s for cmd %s", self._retcode, self._cmd)
        for line in self._collected_stdout:
            logger.error(STDOUT_LOG_PREFIX + line)
949349
def log_starting(self):
		""""""
		self.start_time = time.perf_counter()
		logger.log("Starting '", logger.cyan(self.name), "'...")
583882
def _start(self):
        """"""
        self._enable_logpersist()
        logcat_file_path = self._configs.output_file_path
        if not logcat_file_path:
            f_name = 'adblog,%s,%s.txt' % (self._ad.model,
                                           self._ad._normalized_serial)
            logcat_file_path = os.path.join(self._ad.log_path, f_name)
        utils.create_dir(os.path.dirname(logcat_file_path))
        cmd = '"%s" -s %s logcat -v threadtime %s >> "%s"' % (
            adb.ADB, self._ad.serial, self._configs.logcat_params,
            logcat_file_path)
        process = utils.start_standing_subprocess(cmd, shell=True)
        self._adb_logcat_process = process
        self.adb_logcat_file_path = logcat_file_path
1336088
public function killChild()
	{
		if(!$this->child) {
			$this->logger->log(Psr\Log\LogLevel::DEBUG, 'No child to kill.');
			return;
		}

		$this->logger->log(Psr\Log\LogLevel::INFO, 'Killing child at {child}', array('child' => $this->child));
		if(exec('ps -o pid,state -p ' . $this->child, $output, $returnCode) && $returnCode != 1) {
			$this->logger->log(Psr\Log\LogLevel::DEBUG, 'Child {child} found, killing.', array('child' => $this->child));
			posix_kill($this->child, SIGKILL);
			$this->child = null;
		}
		else {
			$this->logger->log(Psr\Log\LogLevel::INFO, 'Child {child} not found, restarting.', array('child' => $this->child));
			$this->shutdown();
		}
	}
1174468
def run(self):
        
        setproctitle.setproctitle("{:s}: {:s}".format(
            self.context.config.name, self.__class__.__name__))
        self.logger.info(
            "Worker '%s' has been started with pid %d",
            self.__class__.__name__, os.getpid())

        # Register SIGINT handler which will exit service process
        def sigint_handler(unused_signum, unused_frame):
            """
            Exit service process when SIGINT is reached.
            """
            self.stop()
        signal.signal(signal.SIGINT, sigint_handler)

        # Initialize logging
        self.context.config.configure_logging()
        # Initialize child
        self.context.initialize_child(SERVICE_PROCESS, process=self)

        next_loop_time = 0
        while 1:
            # Exit if pid of the parent process has changed (parent process
            # has exited and init is new parent) or if stop flag is set.
            if os.getppid() != self._parent_pid or self._stop_event.is_set():
                break
            # Repeatedly call loop method. After first call set ready flag.
            if time.time() >= next_loop_time:
                try:
                    self.loop()
                except Exception:
                    self.logger.exception(
                        "Worker '%s' failed", self.__class__.__name__)
                else:
                    if not next_loop_time and not self.ready:
                        self._ready.value = True
                next_loop_time = time.time() + self.interval
            else:
                time.sleep(0.25)
43519
def mark_process_dead(pid, path=None):
    """"""
    if path is None:
        path = os.environ.get('prometheus_multiproc_dir')
    for f in glob.glob(os.path.join(path, 'gauge_livesum_{0}.db'.format(pid))):
        os.remove(f)
    for f in glob.glob(os.path.join(path, 'gauge_liveall_{0}.db'.format(pid))):
        os.remove(f)
605537
def run(self):
        """"""
        self.log.debug("Entered main loop")
        while not self.shutdown:
            # If no service is running slow down the main loop
            if not self._pipe_service:
                time.sleep(0.3)
            self.update_status()
            # While a service is running, check for incoming messages from that service
            if self._pipe_service and self._pipe_service.poll(1):
                try:
                    message = self._pipe_service.recv()
                    if isinstance(message, dict) and "band" in message:
                        # only dictionaries with 'band' entry are valid messages
                        try:
                            handler = getattr(self, "parse_band_" + message["band"])
                        except AttributeError:
                            handler = None
                            self.log.warning("Unknown band %s", str(message["band"]))
                        if handler:
                            #              try:
                            handler(message)
                    #              except Exception:
                    #                print('Uh oh. What to do.')
                    else:
                        self.log.warning("Invalid message received %s", str(message))
                except EOFError:
                    # Service has gone away
                    error_message = False
                    if self._service_status == CommonService.SERVICE_STATUS_END:
                        self.log.info("Service terminated")
                    elif self._service_status == CommonService.SERVICE_STATUS_ERROR:
                        error_message = "Service terminated with error code"
                    elif self._service_status in (
                        CommonService.SERVICE_STATUS_NONE,
                        CommonService.SERVICE_STATUS_NEW,
                        CommonService.SERVICE_STATUS_STARTING,
                    ):
                        error_message = (
                            "Service may have died unexpectedly in "
                            + "initialization (last known status: %s)"
                            % CommonService.human_readable_state.get(
                                self._service_status, self._service_status
                            )
                        )
                    else:
                        error_message = (
                            "Service may have died unexpectedly"
                            " (last known status: %s)"
                            % CommonService.human_readable_state.get(
                                self._service_status, self._service_status
                            )
                        )
                    if error_message:
                        self.log.error(error_message)
                    self._terminate_service()
                    if self.restart_service:
                        self.exponential_backoff()
                    else:
                        self.shutdown = True
                        if error_message:
                            raise workflows.Error(error_message)

            with self.__lock:
                if (
                    self._service is None
                    and self.restart_service
                    and self._service_factory
                ):
                    self.update_status(status_code=CommonService.SERVICE_STATUS_NEW)
                    self.switch_service()

            # Check that the transport is alive
            if not self._transport.is_connected():
                self._terminate_service()
                raise workflows.Error("Lost transport layer connection")
        self.log.debug("Left main loop")
        self.update_status(status_code=CommonService.SERVICE_STATUS_TEARDOWN)
        self._terminate_service()
        self.log.debug("Terminating.")
702778
def watch_process(self, process):
        

        status = process["psutil"].status()

        # TODO: how to avoid zombies?
        # print process["pid"], status

        if process.get("terminate"):
            if status in ("zombie", "dead"):
                process["dead"] = True
            elif process.get("terminate_at"):
                if time.time() > (process["terminate_at"] + 5):
                    log.warning("Process %s had to be sent SIGKILL" % (process["pid"], ))
                    process["subprocess"].send_signal(signal.SIGKILL)
                elif time.time() > process["terminate_at"]:
                    log.warning("Process %s had to be sent SIGTERM" % (process["pid"], ))
                    process["subprocess"].send_signal(signal.SIGTERM)

        else:
            if status in ("zombie", "dead"):
                # Restart a new process right away (TODO: sleep a bit? max retries?)
                process["dead"] = True
                self.spawn(process["command"])

            elif status not in ("running", "sleeping"):
                log.warning("Process %s was in status %s" % (process["pid"], status))