Check if we have violated our quota for any metric that
        has a configured quota
760435
def _check_quotas(self, time_ms):
        
        for metric in self._metrics:
            if metric.config and metric.config.quota:
                value = metric.value(time_ms)
                if not metric.config.quota.is_acceptable(value):
                    raise QuotaViolationError("'%s' violated quota. Actual: "
                                              "%d, Threshold: %d" %
                                              (metric.metric_name,
                                               value,
                                               metric.config.quota.bound))
1343932
def get_request_quotas(self):
        

        resp = self._client.get("request-quotas")
        return [RequestQuota.from_dict(quota) for quota in resp.json()]
76280
def process(self, metric):
        
        if self._match_metric(metric):
            self.metrics.append(metric)
        if self.should_flush():
            self._send()
282956
def _check_exclude(self, val):
        
        if val is None:
            exclude = frozenset()
        elif isinstance(val, str):
            exclude = frozenset([val.lower()])
        else:
            exclude = frozenset(map(lambda s: s.lower(), val))

        if len(exclude - frozenset(METRICS)) > 0:
            raise YellowbrickValueError(
                "'{}' is not a valid metric to exclude".format(repr(val))
            )

        return exclude
906091
def assert_metric_has_tag(self, metric_name, tag, count=None, at_least=1):
        
        self._asserted.add(metric_name)

        candidates = []
        for metric in self.metrics(metric_name):
            if tag in metric.tags:
                candidates.append(metric)

        if count is not None:
            assert len(candidates) == count
        else:
            assert len(candidates) >= at_least
457564
def flush(self, log=False):
        
        if not self.my_metrics:
            logger.debug("Flushing - no metrics to send")
            return True

        now = int(time.time())
        if self.last_failure and self.last_failure + self.metrics_flush_pause > now:
            if not self.log_metrics_flush_pause:
                date = datetime.datetime.fromtimestamp(
                    self.last_failure).strftime(self.date_fmt)
                logger.warning("Metrics flush paused on connection error "
                               "(last failed: %s). "
                               "Inner stored metric: %d. Trying to send...",
                               date, self.metrics_count)
                self.log_metrics_flush_pause = True
            return True

        try:
            logger.debug("Flushing %d metrics to Graphite/carbon", self.metrics_count)
            if self.carbon.send_data():
                self.my_metrics = []
            else:
                logger.warning("Failed sending metrics to Graphite/carbon. "
                               "Inner stored metric: %d", self.metrics_count)
                if log:
                    logger.warning("Failed sending metrics to Graphite/carbon. "
                                   "Inner stored metric: %d", self.metrics_count)
                return False
            if self.log_metrics_flush_pause:
                logger.warning("Metrics flush restored. "
                               "Remaining stored metric: %d", self.metrics_count)
            self.last_failure = 0
            self.log_metrics_flush_pause = False
        except Exception as exp:  # pylint: disable=broad-except
            if not self.log_metrics_flush_pause:
                logger.warning("Failed sending metrics to Graphite/carbon. "
                               "Inner stored metric: %d", self.metrics_count)
            else:
                date = datetime.datetime.fromtimestamp(
                    self.last_failure).strftime(self.date_fmt)
                logger.warning("Metrics flush paused on connection error "
                               "(last failed: %s). "
                               "Inner stored metric: %d. Trying to send...",
                               date, self.metrics_count)

            logger.warning("Exception: %s", str(exp))
            self.last_failure = now
            return False
        return True
73930
def _submit_gauges_from_histogram(self, metric_name, metric, scraper_config, hostname=None):
        
        for sample in metric.samples:
            val = sample[self.SAMPLE_VALUE]
            if not self._is_value_valid(val):
                self.log.debug("Metric value is not supported for metric {}".format(sample[self.SAMPLE_NAME]))
                continue
            custom_hostname = self._get_hostname(hostname, sample, scraper_config)
            if sample[self.SAMPLE_NAME].endswith("_sum"):
                tags = self._metric_tags(metric_name, val, sample, scraper_config, hostname)
                self.gauge(
                    "{}.{}.sum".format(scraper_config['namespace'], metric_name),
                    val,
                    tags=tags,
                    hostname=custom_hostname,
                )
            elif sample[self.SAMPLE_NAME].endswith("_count"):
                tags = self._metric_tags(metric_name, val, sample, scraper_config, hostname)
                self.gauge(
                    "{}.{}.count".format(scraper_config['namespace'], metric_name),
                    val,
                    tags=tags,
                    hostname=custom_hostname,
                )
            elif (
                scraper_config['send_histograms_buckets']
                and sample[self.SAMPLE_NAME].endswith("_bucket")
                and "Inf" not in sample[self.SAMPLE_LABELS]["le"]
            ):
                sample[self.SAMPLE_LABELS]["le"] = float(sample[self.SAMPLE_LABELS]["le"])
                tags = self._metric_tags(metric_name, val, sample, scraper_config, hostname)
                self.gauge(
                    "{}.{}.count".format(scraper_config['namespace'], metric_name),
                    val,
                    tags=tags,
                    hostname=custom_hostname,
                )
