Return Icinga's uptime
345544
def _get_uptime(self, app_stats):
        
        if "program_start" not in app_stats.keys():
            return 0

        if not app_stats["program_start"].isdigit():
            return 0

        uptime = int(time.time()) - int(app_stats["program_start"])
        if uptime < 0:
            return 0

        return uptime
1231275
private function _uptime()
    {
        if (CommonFunctions::executeProgram('uptime', '', $buf)) {
            if (preg_match("/up (\d+) day[s]?,\s*(\d+):(\d+),/", $buf, $ar_buf)) {
                $min = $ar_buf[3];
                $hours = $ar_buf[2];
                $days = $ar_buf[1];
                $this->sys->setUptime($days * 86400 + $hours * 3600 + $min * 60);
            }
        }
    }
268669
protected function uptime()
    {
        $linfo = $this->linfo->getParser();

        $uptime = $booted_at = null;

        $systemUptime = $this->ifExists($linfo->getUpTime());

        if (! empty($systemUptime['text'])) {
            $uptime = $systemUptime['text'];
        }

        if (! empty($systemUptime['bootedTimestamp'])) {
            $booted_at = date('Y-m-d H:i:s', $systemUptime['bootedTimestamp']);
        }

        $this->results['server']['uptime'] = compact(
            'uptime', 'booted_at'
        );

        return $this;
    }
648668
def get_lambda_runtime_info(context):
    '''
    
    '''

    runtime_info = {
        'remaining_time': context.get_remaining_time_in_millis(),
        'function_name': context.function_name,
        'function_version': context.function_version,
        'invoked_function_arn': context.invoked_function_arn,
        'memory_limit': context.memory_limit_in_mb,
        'aws_request_id': context.aws_request_id,
        'log_group_name': context.log_group_name,
        'log_stream_name': context.log_stream_name
    }

    return runtime_info
592206
def _get(self, name, interval, config, timestamp, **kws):
    '''
    
    '''
    i_bucket = config['i_calc'].to_bucket(timestamp)
    fetch = kws.get('fetch')
    process_row = kws.get('process_row') or self._process_row

    rval = OrderedDict()
    if fetch:
      data = fetch( self._client.connect(), self._table, name, interval, i_bucket )
    else:
      data = self._type_get(name, interval, i_bucket)

    if config['coarse']:
      if data:
        rval[ config['i_calc'].from_bucket(i_bucket) ] = process_row(data.values()[0][None])
      else:
        rval[ config['i_calc'].from_bucket(i_bucket) ] = self._type_no_value()
    else:
      for r_bucket,row_data in data.values()[0].items():
        rval[ config['r_calc'].from_bucket(r_bucket) ] = process_row(row_data)

    return rval
606661
def getMonitors(self, response_times=0, logs=0, uptime_ratio=''):
        
        url = self.baseUrl
        url += "getMonitors?apiKey=%s" % (self.apiKey)
        url += "&noJsonCallback=1&format=json"
        # responseTimes - optional (defines if the response time data of each
        # monitor will be returned. Should be set to 1 for getting them. Default
        # is 0)
        if response_times:
            url += "&responseTimes=1"
        # logs - optional (defines if the logs of each monitor will be returned.
        # Should be set to 1 for getting the logs. Default is 0)
        if logs:
            url += '&logs=1'
        # customUptimeRatio - optional (defines the number of days to calculate
        # the uptime ratio(s) for. Ex: customUptimeRatio=7-30-45 to get the
        # uptime ratios for those periods)
        if uptime_ratio:
            url += '&customUptimeRatio=%s' % uptime_ratio

        return self.requestApi(url)
172505
def get(self):
        
        now = time.time()
        while self._clients and self._clients[0][0] < now:
            _, (client, last_wait) = heapq.heappop(self._clients)
            connect_start = time.time()
            try:
                client.echo("test")  # reconnected if this succeeds.
                self._client_ids.remove(client.pool_id)
                yield client
            except (ConnectionError, TimeoutError):
                timer = time.time() - connect_start
                wait = min(int(last_wait * self._multiplier), self._max_wait)
                heapq.heappush(self._clients, (time.time() + wait, (client, wait)))
                log.info(
                    "%r is still down after a %s second attempt to connect. Retrying in %ss.",
                    client,
                    timer,
                    wait,
                )
1012624
def getTimeSinceLastUpdate(IOType):
    """"""
    global last_update_times
    # assert(IOType in ['net', 'disk', 'process_disk'])
    current_time = time()
    last_time = last_update_times.get(IOType)
    if not last_time:
        time_since_update = 1
    else:
        time_since_update = current_time - last_time
    last_update_times[IOType] = current_time
    return time_since_update
137830
def getCPUuse(self):
        
        hz = os.sysconf('SC_CLK_TCK')
        info_dict = {}
        try:
            fp = open(cpustatFile, 'r')
            line = fp.readline()
            fp.close()
        except:
            raise IOError('Failed reading stats from file: %s' % cpustatFile)
        headers = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq', 'steal', 'guest']
        arr = line.split()
        if len(arr) > 1 and arr[0] == 'cpu':
            return dict(zip(headers[0:len(arr)], [(float(t) / hz) for t in arr[1:]]))
        return info_dict
