Get the current values for a metric.

        Returns a dictionary with metric values accumulated for the seconds,
        minutes, hours, day, week, month, and year.
6521
def get_metric(self, slug):
        
        results = OrderedDict()
        granularities = self._granularities()
        keys = self._build_keys(slug)
        for granularity, key in zip(granularities, keys):
            results[granularity] = self.r.get(key)
        return results
952070
def _GetTimeValues(self, number_of_seconds):
    
    number_of_seconds = int(number_of_seconds)
    number_of_minutes, seconds = divmod(number_of_seconds, 60)
    number_of_hours, minutes = divmod(number_of_minutes, 60)
    number_of_days, hours = divmod(number_of_hours, 24)
    return number_of_days, hours, minutes, seconds
465647
def get_metric_time_series(self, mts_id, **kwargs):
        """"""
        return self._get_object_by_name(self._MTS_ENDPOINT_SUFFIX,
                                        mts_id,
                                        **kwargs)
1088395
def get_current(self):
        """"""
        now = dt.now().timestamp()
        url = build_url(self.api_key, self.spot_id, self.fields,
                        self.unit, now, now)
        return get_msw(url)
1210309
def log_metrics(self, metrics_by_name, info):
        
        try:
            metrics_path = os.path.join(self.dir, "metrics.json")
            with open(metrics_path, 'r') as f:
                saved_metrics = json.load(f)
        except IOError:
            # We haven't recorded anything yet. Start Collecting.
            saved_metrics = {}

        for metric_name, metric_ptr in metrics_by_name.items():

            if metric_name not in saved_metrics:
                saved_metrics[metric_name] = {"values": [],
                                              "steps": [],
                                              "timestamps": []}

            saved_metrics[metric_name]["values"] += metric_ptr["values"]
            saved_metrics[metric_name]["steps"] += metric_ptr["steps"]

            # Manually convert them to avoid passing a datetime dtype handler
            # when we're trying to convert into json.
            timestamps_norm = [ts.isoformat()
                               for ts in metric_ptr["timestamps"]]
            saved_metrics[metric_name]["timestamps"] += timestamps_norm

        self.save_json(saved_metrics, 'metrics.json')
874357
def get_metrics(awsclient, name):
    
    metrics = ['Duration', 'Errors', 'Invocations', 'Throttles']
    client_cw = awsclient.get_client('cloudwatch')
    for metric in metrics:
        response = client_cw.get_metric_statistics(
            Namespace='AWS/Lambda',
            MetricName=metric,
            Dimensions=[
                {
                    'Name': 'FunctionName',
                    'Value': name
                },
            ],
            # StartTime=datetime.now() + timedelta(days=-1),
            # EndTime=datetime.now(),
            StartTime=maya.now().subtract(days=1).datetime(),
            EndTime=maya.now().datetime(),
            Period=3600,
            Statistics=[
                'Sum',
            ],
            Unit=unit(metric)
        )
        log.info('\t%s %s' % (metric,
                           repr(aggregate_datapoints(response['Datapoints']))))
    return 0
963188
private Map<MetricName, MetricValue> get_metrics_(DateTime now, Context ctx) {
        final Consumer<Alert> alert_manager = ctx.getAlertManager();
        final long failed_collections = registry_.getFailedCollections();
        final boolean has_config = registry_.hasConfig();
        final Optional<Duration> scrape_duration = registry_.getScrapeDuration();
        final Optional<Duration> rule_eval_duration = registry_.getRuleEvalDuration();
        final Optional<Duration> processor_duration = registry_.getProcessorDuration();
        first_scrape_ts_.compareAndSet(null, now);  // First time, register the timestamp.
        final Duration uptime = new Duration(first_scrape_ts_.get(), now);

        final Optional<DateTime> last_scrape = last_scrape_;
        last_scrape_ = Optional.of(now);

        final long metric_count = ctx.getTSData().getCurrentCollection().getTSValues().stream()
                .map(TimeSeriesValue::getMetrics)
                .collect(Collectors.summingLong(Map::size));

        alert_manager.accept(new Alert(now, MONITOR_FAIL_ALERT, () -> "builtin rule", Optional.of(failed_collections != 0), MON_ALERT_DURATION, "builtin rule: some collectors failed", EMPTY_MAP));
        alert_manager.accept(new Alert(now, HAS_CONFIG_ALERT, () -> "builtin rule", Optional.of(!has_config), Duration.ZERO, "builtin rule: monitor has no configuration file", EMPTY_MAP));

        Map<MetricName, MetricValue> result = new HashMap<>();
        result.put(FAILED_COLLECTIONS_METRIC, MetricValue.fromIntValue(failed_collections));
        result.put(GROUP_COUNT_METRIC, MetricValue.fromIntValue(ctx.getTSData().getCurrentCollection().getGroups(x -> true).size()));
        result.put(METRIC_COUNT_METRIC, MetricValue.fromIntValue(metric_count));
        result.put(CONFIG_PRESENT_METRIC, MetricValue.fromBoolean(has_config));
        result.put(SCRAPE_DURATION, opt_duration_to_metricvalue_(scrape_duration));
        result.put(RULE_EVAL_DURATION, opt_duration_to_metricvalue_(rule_eval_duration));
        result.put(PROCESSOR_DURATION, opt_duration_to_metricvalue_(processor_duration));
        result.put(UPTIME_DURATION, duration_to_metricvalue_(uptime));
        result.put(SCRAPE_COUNT, MetricValue.fromIntValue(++scrape_count_));
        result.put(SCRAPE_INTERVAL, opt_duration_to_metricvalue_(last_scrape.map(prev -> new Duration(prev, now))));
        result.put(SCRAPE_TS, MetricValue.fromIntValue(now.getMillis()));
        return result;
    }
