Return whether a metric is about a container or not.
        It can be about pods, or even higher levels in the cgroup hierarchy
        and we don't want to report on that.
        :param metric:
        :return: bool
760276
def _is_container_metric(labels):
        
        for lbl in CONTAINER_LABELS:
            if lbl == 'container_name':
                if lbl in labels:
                    if labels[lbl] == '' or labels[lbl] == 'POD':
                        return False
            if lbl not in labels:
                return False
        return True
873601
def _measurements(session_group, metric_name):
  
  for session_index, session in enumerate(session_group.sessions):
    metric_value = _find_metric_value(session, metric_name)
    if not metric_value:
      continue
    yield _Measurement(metric_value, session_index)
793350
def disable_metrics_collection(self, as_group, metrics=None):
        
        params = {'AutoScalingGroupName': as_group}

        if metrics:
            self.build_list_params(params, metrics, 'Metrics')
        return self.get_status('DisableMetricsCollection', params)
798563
def metric(cls, name, count, elapsed):
        

        if name is None:
            warnings.warn("Ignoring unnamed metric", stacklevel=3)
            return

        with cls.lock:
            if not cls.instances:
                # first call
                shutil.rmtree(cls.outdir, ignore_errors=True)
                os.makedirs(cls.outdir)

                if cls.dump_atexit: atexit.register(cls.dump)

            try:
                self = cls.instances[name]
            except KeyError:
                self = cls.instances[name] = cls(name)

            self.writer.writerow((count, "%f"%elapsed))
207725
def _process(self, metric):
        
        if not self.enabled:
            return
        try:
            try:
                self.lock.acquire()
                self.process(metric)
            except Exception:
                self.log.error(traceback.format_exc())
        finally:
            if self.lock.locked():
                self.lock.release()
306995
def metrics_api(self):
        
        if self._metrics_api is None:
            if self._use_grpc:
                self._metrics_api = _gapic.make_metrics_api(self)
            else:
                self._metrics_api = JSONMetricsAPI(self)
        return self._metrics_api
294572
def _process_metric(self, data, metric, xtype, path, xform=None, tags=None, hostname=None):
        
        value = data

        # Traverse the nested dictionaries
        for key in path.split('.'):
            if value is not None:
                value = value.get(key)
            else:
                break

        if value is not None:
            if xform:
                value = xform(value)
            if xtype == "gauge":
                self.gauge(metric, value, tags=tags, hostname=hostname)
            else:
                self.rate(metric, value, tags=tags, hostname=hostname)
        else:
            self.log.debug("Metric not found: %s -> %s", path, metric)
340966
function shipMetrics (metric) {
    try {
      this.emit('metric', metric)
      this.spmSender.collectMetric(metric)
    } catch (ex) {
      logger.error('Error in shipMetrics' + ex.stack)
    }
  }
171907
def query_metric_tags(self, metric_type, metric_id):
        
        definition = self._get(self._get_metrics_tags_url(self._get_metrics_single_url(metric_type, metric_id)))
        return definition
78085
def add_metric(self, metric: float) -> None:
        
        new_best = ((self._best_so_far is None) or
                    (self._should_decrease and metric < self._best_so_far) or
                    (not self._should_decrease and metric > self._best_so_far))

        if new_best:
            self.best_epoch = self._epoch_number
            self._is_best_so_far = True
            self._best_so_far = metric
            self._epochs_with_no_improvement = 0
        else:
            self._is_best_so_far = False
            self._epochs_with_no_improvement += 1
        self._epoch_number += 1
411232
def _get_metrics_to_collect(self, instance_key, additional_metrics):
        
        if instance_key not in self.metrics_to_collect_by_instance:
            self.metrics_to_collect_by_instance[instance_key] = self._build_metric_list_to_collect(additional_metrics)
        return self.metrics_to_collect_by_instance[instance_key]
