// GetMeasurements returns measurements in a specified database, paginated by
// optional limit and offset. If no limit or offset is provided, it defaults to
// a limit of 100 measurements with no offset.
486872
func (c *Client) GetMeasurements(ctx context.Context, db string, limit, offset int) ([]chronograf.Measurement, error) {
	span, ctx := tracing.StartSpanFromContext(ctx)
	defer span.Finish()

	return c.showMeasurements(ctx, db, limit, offset)
}
718760
func (t *dbTables) getLimitSQL(mi *modelInfo, offset int64, limit int64) (limits string) {
	if limit == 0 {
		limit = int64(DefaultRowsLimit)
	}
	if limit < 0 {
		// no limit
		if offset > 0 {
			maxLimit := t.base.MaxLimit()
			if maxLimit == 0 {
				limits = fmt.Sprintf("OFFSET %d", offset)
			} else {
				limits = fmt.Sprintf("LIMIT %d OFFSET %d", maxLimit, offset)
			}
		}
	} else if offset <= 0 {
		limits = fmt.Sprintf("LIMIT %d", limit)
	} else {
		limits = fmt.Sprintf("LIMIT %d OFFSET %d", limit, offset)
	}
	return
}
1154877
func (h *Handler) HandleMeasures(mtime time.Time, measures ...stats.Measure) {
	cache := handleMetricPool.Get().(*handleMetricCache)

	for _, m := range measures {
		scope := h.trimPrefix(m.Name)

		cache.labels = cache.labels[:0]
		cache.labels = cache.labels.appendTags(m.Tags...)

		for _, f := range m.Fields {
			var buckets []stats.Value
			var mtype = typeOf(f.Type())

			if mtype == histogram {
				k := stats.Key{Measure: m.Name, Field: f.Name}

				if b := h.Buckets; b != nil {
					buckets = b[k]
				} else {
					buckets = stats.Buckets[k]
				}
			}

			h.metrics.update(metric{
				mtype:  mtype,
				scope:  scope,
				name:   f.Name,
				value:  valueOf(f.Value),
				time:   mtime,
				labels: cache.labels,
			}, buckets)
		}

		for i := range cache.labels {
			cache.labels[i] = label{}
		}
	}

	handleMetricPool.Put(cache)

	// Every 10K updates we cleanup the metric store of outdated entries to
	// having memory leaks if the program has generated metrics for a pair of
	// metric name and labels that won't be seen again.
	if (atomic.AddUint64(&h.opcount, 1) % 10000) == 0 {
		h.metrics.cleanup(time.Now().Add(-h.timeout()))
	}
}
1102539
func (c *randomEvictedCache) Get(key Measurable) (data Measurable, ok bool) {
	c.mu.RLock()
	defer c.mu.RUnlock()
	memoized, ok := c.data[key]
	if !ok {
		return nil, false
	}
	return memoized.m, ok
}
1080967
func (b *stdBackend) BeginMeasuring(id string) Measuring {
	if b.etmFilter != nil && !b.etmFilter(id) {
		return &stdMeasuring{}
	}
	return &stdMeasuring{b, id, time.Now(), 0}
}
469115
func scanMeasurement(buf []byte, i int) (int, int, error) {
	// Check first byte of measurement, anything except a comma is fine.
	// It can't be a space, since whitespace is stripped prior to this
	// function call.
	if i >= len(buf) || buf[i] == ',' {
		return -1, i, fmt.Errorf("missing measurement")
	}

	for {
		i++
		if i >= len(buf) {
			// cpu
			return -1, i, fmt.Errorf("missing fields")
		}

		if buf[i-1] == '\\' {
			// Skip character (it's escaped).
			continue
		}

		// Unescaped comma; move onto scanning the tags.
		if buf[i] == ',' {
			return tagKeyState, i + 1, nil
		}

		// Unescaped space; move onto scanning the fields.
		if buf[i] == ' ' {
			// cpu value=1.0
			return fieldsState, i, nil
		}
	}
}
329610
func MergeMeasurementIterators(itrs ...MeasurementIterator) MeasurementIterator {
	if len(itrs) == 0 {
		return nil
	}

	return &measurementMergeIterator{
		e:    make(measurementMergeElem, 0, len(itrs)),
		buf:  make([]MeasurementElem, len(itrs)),
		itrs: itrs,
	}
}
173351
func (c *CloudWatch) getDataQueries(filteredMetrics []filteredMetric) ([]*cloudwatch.MetricDataQuery, error) {
	if c.metricCache != nil && c.metricCache.queries != nil && c.metricCache.isValid() {
		return c.metricCache.queries, nil
	}

	c.queryDimensions = map[string]*map[string]string{}

	dataQueries := []*cloudwatch.MetricDataQuery{}
	for i, filtered := range filteredMetrics {
		for j, metric := range filtered.metrics {
			id := strconv.Itoa(j) + "_" + strconv.Itoa(i)
			dimension := ctod(metric.Dimensions)
			if filtered.statFilter.Match("average") {
				c.queryDimensions["average_"+id] = dimension
				dataQueries = append(dataQueries, &cloudwatch.MetricDataQuery{
					Id:    aws.String("average_" + id),
					Label: aws.String(snakeCase(*metric.MetricName + "_average")),
					MetricStat: &cloudwatch.MetricStat{
						Metric: metric,
						Period: aws.Int64(int64(c.Period.Duration.Seconds())),
						Stat:   aws.String(cloudwatch.StatisticAverage),
					},
				})
			}
			if filtered.statFilter.Match("maximum") {
				c.queryDimensions["maximum_"+id] = dimension
				dataQueries = append(dataQueries, &cloudwatch.MetricDataQuery{
					Id:    aws.String("maximum_" + id),
					Label: aws.String(snakeCase(*metric.MetricName + "_maximum")),
					MetricStat: &cloudwatch.MetricStat{
						Metric: metric,
						Period: aws.Int64(int64(c.Period.Duration.Seconds())),
						Stat:   aws.String(cloudwatch.StatisticMaximum),
					},
				})
			}
			if filtered.statFilter.Match("minimum") {
				c.queryDimensions["minimum_"+id] = dimension
				dataQueries = append(dataQueries, &cloudwatch.MetricDataQuery{
					Id:    aws.String("minimum_" + id),
					Label: aws.String(snakeCase(*metric.MetricName + "_minimum")),
					MetricStat: &cloudwatch.MetricStat{
						Metric: metric,
						Period: aws.Int64(int64(c.Period.Duration.Seconds())),
						Stat:   aws.String(cloudwatch.StatisticMinimum),
					},
				})
			}
			if filtered.statFilter.Match("sum") {
				c.queryDimensions["sum_"+id] = dimension
				dataQueries = append(dataQueries, &cloudwatch.MetricDataQuery{
					Id:    aws.String("sum_" + id),
					Label: aws.String(snakeCase(*metric.MetricName + "_sum")),
					MetricStat: &cloudwatch.MetricStat{
						Metric: metric,
						Period: aws.Int64(int64(c.Period.Duration.Seconds())),
						Stat:   aws.String(cloudwatch.StatisticSum),
					},
				})
			}
			if filtered.statFilter.Match("sample_count") {
				c.queryDimensions["sample_count_"+id] = dimension
				dataQueries = append(dataQueries, &cloudwatch.MetricDataQuery{
					Id:    aws.String("sample_count_" + id),
					Label: aws.String(snakeCase(*metric.MetricName + "_sample_count")),
					MetricStat: &cloudwatch.MetricStat{
						Metric: metric,
						Period: aws.Int64(int64(c.Period.Duration.Seconds())),
						Stat:   aws.String(cloudwatch.StatisticSampleCount),
					},
				})
			}
		}
	}

	if len(dataQueries) == 0 {
		return nil, errors.New("no metrics found to collect")
	}

	if c.metricCache == nil {
		c.metricCache = &metricCache{
			queries: dataQueries,
			built:   time.Now(),
			ttl:     c.CacheTTL.Duration,
		}
	} else {
		c.metricCache.queries = dataQueries
	}

	return dataQueries, nil
}
482136
func (c *MempoolDataCache) GetFees(N int) (uint32, int, []float64) {
	c.mtx.RLock()
	defer c.mtx.RUnlock()

	numFees := len(c.allFees)

	//var fees []float64
	fees := []float64{} // for consistency
	if N == 0 {
		return c.height, numFees, fees
	}

	if N < 0 || N >= numFees {
		fees = make([]float64, numFees)
		copy(fees, c.allFees)
	} else if N < numFees {
		// fees are in ascending order, take from end of slice
		smallestFeeInd := numFees - N
		fees = make([]float64, N)
		copy(fees, c.allFees[smallestFeeInd:])
	}

	return c.height, numFees, fees
}
95281
func (c *TagValueSeriesIDCache) DeleteMeasurement(name []byte) {
	c.Lock()
	delete(c.cache, string(name))
	c.Unlock()
}
1051712
func (t *TSMReader) MeasurementStats() (MeasurementStats, error) {
	f, err := os.Open(StatsFilename(t.Path()))
	if os.IsNotExist(err) {
		return make(MeasurementStats), nil
	} else if err != nil {
		return nil, err
	}
	defer f.Close()

	stats := make(MeasurementStats)
	if _, err := stats.ReadFrom(bufio.NewReader(f)); err != nil {
		return nil, err
	}
	return stats, err
}
135311
func getMetric(store *cassandra.CassandraStore, amkey schema.AMKey) ([]Metric, error) {
	var metrics []Metric
	// index only stores MKey's, not AMKey's.
	iter := store.Session.Query("select name from metric_idx where id=? ALLOW FILTERING", amkey.MKey.String()).Iter()
	var m Metric
	for iter.Scan(&m.name) {
		m.AMKey = amkey
		metrics = append(metrics, m)
	}
	if len(metrics) > 1 {
		panic(fmt.Sprintf("wtf. found more than one entry for id %s: %v", amkey.String(), metrics))
	}
	err := iter.Close()
	if err != nil {
		return metrics, err
	}
	return metrics, nil
}
598611
func NewTSDBMeasurementIteratorAdapter(itr MeasurementIterator) tsdb.MeasurementIterator {
	if itr == nil {
		return nil
	}
	return &tsdbMeasurementIteratorAdapter{itr: itr}
}
186323
func (c *lruEvictedCache) Get(key Measurable) (data Measurable, ok bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	d, ok := c.data.Get(lru.Key(key))
	if !ok {
		return nil, false
	}
	memoized, ok := d.(memoizedMeasurable)
	if !ok {
		return nil, false
	}
	return memoized.m, ok
}
1197581
func GetEncodedMetrics(config libkbfs.Config) func(context.Context) ([]byte, time.Time, error) {
	return func(context.Context) ([]byte, time.Time, error) {
		if registry := config.MetricsRegistry(); registry != nil {
			b := bytes.NewBuffer(nil)
			metricsutil.WriteMetrics(registry, b)
			return b.Bytes(), time.Time{}, nil
		}
		return []byte("Metrics have been turned off.\n"), time.Time{}, nil
	}
}
853534
func (r Survey) GetQuestions() (resp []datatypes.Survey_Question, err error) {
	err = r.Session.DoRequest("SoftLayer_Survey", "getQuestions", nil, &r.Options, &resp)
	return
}
1050556
func ReadMeasurementBlockTrailer(data []byte) (MeasurementBlockTrailer, error) {
	var t MeasurementBlockTrailer

	// Read version (which is located in the last two bytes of the trailer).
	t.Version = int(binary.BigEndian.Uint16(data[len(data)-2:]))
	if t.Version != MeasurementBlockVersion {
		return t, ErrUnsupportedIndexFileVersion
	}

	// Slice trailer data.
	buf := data[len(data)-MeasurementTrailerSize:]

	// Read data section info.
	t.Data.Offset, buf = int64(binary.BigEndian.Uint64(buf[0:8])), buf[8:]
	t.Data.Size, buf = int64(binary.BigEndian.Uint64(buf[0:8])), buf[8:]

	// Read measurement block info.
	t.HashIndex.Offset, buf = int64(binary.BigEndian.Uint64(buf[0:8])), buf[8:]
	t.HashIndex.Size, buf = int64(binary.BigEndian.Uint64(buf[0:8])), buf[8:]

	// We would advance past old sketch info, but that's unused now.
	_ = buf
	// buf = buf[4*8:]

	return t, nil
}