// Create and initialize a timeSeriesConf for a given GCP metric type with
// defaults taken from the gcp_stackdriver plugin configuration.
19339
func (s *Stackdriver) newTimeSeriesConf(
	metricType string, startTime, endTime time.Time,
) *timeSeriesConf {
	filter := s.newListTimeSeriesFilter(metricType)
	interval := &monitoringpb.TimeInterval{
		EndTime:   &googlepbts.Timestamp{Seconds: endTime.Unix()},
		StartTime: &googlepbts.Timestamp{Seconds: startTime.Unix()},
	}
	tsReq := &monitoringpb.ListTimeSeriesRequest{
		Name:     monitoring.MetricProjectPath(s.Project),
		Filter:   filter,
		Interval: interval,
	}
	cfg := &timeSeriesConf{
		measurement:           metricType,
		fieldKey:              "value",
		listTimeSeriesRequest: tsReq,
	}

	// GCP metric types have at least one slash, but we'll be defensive anyway.
	slashIdx := strings.LastIndex(metricType, "/")
	if slashIdx > 0 {
		cfg.measurement = metricType[:slashIdx]
		cfg.fieldKey = metricType[slashIdx+1:]
	}

	return cfg
}
675732
func Init(m interface{}, factory Factory, globalTags map[string]string) error {
	// Allow user to opt out of reporting metrics by passing in nil.
	if factory == nil {
		factory = NullFactory
	}

	counterPtrType := reflect.TypeOf((*Counter)(nil)).Elem()
	gaugePtrType := reflect.TypeOf((*Gauge)(nil)).Elem()
	timerPtrType := reflect.TypeOf((*Timer)(nil)).Elem()
	histogramPtrType := reflect.TypeOf((*Histogram)(nil)).Elem()

	v := reflect.ValueOf(m).Elem()
	t := v.Type()
	for i := 0; i < t.NumField(); i++ {
		tags := make(map[string]string)
		for k, v := range globalTags {
			tags[k] = v
		}
		var buckets []float64
		field := t.Field(i)
		metric := field.Tag.Get("metric")
		if metric == "" {
			return fmt.Errorf("Field %s is missing a tag 'metric'", field.Name)
		}
		if tagString := field.Tag.Get("tags"); tagString != "" {
			tagPairs := strings.Split(tagString, ",")
			for _, tagPair := range tagPairs {
				tag := strings.Split(tagPair, "=")
				if len(tag) != 2 {
					return fmt.Errorf(
						"Field [%s]: Tag [%s] is not of the form key=value in 'tags' string [%s]",
						field.Name, tagPair, tagString)
				}
				tags[tag[0]] = tag[1]
			}
		}
		if bucketString := field.Tag.Get("buckets"); bucketString != "" {
			if field.Type.AssignableTo(timerPtrType) {
				// TODO: Parse timer duration buckets
				return fmt.Errorf(
					"Field [%s]: Buckets are not currently initialized for timer metrics",
					field.Name)
			} else if field.Type.AssignableTo(histogramPtrType) {
				bucketValues := strings.Split(bucketString, ",")
				for _, bucket := range bucketValues {
					b, err := strconv.ParseFloat(bucket, 64)
					if err != nil {
						return fmt.Errorf(
							"Field [%s]: Bucket [%s] could not be converted to float64 in 'buckets' string [%s]",
							field.Name, bucket, bucketString)
					}
					buckets = append(buckets, b)
				}
			} else {
				return fmt.Errorf(
					"Field [%s]: Buckets should only be defined for Timer and Histogram metric types",
					field.Name)
			}
		}
		help := field.Tag.Get("help")
		var obj interface{}
		if field.Type.AssignableTo(counterPtrType) {
			obj = factory.Counter(Options{
				Name: metric,
				Tags: tags,
				Help: help,
			})
		} else if field.Type.AssignableTo(gaugePtrType) {
			obj = factory.Gauge(Options{
				Name: metric,
				Tags: tags,
				Help: help,
			})
		} else if field.Type.AssignableTo(timerPtrType) {
			// TODO: Add buckets once parsed (see TODO above)
			obj = factory.Timer(TimerOptions{
				Name: metric,
				Tags: tags,
				Help: help,
			})
		} else if field.Type.AssignableTo(histogramPtrType) {
			obj = factory.Histogram(HistogramOptions{
				Name:    metric,
				Tags:    tags,
				Help:    help,
				Buckets: buckets,
			})
		} else {
			return fmt.Errorf(
				"Field %s is not a pointer to timer, gauge, or counter",
				field.Name)
		}
		v.Field(i).Set(reflect.ValueOf(obj))
	}
	return nil
}
484593
func (p IndexFiles) MeasurementSeriesIDIterator(name []byte) tsdb.SeriesIDIterator {
	a := make([]tsdb.SeriesIDIterator, 0, len(p))
	for _, f := range p {
		itr := f.MeasurementSeriesIDIterator(name)
		if itr == nil {
			continue
		}
		a = append(a, itr)
	}
	return tsdb.MergeSeriesIDIterators(a...)
}
1244204
func InitializeGraphiteCollector(config *GraphiteCollectorConfig) {
	go metrics.Graphite(metrics.DefaultRegistry, config.TickInterval, config.Prefix, config.GraphiteAddr)
}
287858
func Convert_v1_MetricSpec_To_autoscaling_MetricSpec(in *v1.MetricSpec, out *autoscaling.MetricSpec, s conversion.Scope) error {
	return autoConvert_v1_MetricSpec_To_autoscaling_MetricSpec(in, out, s)
}
774075
func NewMetrics(conf *metrics.Config, sink metrics.MetricSink) (err error) {
	m, err := metrics.NewGlobal(conf, sink)
	SetMetrics(m)

	return nil
}
1065014
func (tsdbSink *openTSDBSink) metricToPoint(name string, value core.MetricValue, timestamp time.Time, labels map[string]string) opentsdbclient.DataPoint {
	seriesName := strings.Replace(toValidOpenTsdbName(name), "/", "_", -1)

	if value.MetricType.String() != "" {
		seriesName = fmt.Sprintf("%s_%s", seriesName, value.MetricType.String())
	}

	datapoint := opentsdbclient.DataPoint{
		Metric:    seriesName,
		Tags:      make(map[string]string, len(labels)),
		Timestamp: timestamp.Unix(),
	}
	if value.ValueType == core.ValueInt64 {
		datapoint.Value = value.IntValue
	} else {
		datapoint.Value = value.FloatValue
	}

	for key, value := range labels {
		key = toValidOpenTsdbName(key)
		value = toValidOpenTsdbName(value)

		if value != "" {
			datapoint.Tags[key] = value
		}
	}

	tsdbSink.putDefaultTags(&datapoint)
	return datapoint
}
885012
func (tm *TrustMetric) Init(hist MetricHistoryJSON) {
	// Restore the number of time intervals we have previously tracked
	if hist.NumIntervals > tm.maxIntervals {
		hist.NumIntervals = tm.maxIntervals
	}
	tm.numIntervals = hist.NumIntervals
	// Restore the history and its current size
	if len(hist.History) > tm.historyMaxSize {
		// Keep the history no larger than historyMaxSize
		last := len(hist.History) - tm.historyMaxSize
		hist.History = hist.History[last:]
	}
	tm.history = hist.History
	tm.historySize = len(tm.history)
	// Create the history weight values and weight sum
	for i := 1; i <= tm.numIntervals; i++ {
		x := math.Pow(defaultHistoryDataWeight, float64(i)) // Optimistic weight
		tm.historyWeights = append(tm.historyWeights, x)
	}

	for _, v := range tm.historyWeights {
		tm.historyWeightSum += v
	}
	// Calculate the history value based on the loaded history data
	tm.historyValue = tm.calcHistoryValue()
}
600410
func Convert_autoscaling_MetricSpec_To_v1_MetricSpec(in *autoscaling.MetricSpec, out *v1.MetricSpec, s conversion.Scope) error {
	return autoConvert_autoscaling_MetricSpec_To_v1_MetricSpec(in, out, s)
}
609240
func NewExtendedMetricsReporter(
	scope tally.Scope,
	reportInterval time.Duration,
	metricsType ExtendedMetricsType,
) Reporter {
	r := new(extendedMetricsReporter)
	r.metricsType = metricsType
	r.init(reportInterval, func() {
		r.runtime.report(r.metricsType)
		if r.metricsType >= ModerateExtendedMetrics {
			r.process.report()
		}
	})
	if r.metricsType == NoExtendedMetrics {
		return r
	}

	runtimeScope := scope.SubScope("runtime")
	processScope := scope.SubScope("process")
	r.runtime.NumGoRoutines = runtimeScope.Gauge("num-goroutines")
	r.runtime.GoMaxProcs = runtimeScope.Gauge("gomaxprocs")
	r.process.NumFDs = processScope.Gauge("num-fds")
	r.process.NumFDErrors = processScope.Counter("num-fd-errors")
	r.process.pid = os.Getpid()
	if r.metricsType < DetailedExtendedMetrics {
		return r
	}

	var memstats runtime.MemStats
	runtime.ReadMemStats(&memstats)
	memoryScope := runtimeScope.SubScope("memory")
	r.runtime.MemoryAllocated = memoryScope.Gauge("allocated")
	r.runtime.MemoryHeap = memoryScope.Gauge("heap")
	r.runtime.MemoryHeapIdle = memoryScope.Gauge("heapidle")
	r.runtime.MemoryHeapInuse = memoryScope.Gauge("heapinuse")
	r.runtime.MemoryStack = memoryScope.Gauge("stack")
	r.runtime.GCCPUFraction = memoryScope.Gauge("gc-cpu-fraction")
	r.runtime.NumGC = memoryScope.Counter("num-gc")
	r.runtime.GcPauseMs = memoryScope.Timer("gc-pause-ms")
	r.runtime.lastNumGC = memstats.NumGC

	return r
}
1106393
func init() {
	cloudFormationStackTemplateMap = make(map[string]*gocf.Template)
	rand.Seed(time.Now().Unix())
}
11719
func (s *GetTimeSeriesServiceStatisticsOutput) SetTimeSeriesServiceStatistics(v []*TimeSeriesServiceStatistics) *GetTimeSeriesServiceStatisticsOutput {
	s.TimeSeriesServiceStatistics = v
	return s
}
288939
func (m *metricCollectorRegistry) InitializeMetricCollectors(name string) []MetricCollector {
	m.lock.RLock()
	defer m.lock.RUnlock()

	metrics := make([]MetricCollector, len(m.registry))
	for i, metricCollectorInitializer := range m.registry {
		metrics[i] = metricCollectorInitializer(name)
	}
	return metrics
}
1131701
func NewMetricType(namespace core.Namespace, timestamp time.Time, tags map[string]string, unit string, data interface{}) *MetricType {
	return &MetricType{
		Namespace_:          namespace,
		Tags_:               tags,
		Data_:               data,
		Timestamp_:          timestamp,
		LastAdvertisedTime_: timestamp,
		Unit_:               unit,
	}
}
40807
func (_m *APIClient) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error) {
	ret := _m.Called(ctx, config)

	var r0 types.ConfigCreateResponse
	if rf, ok := ret.Get(0).(func(context.Context, swarm.ConfigSpec) types.ConfigCreateResponse); ok {
		r0 = rf(ctx, config)
	} else {
		r0 = ret.Get(0).(types.ConfigCreateResponse)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, swarm.ConfigSpec) error); ok {
		r1 = rf(ctx, config)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
1268190
func New(conf *Config, sink MetricSink) (*Metrics, error) {
	met := &Metrics{}
	met.Config = *conf
	met.sink = sink
	met.UpdateFilterAndLabels(conf.AllowedPrefixes, conf.BlockedPrefixes, conf.AllowedLabels, conf.BlockedLabels)

	// Start the runtime collector
	if conf.EnableRuntimeMetrics {
		go met.collectStats()
	}
	return met, nil
}
995084
func (t *seriesPartitionTracker) AddSeriesCreated(n uint64) {
	if !t.enabled {
		return
	}

	labels := t.Labels()
	t.metrics.SeriesCreated.With(labels).Add(float64(n))
}