// GetMetricReplicas calculates the desired replica count based on a target metric utilization
// (as a milli-value) for pods matching the given selector in the given namespace, and the
// current replica count
510912
func (c *ReplicaCalculator) GetMetricReplicas(currentReplicas int32, targetUtilization int64, metricName string, namespace string, selector labels.Selector, metricSelector labels.Selector) (replicaCount int32, utilization int64, timestamp time.Time, err error) {
	metrics, timestamp, err := c.metricsClient.GetRawMetric(metricName, namespace, selector, metricSelector)
	if err != nil {
		return 0, 0, time.Time{}, fmt.Errorf("unable to get metric %s: %v", metricName, err)
	}

	replicaCount, utilization, err = c.calcPlainMetricReplicas(metrics, currentReplicas, targetUtilization, namespace, selector, v1.ResourceName(""))
	return replicaCount, utilization, timestamp, err
}
815251
func (em *EventMeter) GetMetric(query string) (*EventMetric, error) {
	em.mtx.Lock()
	defer em.mtx.Unlock()
	metric, ok := em.queryToMetricMap[query]
	if !ok {
		return nil, fmt.Errorf("unknown query: %s", query)
	}
	return metric.fillMetric().Copy(), nil
}
842795
func getReplicaSetFraction(rs apps.ReplicaSet, d apps.Deployment) int32 {
	// If we are scaling down to zero then the fraction of this replica set is its whole size (negative)
	if *(d.Spec.Replicas) == int32(0) {
		return -*(rs.Spec.Replicas)
	}

	deploymentReplicas := *(d.Spec.Replicas) + MaxSurge(d)
	annotatedReplicas, ok := getMaxReplicasAnnotation(&rs)
	if !ok {
		// If we cannot find the annotation then fallback to the current deployment size. Note that this
		// will not be an accurate proportion estimation in case other replica sets have different values
		// which means that the deployment was scaled at some point but we at least will stay in limits
		// due to the min-max comparisons in getProportion.
		annotatedReplicas = d.Status.Replicas
	}

	// We should never proportionally scale up from zero which means rs.spec.replicas and annotatedReplicas
	// will never be zero here.
	newRSsize := (float64(*(rs.Spec.Replicas) * deploymentReplicas)) / float64(annotatedReplicas)
	return integer.RoundToInt32(newRSsize) - *(rs.Spec.Replicas)
}
891055
func (_class VIFClass) GetMetrics(sessionID SessionRef, self VIFRef) (_retval VIFMetricsRef, _err error) {
	_method := "VIF.get_metrics"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertVIFRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertVIFMetricsRefToGo(_method + " -> ", _result.Value)
	return
}
116263
func GetReplicaCountForRCs(replicationControllers []*api.ReplicationController) int {
	totalReplicaCount := 0
	for _, rc := range replicationControllers {
		totalReplicaCount += rc.Spec.Replicas
	}
	return totalReplicaCount
}
524366
func (c *Collection) GetFromReplica(key string, replicaIdx int, opts *GetFromReplicaOptions) (docOut *GetResult, errOut error) {
	if opts == nil {
		opts = &GetFromReplicaOptions{}
	}

	span := c.startKvOpTrace(opts.ParentSpanContext, "GetFromReplica")
	defer span.Finish()

	ctx, cancel := c.context(opts.Context, opts.Timeout)
	if cancel != nil {
		defer cancel()
	}

	res, err := c.getFromReplica(ctx, span.Context(), key, replicaIdx, *opts)
	if err != nil {
		return nil, err
	}

	return res, nil
}
242276
func getMetrics(store *cassandra.CassandraStore, prefix, substr, glob string, archive schema.Archive) ([]Metric, error) {
	var metrics []Metric
	iter := store.Session.Query("select id, name from metric_idx").Iter()
	var m Metric
	var idString string
	for iter.Scan(&idString, &m.name) {
		if match(prefix, substr, glob, m) {
			mkey, err := schema.MKeyFromString(idString)
			if err != nil {
				panic(err)
			}
			m.AMKey = schema.AMKey{
				MKey:    mkey,
				Archive: archive,
			}
			metrics = append(metrics, m)
		}
	}
	err := iter.Close()
	if err != nil {
		return metrics, err
	}
	sort.Sort(MetricsByName(metrics))
	return metrics, nil
}
484690
func (m *MetricBatch) Metrics() []Metric {
	result := make([]Metric, len(m.doc.Metrics))
	copy(result, m.doc.Metrics)
	return result
}
197313
func (f *Mock) CollectMetrics(mts []plugin.Metric) ([]plugin.Metric, error) {
	for _, p := range mts {
		log.Printf("collecting %+v\n", p)
	}

	rand.Seed(time.Now().UTC().UnixNano())
	metrics := []plugin.Metric{}
	for i := range mts {
		if _, err := mts[i].Config.GetBool("long_print"); err == nil {
			letterBytes := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
			longLine := []byte{}
			for i := 0; i < 8193; i++ {
				longLine = append(longLine, letterBytes[rand.Intn(len(letterBytes))])
			}
			fmt.Println(string(longLine))
		}
		if _, err := mts[i].Config.GetBool("panic"); err == nil {
			panic("Oops!")
		}

		if isDynamic, _ := mts[i].Namespace.IsDynamic(); isDynamic {
			requestedHosts := []string{}

			if mts[i].Namespace[2].Value == "*" {
				// when dynamic element is not specified (equals an asterisk)
				// then consider all available hosts as requested hosts
				requestedHosts = append(requestedHosts, availableHosts...)
			} else {
				// when the dynamic element is specified
				// then consider this specified host as requested hosts
				host := mts[i].Namespace[2].Value

				// check if specified host is available in system
				if contains(availableHosts, host) {
					requestedHosts = append(requestedHosts, host)
				} else {
					return nil, fmt.Errorf("requested hostname `%s` is not available (list of available hosts: %s)", host, availableHosts)
				}

			}
			// collect data for each of requested hosts
			for _, host := range requestedHosts {
				//generate random data
				data := randInt(65, 90) + 1000
				// prepare namespace as a copy of incoming dynamic namespace,
				// but with the set value of dynamic element
				ns := plugin.CopyNamespace(mts[i].Namespace)
				ns[2].Value = host
				// metric with set data, ns, timestamp and the version of the plugin
				mt := plugin.Metric{
					Data:      data,
					Namespace: ns,
					Timestamp: time.Now(),
					Unit:      mts[i].Unit,
					Version:   mts[i].Version,
				}
				metrics = append(metrics, mt)
			}

		} else {
			data := randInt(65, 90) + 1000
			mts[i].Data = data
			mts[i].Timestamp = time.Now()
			metrics = append(metrics, mts[i])
		}
	}
	return metrics, nil
}
1098105
func (_class HostMetricsClass) GetAllRecords(sessionID SessionRef) (_retval map[HostMetricsRef]HostMetricsRecord, _err error) {
	_method := "host_metrics.get_all_records"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg)
	if _err != nil {
		return
	}
	_retval, _err = convertHostMetricsRefToHostMetricsRecordMapToGo(_method + " -> ", _result.Value)
	return
}
1208994
func (c *Client) GetMetrics(tags ...string) ([]params.MetricResult, error) {
	entities := make([]params.Entity, len(tags))
	for i, tag := range tags {
		entities[i] = params.Entity{Tag: tag}
	}
	p := params.Entities{Entities: entities}
	results := new(params.MetricResults)
	if err := c.facade.FacadeCall("GetMetrics", p, results); err != nil {
		return nil, errors.Trace(err)
	}
	if err := results.OneError(); err != nil {
		return nil, errors.Trace(err)
	}
	metrics := []params.MetricResult{}
	for _, r := range results.Results {
		metrics = append(metrics, r.Metrics...)
	}
	return metrics, nil
}
525515
func ExtractReplicas(opts ...interface{}) *opt.ReplicasOption {
	for _, o := range opts {
		if v, ok := o.(*opt.ReplicasOption); ok {
			return v
		}
	}
	return nil
}
434839
func (_class HostClass) GetMetrics(sessionID SessionRef, self HostRef) (_retval HostMetricsRef, _err error) {
	_method := "host.get_metrics"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertHostRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertHostMetricsRefToGo(_method + " -> ", _result.Value)
	return
}
1170357
func (h *HTTPReporter) GetMetrics() *vegeta.Metrics {
	h.Lock()
	defer h.Unlock()
	return h.metrics
}
770282
func (mc *metricCatalog) GetMetric(requested core.Namespace, version int) (*metricType, error) {
	mc.mutex.Lock()
	defer mc.mutex.Unlock()

	var ns core.Namespace

	catalogedmt, err := mc.tree.GetMetric(requested.Strings(), version)
	if err != nil {
		log.WithFields(log.Fields{
			"_module": "control",
			"_file":   "metrics.go,",
			"_block":  "get-metric",
			"error":   err,
		}).Error("error getting metric")
		return nil, err
	}

	ns = catalogedmt.Namespace()

	if isDynamic, _ := ns.IsDynamic(); isDynamic {
		// when namespace is dynamic and the cataloged namespace (e.g. ns=/intel/mock/*/bar) is different than
		// the requested (e.g. requested=/intel/mock/host0/bar), than specify an instance of dynamic element,
		// so as a result the dynamic element will have set a value (e.g. ns[2].Value equals "host0")
		if ns.String() != requested.String() {
			ns = specifyInstanceOfDynamicMetric(ns, requested)
		}
	}

	returnedmt := &metricType{
		Plugin:             catalogedmt.Plugin,
		namespace:          ns,
		version:            catalogedmt.Version(),
		lastAdvertisedTime: catalogedmt.LastAdvertisedTime(),
		tags:               catalogedmt.Tags(),
		policy:             catalogedmt.Plugin.Policy().Get(catalogedmt.Namespace().Strings()),
		config:             catalogedmt.Config(),
		unit:               catalogedmt.Unit(),
		description:        catalogedmt.Description(),
		subscriptions:      catalogedmt.SubscriptionCount(),
	}
	return returnedmt, nil
}
352674
func (c *ReplicaCalculator) GetExternalPerPodMetricReplicas(currentReplicas int32, targetUtilizationPerPod int64, metricName, namespace string, metricSelector *metav1.LabelSelector) (replicaCount int32, utilization int64, timestamp time.Time, err error) {
	metricLabelSelector, err := metav1.LabelSelectorAsSelector(metricSelector)
	if err != nil {
		return 0, 0, time.Time{}, err
	}
	metrics, timestamp, err := c.metricsClient.GetExternalMetric(metricName, namespace, metricLabelSelector)
	if err != nil {
		return 0, 0, time.Time{}, fmt.Errorf("unable to get external metric %s/%s/%+v: %s", namespace, metricName, metricSelector, err)
	}
	utilization = 0
	for _, val := range metrics {
		utilization = utilization + val
	}

	replicaCount = currentReplicas
	usageRatio := float64(utilization) / (float64(targetUtilizationPerPod) * float64(replicaCount))
	if math.Abs(1.0-usageRatio) > c.tolerance {
		// update number of replicas if the change is large enough
		replicaCount = int32(math.Ceil(float64(utilization) / float64(targetUtilizationPerPod)))
	}
	utilization = int64(math.Ceil(float64(utilization) / float64(currentReplicas)))
	return replicaCount, utilization, timestamp, nil
}
780197
func (mt MetricsTree) GetTagsForMetric(metric string) (tags []string, e error) {
	if m, ok := mt[metric]; ok {
		keys := make([]string, 0, len(m))
		for key, _ := range m {
			keys = append(keys, key)
		}
		return keys, e
	}
	return tags, errors.New(fmt.Sprintf("Failed to find metric %s", metric))
}