@staticmethod
  def Aggregate(varz, metrics, key_selector=None):
    """Aggregate varz

    Args:
      varz - The varz dictionary to aggregate, typically VarzReceiver.VARZ_DATA.
      metrics - The metric metadata dictionary, typically VarzReceiver.VARZ_METRICS
      key_selector - A function to select the key to aggregate by given a
                     (endpoint, service, host, client) tuple.  By default this returns
                     the service.
    Returns:
      A dictionary of metric -> service -> aggregate.
    """
    if not key_selector:
      key_selector = DefaultKeySelector

    agg = defaultdict(dict)
    now = LOW_RESOLUTION_TIME_SOURCE.now
    for metric in varz.keys():
      if metric not in metrics:
        continue
      varz_type = metrics[metric]
      assert isinstance(varz_type, int), varz_type
      metric_agg = agg[metric]
      gevent.sleep(0)
      for source in varz[metric].keys():
        key = key_selector(source)
        data = varz[metric][source]
        if key not in metric_agg:
          metric_agg[key] = VarzAggregator._Agg()
          if isinstance(data, _SampleSet):
            metric_agg[key].work = []

        if isinstance(data, _SampleSet):
          if (now - data.last_update) < VarzAggregator.MAX_AGG_AGE:
            metric_agg[key].work.append(data)
            metric_agg[key].count += 1
        else:
          metric_agg[key].work += data
          metric_agg[key].count += 1
      if varz_type in (VarzType.AggregateTimer, VarzType.Counter,
                       VarzType.Gauge, VarzType.Rate):
        for source_agg in metric_agg.values():
          source_agg.total = source_agg.work
      elif varz_type in (VarzType.AverageTimer, VarzType.AverageRate):
        for source_agg in metric_agg.values():
          if source_agg.count > 0:
            pct_sample = 1.0 / source_agg.count
            values = [VarzAggregator._Downsample(v.data, int(len(v.data) * pct_sample))
                      for v in source_agg.work]
            values = sorted(itertools.chain(*values))
          else:
            values = []
          source_agg.total = [
            VarzAggregator.CalculatePercentile(values, pct)
            for pct in VarzReceiver.VARZ_PERCENTILES
            ]
          if values:
            source_agg.total.insert(0, sum(values) / float(len(values)))
          else:
            source_agg.total.insert(0, 0)
          source_agg.work = None
      else:
        for source_agg in metric_agg.values():
          source_agg.total = float(source_agg.work) / source_agg.count

    return agg
dataset/ETHPy150Open steveniemitz/scales/scales/varz.py/VarzAggregator.Aggregate/original