// metricsDiff() returns set names for removal
180211
func metricsDiff(role Role, w []string) []string {
	b := []string{}
	s := make(map[string]bool)

	if len(w) == 0 {
		return b
	}

	for _, v := range w {
		s[v] = true
	}

	for _, d := range allMetrics[role] {
		if _, ok := s[d]; !ok {
			b = append(b, d)
		}
	}

	return b
}
1006096
func getFilteredMetrics(c *CloudWatch) ([]filteredMetric, error) {
	if c.metricCache != nil && c.metricCache.isValid() {
		return c.metricCache.metrics, nil
	}

	fMetrics := []filteredMetric{}

	// check for provided metric filter
	if c.Metrics != nil {
		for _, m := range c.Metrics {
			metrics := []*cloudwatch.Metric{}
			if !hasWilcard(m.Dimensions) {
				dimensions := make([]*cloudwatch.Dimension, len(m.Dimensions))
				for k, d := range m.Dimensions {
					dimensions[k] = &cloudwatch.Dimension{
						Name:  aws.String(d.Name),
						Value: aws.String(d.Value),
					}
				}
				for _, name := range m.MetricNames {
					metrics = append(metrics, &cloudwatch.Metric{
						Namespace:  aws.String(c.Namespace),
						MetricName: aws.String(name),
						Dimensions: dimensions,
					})
				}
			} else {
				allMetrics, err := c.fetchNamespaceMetrics()
				if err != nil {
					return nil, err
				}
				for _, name := range m.MetricNames {
					for _, metric := range allMetrics {
						if isSelected(name, metric, m.Dimensions) {
							metrics = append(metrics, &cloudwatch.Metric{
								Namespace:  aws.String(c.Namespace),
								MetricName: aws.String(name),
								Dimensions: metric.Dimensions,
							})
						}
					}
				}
			}

			if m.StatisticExclude == nil {
				m.StatisticExclude = &c.StatisticExclude
			}
			if m.StatisticInclude == nil {
				m.StatisticInclude = &c.StatisticInclude
			}
			statFilter, err := filter.NewIncludeExcludeFilter(*m.StatisticInclude, *m.StatisticExclude)
			if err != nil {
				return nil, err
			}

			fMetrics = append(fMetrics, filteredMetric{
				metrics:    metrics,
				statFilter: statFilter,
			})
		}
	} else {
		metrics, err := c.fetchNamespaceMetrics()
		if err != nil {
			return nil, err
		}

		fMetrics = []filteredMetric{{
			metrics:    metrics,
			statFilter: c.statFilter,
		}}
	}

	c.metricCache = &metricCache{
		metrics: fMetrics,
		built:   time.Now(),
		ttl:     c.CacheTTL.Duration,
	}

	return fMetrics, nil
}
634358
func NewMetricExtractionSink(mw []Processor, indicatorTimerName, objectiveTimerName string, cl *trace.Client, log *logrus.Logger) (DerivedMetricsSink, error) {
	return &metricExtractionSink{
		workers:                mw,
		indicatorSpanTimerName: indicatorTimerName,
		objectiveSpanTimerName: objectiveTimerName,
		traceClient:            cl,
		log:                    log,
	}, nil
}
609538
func (tracerOptions) Metrics(m *Metrics) TracerOption {
	return func(tracer *Tracer) {
		tracer.metrics = *m
	}
}
606615
func (m *Meta) SetSchemaDiff(diff *model.SchemaDiff) error {
	data, err := json.Marshal(diff)
	if err != nil {
		return errors.Trace(err)
	}
	diffKey := m.schemaDiffKey(diff.Version)
	startTime := time.Now()
	err = m.txn.Set(diffKey, data)
	metrics.MetaHistogram.WithLabelValues(metrics.SetSchemaDiff, metrics.RetLabel(err)).Observe(time.Since(startTime).Seconds())
	return errors.Trace(err)
}
1262040
func SymDiff(data sort.Interface, pivot int) (size int) {
	// BUG(extemporalgenome): SymDiff currently uses a multi-pass implementation

	i := Inter(data, pivot)
	l := data.Len()
	b := boundspan{data, span{i, l}}
	sort.Sort(b)
	size = Uniq(b)
	slide(data, 0, i, size)
	l = i + size
	sort.Sort(boundspan{data, span{size, l}})
	return Diff(data, size)
}
785936
func (m *Metrics) RemoveZone(z string) {
	m.zoneMu.Lock()
	delete(m.zoneMap, z)
	m.zoneNames = keys(m.zoneMap)
	m.zoneMu.Unlock()
}
516049
func (wfc *WorkflowController) MetricsServer(ctx context.Context) {
	if wfc.Config.MetricsConfig.Enabled {
		informer := util.NewWorkflowInformer(wfc.restConfig, wfc.Config.Namespace, workflowMetricsResyncPeriod, wfc.tweakWorkflowMetricslist)
		go informer.Run(ctx.Done())
		registry := metrics.NewWorkflowRegistry(informer)
		metrics.RunServer(ctx, wfc.Config.MetricsConfig, registry)
	}
}
816390
func (c *Client) GetMetricVersions(ns string) *GetMetricsResult {
	r := &GetMetricsResult{}
	q := fmt.Sprintf("/metrics?ns=%s", ns)
	resp, err := c.do("GET", q, ContentTypeJSON)
	if err != nil {
		return &GetMetricsResult{Err: err}
	}

	switch resp.Meta.Type {
	case rbody.MetricsReturnedType:
		mc := resp.Body.(*rbody.MetricsReturned)
		r.Catalog = convertCatalog(mc)
	case rbody.ErrorType:
		r.Err = resp.Body.(*rbody.Error)
	default:
		r.Err = ErrAPIResponseMetaType
	}
	return r
}
1172135
func Metrics() []telegraf.Metric {
	registry.mu.Lock()
	now := time.Now()
	metrics := make([]telegraf.Metric, len(registry.stats))
	i := 0
	for _, stats := range registry.stats {
		if len(stats) > 0 {
			var tags map[string]string
			var name string
			fields := map[string]interface{}{}
			j := 0
			for fieldname, stat := range stats {
				if j == 0 {
					tags = stat.Tags()
					name = stat.Name()
				}
				fields[fieldname] = stat.Get()
				j++
			}
			metric, err := metric.New(name, tags, fields, now)
			if err != nil {
				log.Printf("E! Error creating selfstat metric: %s", err)
				continue
			}
			metrics[i] = metric
			i++
		}
	}
	registry.mu.Unlock()
	return metrics
}
786033
func CalculateDiff(options *Options) (*Result, error) {
	baseVersionQuery := models.GetDashboardVersionQuery{
		DashboardId: options.Base.DashboardId,
		Version:     options.Base.Version,
		OrgId:       options.OrgId,
	}

	if err := bus.Dispatch(&baseVersionQuery); err != nil {
		return nil, err
	}

	newVersionQuery := models.GetDashboardVersionQuery{
		DashboardId: options.New.DashboardId,
		Version:     options.New.Version,
		OrgId:       options.OrgId,
	}

	if err := bus.Dispatch(&newVersionQuery); err != nil {
		return nil, err
	}

	baseData := baseVersionQuery.Result.Data
	newData := newVersionQuery.Result.Data

	left, jsonDiff, err := getDiff(baseData, newData)
	if err != nil {
		return nil, err
	}

	result := &Result{}

	switch options.DiffType {
	case DiffDelta:

		deltaOutput, err := deltaFormatter.NewDeltaFormatter().Format(jsonDiff)
		if err != nil {
			return nil, err
		}
		result.Delta = []byte(deltaOutput)

	case DiffJSON:
		jsonOutput, err := NewJSONFormatter(left).Format(jsonDiff)
		if err != nil {
			return nil, err
		}
		result.Delta = []byte(jsonOutput)

	case DiffBasic:
		basicOutput, err := NewBasicFormatter(left).Format(jsonDiff)
		if err != nil {
			return nil, err
		}
		result.Delta = basicOutput

	default:
		return nil, ErrUnsupportedDiffType
	}

	return result, nil
}
815322
func (m *MetricsService) Delete(name string) (*http.Response, error) {
	u := fmt.Sprintf("metrics/%s", name)
	req, err := m.client.NewRequest("DELETE", u, nil)
	if err != nil {
		return nil, err
	}

	return m.client.Do(req, nil)
}
1314599
func filterServerMetrics(filter string) (map[int]*prometheus.Desc, error) {
	metrics := map[int]*prometheus.Desc{}
	if len(filter) == 0 {
		return metrics, nil
	}

	selected := map[int]struct{}{}
	for _, f := range strings.Split(filter, ",") {
		field, err := strconv.Atoi(f)
		if err != nil {
			return nil, fmt.Errorf("invalid server metric field number: %v", f)
		}
		selected[field] = struct{}{}
	}

	for field, metric := range serverMetrics {
		if _, ok := selected[field]; ok {
			metrics[field] = metric
		}
	}
	return metrics, nil
}
625707
func serviceDiff(old, new *Service, contextual bool) *ObjectDiff {
	diff := &ObjectDiff{Type: DiffTypeNone, Name: "Service"}
	var oldPrimitiveFlat, newPrimitiveFlat map[string]string

	if reflect.DeepEqual(old, new) {
		return nil
	} else if old == nil {
		old = &Service{}
		diff.Type = DiffTypeAdded
		newPrimitiveFlat = flatmap.Flatten(new, nil, true)
	} else if new == nil {
		new = &Service{}
		diff.Type = DiffTypeDeleted
		oldPrimitiveFlat = flatmap.Flatten(old, nil, true)
	} else {
		diff.Type = DiffTypeEdited
		oldPrimitiveFlat = flatmap.Flatten(old, nil, true)
		newPrimitiveFlat = flatmap.Flatten(new, nil, true)
	}

	// Diff the primitive fields.
	diff.Fields = fieldDiffs(oldPrimitiveFlat, newPrimitiveFlat, contextual)

	if setDiff := stringSetDiff(old.CanaryTags, new.CanaryTags, "CanaryTags", contextual); setDiff != nil {
		diff.Objects = append(diff.Objects, setDiff)
	}

	// Tag diffs
	if setDiff := stringSetDiff(old.Tags, new.Tags, "Tags", contextual); setDiff != nil {
		diff.Objects = append(diff.Objects, setDiff)
	}

	// Checks diffs
	if cDiffs := serviceCheckDiffs(old.Checks, new.Checks, contextual); cDiffs != nil {
		diff.Objects = append(diff.Objects, cDiffs...)
	}

	return diff
}
1274768
func (builder *MetricBuilder) Metric(metric Metric) *MetricMetricBuilder {
	newMetric := MetricMetricBuilder{
		Metric{
			ID:          metric.ID,
			Name:        metric.Name,
			Description: metric.Description,
			Counter:     metric.Counter,
			CounterMax:  metric.CounterMax,
			ResetValue:  metric.ResetValue,
			Unit:        metric.Unit,
		},
		make(map[string][]string),
	}
	builder.metrics = append(builder.metrics, newMetric)
	return &builder.metrics[len(builder.metrics)-1]
}
762675
func (db *DB) SDiff(keys ...[]byte) ([][]byte, error) {
	v, err := db.sDiffGeneric(keys...)
	return v, err
}
641181
func (m *MetricBatch) UniqueMetrics() []Metric {
	metrics := m.Metrics()
	sort.Sort(byTime(metrics))
	uniq := map[string]Metric{}
	for _, m := range metrics {
		uniq[fmt.Sprintf("%s-%s", m.Key, labelsKey(m.Labels))] = m
	}
	results := make([]Metric, len(uniq))
	i := 0
	for _, m := range uniq {
		results[i] = m
		i++
	}
	sort.Sort(byKey(results))
	return results
}