969311
def sorted_metrics(metrics, hierarchy)
      # 'hierarchy' is a hash where the keys are metric names and the values
      # are arrays with the names of the children metrics. Only metrics with
      # children and with at least one usage limit appear as keys.
      parent_metrics = hierarchy.keys
      child_metrics = metrics - parent_metrics
      parent_metrics + child_metrics
    end
897138
def get_metric_by_name(self, metric_name, **kwargs):
        
        return self._get_object_by_name(self._METRIC_ENDPOINT_SUFFIX,
                                        metric_name,
                                        **kwargs)
75587
def show_metrics(metrics, all_branches=False, all_tags=False):
    
    for branch, val in metrics.items():
        if all_branches or all_tags:
            logger.info("{branch}:".format(branch=branch))

        for fname, metric in val.items():
            lines = metric if type(metric) is list else metric.splitlines()

            if len(lines) > 1:
                logger.info("\t{fname}:".format(fname=fname))

                for line in lines:
                    logger.info("\t\t{content}".format(content=line))

            else:
                logger.info("\t{}: {}".format(fname, metric))
665981
def check(self, instance):
        """"""
        if not self.init_success:
            # Initialization can fail if cgroups are not ready or docker daemon is down. So we retry if needed
            # https://github.com/DataDog/dd-agent/issues/1896
            self.init()

            try:
                if self.docker_util.client is None:
                    message = "Unable to connect to Docker daemon"
                    self.service_check(SERVICE_CHECK_NAME, AgentCheck.CRITICAL,
                                       message=message, tags=self.custom_tags)
                    return
            except Exception as ex:
                self.service_check(SERVICE_CHECK_NAME, AgentCheck.CRITICAL,
                                   message=str(ex), tags=self.custom_tags)
                return

            if not self.init_success:
                # Initialization failed, will try later
                return

        try:
            # Report image metrics
            if self.collect_image_stats:
                self._count_and_weigh_images()

            if Platform.is_k8s():
                self.kube_pod_tags = {}
                if self.kubeutil:
                    try:
                        self.kube_pod_tags = self.kubeutil.get_kube_pod_tags()
                    except Exception as e:
                        self.log.warning('Could not retrieve kubernetes labels: %s' % str(e))

            # containers running with custom cgroups?
            custom_cgroups = _is_affirmative(instance.get('custom_cgroups', False))

            # Get the list of containers and the index of their names
            health_service_checks = True if self.whitelist_patterns else False
            containers_by_id = self._get_and_count_containers(custom_cgroups, health_service_checks)
            containers_by_id = self._crawl_container_pids(containers_by_id, custom_cgroups)

            # Send events from Docker API
            if self.collect_events or self._service_discovery or not self._disable_net_metrics or self.collect_exit_codes:
                self._process_events(containers_by_id)

            # Report performance container metrics (cpu, mem, net, io)
            self._report_performance_metrics(containers_by_id)

            if self.collect_container_size:
                self._report_container_size(containers_by_id)

            if self.collect_container_count:
                self._report_container_count(containers_by_id)

            if self.collect_volume_count:
                self._report_volume_count()

            # Collect disk stats from Docker info command
            if self.collect_disk_stats:
                self._report_disk_stats()

            if health_service_checks:
                self._send_container_healthcheck_sc(containers_by_id)
        except:
            self.log.exception("Docker_daemon check failed")
            self.warning("Check failed. Will retry at next iteration")

        if self.capped_metrics:
            self.filter_capped_metrics()
547085
def is_containerized() -> bool:
    '''
    
    '''
    try:
        cginfo = Path('/proc/self/cgroup').read_text()
        if '/docker/' in cginfo or '/lxc/' in cginfo:
            return True
    except IOError:
        return False
699481
def metrics_asserted_pct(self):
        
        num_metrics = len(self._metrics)
        num_asserted = len(self._asserted)

        if num_metrics == 0:
            if num_asserted == 0:
                return 100
            else:
                return 0

        return num_asserted / num_metrics * 100