555265
def get_time_server():
    '''
    
    '''
    ret = salt.utils.mac_utils.execute_return_result(
        'systemsetup -getnetworktimeserver')
    return salt.utils.mac_utils.parse_return(ret)
841351
function cpuAverage() {
      //Initialise sum of idle and time of cores and fetch CPU info
      var totalIdle = 0, totalTick = 0;
      var cpus = os.cpus();

      //Loop through CPU cores
      for(var i = 0, len = cpus.length; i < len; i++) {

        //Select CPU core
        var cpu = cpus[i];

        //Total up the time in the cores tick
        for(type in cpu.times) {
          totalTick += cpu.times[type];
       }

        //Total up the idle time of the core
        totalIdle += cpu.times.idle;
      }

      //Return the average Idle and Tick times
      return {idle: totalIdle / cpus.length,  total: totalTick / cpus.length};
    }
735252
private function _uptime()
    {
        if (CommonFunctions::executeProgram('uptime', '', $buf)) {
            if (preg_match("/up (\d+) day[s]?,\s*(\d+):(\d+),/", $buf, $ar_buf)) {
                $min = $ar_buf[3];
                $hours = $ar_buf[2];
                $days = $ar_buf[1];
                $this->sys->setUptime($days * 86400 + $hours * 3600 + $min * 60);
            } elseif (preg_match("/up (\d+):(\d+),/", $buf, $ar_buf)) {
                $min = $ar_buf[2];
                $hours = $ar_buf[1];
                $this->sys->setUptime($hours * 3600 + $min * 60);
            }
        }
    }
961547
function getRealUptime (next) {
  fs.readFile('/proc/uptime', 'utf8', function (err, uptime) {
    if (err || uptime === undefined) {
      console.warn("[pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value")
      return next(null, os.uptime())
    }

    return next(null, parseFloat(uptime.split(' ')[0]))
  })
}
205981
def collect(self):
        
        stats = self.parse_stats_file(self.config["status_path"])
        if len(stats) == 0:
            return {}
        elif "info" not in stats.keys():
            return {}
        elif "programstatus" not in stats.keys():
            return {}

        metrics = self.get_icinga_stats(stats["programstatus"])
        if "hoststatus" in stats.keys():
            metrics = dict(
                metrics.items() + self.get_host_stats(
                    stats["hoststatus"]).items())

        if "servicestatus" in stats.keys():
            metrics = dict(
                metrics.items() + self.get_svc_stats(
                    stats["servicestatus"]).items())

        for metric in metrics.keys():
            self.log.debug("Publishing '%s %s'.", metric, metrics[metric])
            self.publish(metric, metrics[metric])
966818
def get_time():
    """"""

    time_request = '\x1b' + 47 * '\0'
    now = struct.unpack("!12I", ntp_service.request(time_request, timeout=5.0).data.read())[10]
    return time.ctime(now - EPOCH_START)
490112
def main(host='localhost', port=8086, nb_day=15):
    """"""
    nb_day = 15  # number of day to generate time series
    timeinterval_min = 5  # create an event every x minutes
    total_minutes = 1440 * nb_day
    total_records = int(total_minutes / timeinterval_min)
    now = datetime.datetime.today()
    metric = "server_data.cpu_idle"
    series = []

    for i in range(0, total_records):
        past_date = now - datetime.timedelta(minutes=i * timeinterval_min)
        value = random.randint(0, 200)
        hostName = "server-%d" % random.randint(1, 5)
        # pointValues = [int(past_date.strftime('%s')), value, hostName]
        pointValues = {
            "time": int(past_date.strftime('%s')),
            "measurement": metric,
            "fields": {
                "value": value,
            },
            "tags": {
                "hostName": hostName,
            },
        }
        series.append(pointValues)

    print(series)

    client = InfluxDBClient(host, port, USER, PASSWORD, DBNAME)

    print("Create database: " + DBNAME)
    try:
        client.create_database(DBNAME)
    except InfluxDBClientError:
        # Drop and create
        client.drop_database(DBNAME)
        client.create_database(DBNAME)

    print("Create a retention policy")
    retention_policy = 'server_data'
    client.create_retention_policy(retention_policy, '3d', 3, default=True)

    print("Write points #: {0}".format(total_records))
    client.write_points(series, retention_policy=retention_policy)

    time.sleep(2)

    query = "SELECT MEAN(value) FROM {} WHERE \
            time > now() - 10d GROUP BY time(500m)".format(metric)
    result = client.query(query, database=DBNAME)
    print(result)
    print("Result: {0}".format(result))

    print("Drop database: {}".format(DBNAME))
    client.drop_database(DBNAME)
424233
def vgcsUplinkGrant():
    """"""
    a = TpPd(pd=0x6)
    b = MessageType(mesType=0x9)  # 00001001
    c = RrCause()
    d = RequestReference()
    e = TimingAdvance()
    packet = a / b / c / d / e
    return packet