1249138
def show_quota(self, project_id, **_params):
        """"""
        return self.get(self.quota_path % (project_id), params=_params)
985088
def get_metric(self, reset: bool) -> Union[float, Tuple[float, ...], Dict[str, float], Dict[str, List[float]]]:
        
        raise NotImplementedError
353619
private void registerMetrics(MetricGroup metricGroup) {
		metricGroup.gauge(NUMBER_OF_CHECKPOINTS_METRIC, new CheckpointsCounter());
		metricGroup.gauge(NUMBER_OF_IN_PROGRESS_CHECKPOINTS_METRIC, new InProgressCheckpointsCounter());
		metricGroup.gauge(NUMBER_OF_COMPLETED_CHECKPOINTS_METRIC, new CompletedCheckpointsCounter());
		metricGroup.gauge(NUMBER_OF_FAILED_CHECKPOINTS_METRIC, new FailedCheckpointsCounter());
		metricGroup.gauge(LATEST_RESTORED_CHECKPOINT_TIMESTAMP_METRIC, new LatestRestoredCheckpointTimestampGauge());
		metricGroup.gauge(LATEST_COMPLETED_CHECKPOINT_SIZE_METRIC, new LatestCompletedCheckpointSizeGauge());
		metricGroup.gauge(LATEST_COMPLETED_CHECKPOINT_DURATION_METRIC, new LatestCompletedCheckpointDurationGauge());
		metricGroup.gauge(LATEST_COMPLETED_CHECKPOINT_ALIGNMENT_BUFFERED_METRIC, new LatestCompletedCheckpointAlignmentBufferedGauge());
		metricGroup.gauge(LATEST_COMPLETED_CHECKPOINT_EXTERNAL_PATH_METRIC, new LatestCompletedCheckpointExternalPathGauge());
	}
695380
def metric(slug, num=1, category=None, expire=None, date=None):
    """"""
    get_r().metric(slug, num=num, category=category, expire=expire, date=date)
155319
def _check_queue(queue, kwargs):
    '''
    
    '''
    if queue:
        _wait(kwargs.get('__pub_jid'))
    else:
        conflict = running(concurrent=kwargs.get('concurrent', False))
        if conflict:
            __context__['retcode'] = 1
            return conflict
266599
def _match_metric(self, metric):
        
        if len(self._compiled_filters) == 0:
            return True
        for (collector, filter_regex) in self._compiled_filters:
            if collector != metric.getCollectorPath():
                continue
            if filter_regex.match(metric.getMetricPath()):
                return True
        return False
1225121
def check_quota(self):
        
        # Don't check on every write, that would be slow
        if self.quota_countdown > 0:
            self.quota_countdown -= 1
            return

        # Re-cache the quota after the countdown
        self.quota = self.get_library_metadata(ArcticLibraryBinding.QUOTA)
        if self.quota is None or self.quota == 0:
            self.quota = 0
            return

        # Figure out whether the user has exceeded their quota
        library = self.arctic[self.get_name()]
        stats = library.stats()

        def to_gigabytes(bytes_):
            return bytes_ / 1024. / 1024. / 1024.

        # Have we exceeded our quota?
        size = stats['totals']['size']
        count = stats['totals']['count']
        if size >= self.quota:
            raise QuotaExceededException("Mongo Quota Exceeded: %s %.3f / %.0f GB used" % (
                '.'.join([self.database_name, self.library]),
                to_gigabytes(size),
                to_gigabytes(self.quota)))

        # Quota not exceeded, print an informational message and return
        try:
            avg_size = size // count if count > 1 else 100 * 1024
            remaining = self.quota - size
            remaining_count = remaining / avg_size
            if remaining_count < 100 or float(remaining) / self.quota < 0.1:
                logger.warning("Mongo Quota: %s %.3f / %.0f GB used" % (
                    '.'.join([self.database_name, self.library]),
                    to_gigabytes(size),
                    to_gigabytes(self.quota)))
            else:
                logger.info("Mongo Quota: %s %.3f / %.0f GB used" % (
                    '.'.join([self.database_name, self.library]),
                    to_gigabytes(size),
                    to_gigabytes(self.quota)))

            # Set-up a timer to prevent us for checking for a few writes.
            # This will check every average half-life
            self.quota_countdown = int(max(remaining_count // 2, 1))
        except Exception as e:
            logger.warning("Encountered an exception while calculating quota statistics: %s" % str(e))
538181
def maybe_submit_measurement(self):
        
        if self.statsd:
            self.submit_statsd_measurements()
        if self.influxdb:
            self.submit_influxdb_measurement()
287492
def get_quota(self):
		''
		du, ds = op.itemgetter('used_bytes', 'max_bytes')((yield self()))
		defer.returnValue((ds - du, ds))
1229665
private void assertMaxTargetsPerManualAssignmentQuota(final Long distributionSetId,
            final int requestedTargetsCount) {
        QuotaHelper.assertAssignmentQuota(distributionSetId, requestedTargetsCount,
                quotaManagement.getMaxTargetsPerManualAssignment(), Target.class, DistributionSet.class, null);
    }