1267103
async def get_metrics(self, element):
        """"""
        await self.get_data()
        await self.get_plugins()

        if element in self.plugins:
            self.values = self.data[element]
        else:
            raise exceptions.GlancesApiError("Element data not available")
470335
def _get_metric(self, metric, tablename, index_name=None):
        
        end = time.time()
        begin = end - 3 * 60  # 3 minute window
        dimensions = [{"Name": "TableName", "Value": tablename}]
        if index_name is not None:
            dimensions.append({"Name": "GlobalSecondaryIndexName", "Value": index_name})
        period = 60
        data = self.cloudwatch_connection.get_metric_statistics(
            Period=period,
            StartTime=begin,
            EndTime=end,
            MetricName=metric,
            Namespace="AWS/DynamoDB",
            Statistics=["Sum"],
            Dimensions=dimensions,
        )
        points = data["Datapoints"]
        if not points:
            return 0
        else:
            points.sort(key=lambda r: r["Timestamp"])
            return float(points[-1]["Sum"]) / period
1306179
def get_seconds(value, scale):
  
  scales = {
    'seconds': lambda x: x,
    'minutes': lambda x: x * 60,
    'hours': lambda x: x * 60 * 60,
    'days': lambda x: x * 60 * 60 * 24,
    'weeks': lambda x: x * 60 * 60 * 24 * 7,
    'months': lambda x: x * 60 * 60 * 24 * 30,
    'years': lambda x: x * 60 * 60 * 24 * 365,
  }
  return scales[scale](value)
1027780
def get_current(self):
        

        where = slice(self._oldest_frame_idx(), self._pos)
        major_axis = pd.DatetimeIndex(deepcopy(self.date_buf[where]), tz='utc')
        return pd.Panel(self.buffer.values[:, where, :], self.items,
                        major_axis, self.minor_axis, dtype=self.dtype)
1245772
def GetTimeOfDay(self):
    
    normalized_timestamp = self._GetNormalizedTimestamp()
    if normalized_timestamp is None:
      return None, None, None

    _, hours, minutes, seconds = self._GetTimeValues(normalized_timestamp)
    return hours, minutes, seconds
197
def _GetMetric(self, metric_name):
    """"""
    if metric_name in self._counter_metrics:
      return self._counter_metrics[metric_name]
    elif metric_name in self._event_metrics:
      return self._event_metrics[metric_name]
    elif metric_name in self._gauge_metrics:
      return self._gauge_metrics[metric_name]
    else:
      raise ValueError("Metric %s is not registered." % metric_name)
1125033
def get_metric_index(self, metric_cls):
        
        ds = self.class2ds[metric_cls.ds]
        if self.index_dict[ds]:
            index_name = self.index_dict[ds]
        else:
            index_name = self.ds2index[metric_cls.ds]
        return index_name
672600
def marshall_now(now=None):
    
    if not now:
        now = utcnow()
    return dict(day=now.day, month=now.month, year=now.year, hour=now.hour,
                minute=now.minute, second=now.second,
                microsecond=now.microsecond)
1233755
def _get_weekly_date_range(self, metric_date, delta):
        
        dates = [metric_date]
        end_date = metric_date + delta
        #Figure out how many years our metric range spans
        spanning_years = end_date.year - metric_date.year
        for i in range(spanning_years):
            #for the weekly keys, we only care about the year
            dates.append(
                datetime.date(
                    year=metric_date.year + (i + 1), month=1, day=1))
        return dates
143686
def __get_metrics(self):
        
        esfilters_merge = None
        esfilters_abandon = None
        if self.esfilters:
            esfilters_merge = self.esfilters.copy()
            esfilters_abandon = self.esfilters.copy()

        merged = Merged(self.es_url, self.es_index,
                        start=self.start, end=self.end,
                        esfilters=esfilters_merge, interval=self.interval)

        abandoned = Abandoned(self.es_url, self.es_index,
                              start=self.start, end=self.end,
                              esfilters=esfilters_abandon, interval=self.interval)
        return (merged, abandoned)