Check if the daemon connection is established and valid
428877
def valid_connection(*outer_args, **outer_kwargs):
        # pylint: disable=unused-argument, no-method-argument
        """"""
        def decorator(func):  # pylint: disable=missing-docstring
            def decorated(*args, **kwargs):  # pylint: disable=missing-docstring
                # outer_args and outer_kwargs are the decorator arguments
                # args and kwargs are the decorated function arguments
                link = args[0]
                if not link.con:
                    raise LinkError("The connection is not created for %s" % link.name)
                if not link.running_id:
                    raise LinkError("The connection is not initialized for %s" % link.name)

                return func(*args, **kwargs)
            return decorated
        return decorator
592937
def is_running(self, port):
        """"""
        try:
            con = self.client('localhost:%s' % port)
            con.admin.command('ping')
            return True
        except (AutoReconnect, ConnectionFailure, OperationFailure):
            # Catch OperationFailure to work around SERVER-31916.
            return False
981674
def _check_pid(self, allow_reset=False):
        """"""
        if not self.pid == current_process().pid:
            if allow_reset:
                self.reset()
            else:
                raise RuntimeError("Forbidden operation in multiple processes")
983693
public boolean checkIdle (long idleStamp)
    {
        if (_lastEvent > idleStamp) {
            return false;
        }
        if (!isClosed()) {
            log.info("Disconnecting non-communicative client",
                     "conn", this, "idle", (System.currentTimeMillis() - _lastEvent) + "ms");
        }
        return true;
    }
283235
def check_connection (self):
        
        # proxy support (we support only http)
        self.set_proxy(self.aggregate.config["proxy"].get(self.scheme))
        if self.proxy:
            # using a (HTTP) proxy
            http = httpurl.HttpUrl(self.base_url,
                  self.recursion_level,
                  self.aggregate,
                  parent_url=self.parent_url,
                  base_ref=self.base_ref,
                  line=self.line,
                  column=self.column,
                  name=self.name)
            http.build_url()
            return http.check()
        self.login()
        self.negotiate_encoding()
        self.filename = self.cwd()
        self.listfile()
        self.files = []
        return None
1266676
def check_server_running(pid):
    
    if pid == os.getpid():
        # special case--we're in Docker or some other kind of container
        # (or we got really unlucky and got the same PID twice).
        # this PID does not correspond to another running server, either way.
        return False

    try:
        os.kill(pid, 0)
        return True
    except OSError as oe:
        if oe.errno == errno.ESRCH:
            return False
        else:
            raise
222215
public function isActive()
    {
        // Get the process id file location for the application.
        $pidFile = $this->config->get('application_pid_file');

        // If the process id file doesn't exist then the daemon is obviously not running.
        if (!is_file($pidFile)) {
            return false;
        }

        // Read the contents of the process id file as an integer.
        $fp = fopen($pidFile, 'r');
        $pid = fread($fp, filesize($pidFile));
        $pid = (int) $pid;
        fclose($fp);

        // Check to make sure that the process id exists as a positive integer.
        if (!$pid) {
            return false;
        }

        // Check to make sure the process is active by pinging it and ensure it responds.
        if (!posix_kill($pid, 0)) {
            // No response so remove the process id file and log the situation.
            @ unlink($pidFile);

            $this->getLogger()->warning('The process found based on PID file was unresponsive.');

            return false;
        }

        return true;
    }
1271542
def check(self, radl):
        """"""

        if not radl.get_system_by_name(self.system):
            raise RADLParseException("Invalid system id '%s'" % self.system, line=self.line)
        if not radl.get_configure_by_name(self.configure):
            raise RADLParseException("Invalid configure id '%s'" % self.configure, line=self.line)
115314
function() {

    // Automatically return true if we are in the GUI and on linux because
    // this requires SUDO and because the daemon should always be running on nix
    if (mode === 'gui' && process.platform === 'linux') {
      return Promise.resolve(true);
    }

    // Get status
    return isDown()

    // Only start if we aren't already
    .then(function(isDown) {
      if (isDown) {
        var opts = (process.platform === 'win32') ? {detached: true} : {};
        return serviceCmd(['start'], opts);
      }
    })

    // Wait for the daemon to respond
    .retry(function() {
      log.debug('Trying to connect to daemon.');
      return bin.sh([DOCKER_EXECUTABLE, 'info'], {mode: 'collect'});
    }, {max: 25, backoff: 1000})

    // Wrap errors.
    .catch(function(err) {
      throw new VError(err, 'Error bringing daemon up.');
    });

  }
1020494
def has_idle_connection(cls, pid):
        
        with cls._lock:
            cls._ensure_pool_exists(pid)
            return bool(cls._pools[pid].idle_connections)
1210479
def check
      begin
        checker_identity = "#{@agent[:identity]}-rchk"
        pid_file = PidFile.new(checker_identity, @agent[:pid_dir])

        if @options[:stop]
          # Stop checker
          pid_data = pid_file.read_pid
          if pid_data[:pid]
            info("Stopping checker daemon")
            if RightScale::Platform.windows?
              begin
                send_command({:name => :terminate}, verbose = @options[:verbose], timeout = 30) do |r|
                  info(r)
                  terminate
                end
              rescue Exception => e
                error("Failed stopping checker daemon, confirm it is still running", e, abort = true)
              end
            else
              Process.kill('TERM', pid_data[:pid])
              terminate
            end
          else
            terminate
          end
        elsif @options[:daemon]
          # Run checker as daemon
          pid_file.check rescue error("Cannot start checker daemon because already running", nil, abort = true)
          daemonize(checker_identity, @options) unless RightScale::Platform.windows?
          pid_file.write
          at_exit { pid_file.remove }

          listen_port = CommandConstants::BASE_INSTANCE_AGENT_CHECKER_SOCKET_PORT
          @command_runner = CommandRunner.start(listen_port, checker_identity, AgentCheckerCommands.get(self))

          info("Checker daemon options:")
          log_options = @options.inject([]) { |t, (k, v)| t << "-  #{k}: #{v}" }
          log_options.each { |l| info(l, to_console = false, no_check = true) }

          info("Starting checker daemon with #{elapsed(@options[:time_limit])} polling " +
               "and #{elapsed(@options[:time_limit])} last communication limit")

          iteration = 0
          EM.add_periodic_timer(@options[:time_limit]) do
            iteration += 1
            debug("Checker iteration #{iteration}")
            check_communication(0)
          end
        else
          # Perform one check
          check_communication(0, @options[:ping])
        end
      rescue SystemExit => e
        raise e
      rescue Exception => e
        error("Internal checker failure", e, abort = true)
      end
      true
    end
666300
def status(self):
        """"""
        if self.pidfile is None:
            raise DaemonError('Cannot get status of daemon without PID file')

        pid = self._read_pidfile()
        if pid is None:
            self._emit_message(
                '{prog} -- not running\n'.format(prog=self.prog))
            sys.exit(1)

        proc = psutil.Process(pid)
        # Default data
        data = {
            'prog': self.prog,
            'pid': pid,
            'status': proc.status(),
            'uptime': '0m',
            'cpu': 0.0,
            'memory': 0.0,
        }

        # Add up all the CPU and memory usage of all the
        # processes in the process group
        pgid = os.getpgid(pid)
        for gproc in psutil.process_iter():
            try:
                if os.getpgid(gproc.pid) == pgid and gproc.pid != 0:
                    data['cpu'] += gproc.cpu_percent(interval=0.1)
                    data['memory'] += gproc.memory_percent()
            except (psutil.Error, OSError):
                continue

        # Calculate the uptime and format it in a human-readable but
        # also machine-parsable format
        try:
            uptime_mins = int(round((time.time() - proc.create_time()) / 60))
            uptime_hours, uptime_mins = divmod(uptime_mins, 60)
            data['uptime'] = str(uptime_mins) + 'm'
            if uptime_hours:
                uptime_days, uptime_hours = divmod(uptime_hours, 24)
                data['uptime'] = str(uptime_hours) + 'h ' + data['uptime']
                if uptime_days:
                    data['uptime'] = str(uptime_days) + 'd ' + data['uptime']
        except psutil.Error:
            pass

        template = ('{prog} -- pid: {pid}, status: {status}, '
                    'uptime: {uptime}, %cpu: {cpu:.1f}, %mem: {memory:.1f}\n')
        self._emit_message(template.format(**data))
772904
def is_connected(self):
        """"""
        self._connected = self._connected and self._conn.is_connected()
        return self._connected
1336185
def _verify_connection(self):
        
        try:
            res = self._session.get(self._connection_validation_url, json={})
            logger.debug(consts.LOG_MSG_VERIFYING_CONNECTION,
                         self._connection_validation_url,
                         res if res else 'No result from backend')
            if not res.ok:
                raise requests.exceptions.RequestException(res.content)
            remote_batch_size = res.json().get(consts.MAX_REQUEST_SIZE_FIELD,
                                               consts.DEFAULT_BATCH_SIZE)
            if remote_batch_size < self._batch_max_size:
                self._batch_max_size = remote_batch_size
                self._notify(logging.INFO,
                             consts.LOG_MSG_NEW_BATCH_SIZE % remote_batch_size)
            self._is_connected.set()
            return True

        except requests.exceptions.RequestException as ex:
            msg = consts.LOG_MSG_CONNECTION_FAILED % str(ex)
            self._notify(logging.ERROR, msg)
            raise exceptions.ConnectionFailed(msg)
534180
def check() -> Result:
        """"""
        try:
            # Context to release connection
            with Connection(conf.get('CELERY_BROKER_URL')) as conn:
                conn.connect()
        except ConnectionRefusedError:
            return Result(message='Service unable to connect, "Connection was refused".',
                          severity=Result.ERROR)

        except AccessRefused:
            return Result(message='Service unable to connect, "Authentication error".',
                          severity=Result.ERROR)

        except IOError:
            return Result(message='Service has an "IOError".', severity=Result.ERROR)

        except Exception as e:
            return Result(message='Service has an "{}" error.'.format(e), severity=Result.ERROR)
        else:
            return Result()
766144
def check(self, radl):
        """"""

        if not radl.get_system_by_name(self.id):
            raise RADLParseException("Invalid system id in the deploy.", line=self.line)

        if self.vm_number < 0:
            raise RADLParseException("Invalid number of virtual machines to deploy.",
                                     line=self.line)
1156749
def check_status(self):
        

        def validate_namespace(self):
            if not self.has_namespace(self.namespace):
                log.warning(format_multiline(["",
                                              """\tnamespace '{}' does not
                                              exist. Creating namespace"""],
                                              self.namespace))
                self.create_namespace(self.namespace)

        if self.url:
            return True
        try:
            result = requests.get(self._make_url(self.namespace,
                                                 self.ext_url,
                                                 check_status_call=True))
            self.url = self.ext_url
            validate_namespace(self)
            return True
        except requests.exceptions.ConnectionError:
            pass
        try:
            result = requests.get(self._make_url(self.namespace,
                                                 self.local_url,
                                                 check_status_call=True))
            log.warning("Url '%s' not connecting. Using local_url '%s'" % \
                     (self.ext_url, self.local_url))
            self.url = self.local_url
            validate_namespace(self)
            return True
        except requests.exceptions.ConnectionError:
            self.url = None
            log.warning("Unable to connect using urls: %s" % set([self.ext_url,
                                                               self.local_url]))
            return False