// GetExternalPerPodMetricReplicas calculates the desired replica count based on a
// target metric value per pod (as a milli-value) for the external metric in the
// given namespace, and the current replica count.
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
}
1124409
func (s *StoreToReplicaSetLister) GetPodReplicaSets(pod *api.Pod) (rss []extensions.ReplicaSet, err error) {
	var selector labels.Selector
	var rs extensions.ReplicaSet

	if len(pod.Labels) == 0 {
		err = fmt.Errorf("no ReplicaSets found for pod %v because it has no labels", pod.Name)
		return
	}

	for _, m := range s.Store.List() {
		rs = *m.(*extensions.ReplicaSet)
		if rs.Namespace != pod.Namespace {
			continue
		}
		selector, err = unversioned.LabelSelectorAsSelector(rs.Spec.Selector)
		if err != nil {
			err = fmt.Errorf("invalid selector: %v", err)
			return
		}

		// If a ReplicaSet with a nil or empty selector creeps in, it should match nothing, not everything.
		if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {
			continue
		}
		rss = append(rss, rs)
	}
	if len(rss) == 0 {
		err = fmt.Errorf("could not find ReplicaSet for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels)
	}
	return
}
162534
func (s *replicaSetLister) GetPodReplicaSets(pod *v1.Pod) ([]*apps.ReplicaSet, error) {
	if len(pod.Labels) == 0 {
		return nil, fmt.Errorf("no ReplicaSets found for pod %v because it has no labels", pod.Name)
	}

	list, err := s.ReplicaSets(pod.Namespace).List(labels.Everything())
	if err != nil {
		return nil, err
	}

	var rss []*apps.ReplicaSet
	for _, rs := range list {
		if rs.Namespace != pod.Namespace {
			continue
		}
		selector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector)
		if err != nil {
			return nil, fmt.Errorf("invalid selector: %v", err)
		}

		// If a ReplicaSet with a nil or empty selector creeps in, it should match nothing, not everything.
		if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {
			continue
		}
		rss = append(rss, rs)
	}

	if len(rss) == 0 {
		return nil, fmt.Errorf("could not find ReplicaSet for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels)
	}

	return rss, nil
}
563503
func (c *FakePodMetricses) Get(name string, options v1.GetOptions) (result *v1alpha1.PodMetrics, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewGetAction(podmetricsesResource, c.ns, name), &v1alpha1.PodMetrics{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.PodMetrics), err
}
489638
func (m *metricMap) getOrCreateMetricWithLabelValues(
	hash uint64, lvs []string, curry []curriedLabelValue,
) Metric {
	m.mtx.RLock()
	metric, ok := m.getMetricWithHashAndLabelValues(hash, lvs, curry)
	m.mtx.RUnlock()
	if ok {
		return metric
	}

	m.mtx.Lock()
	defer m.mtx.Unlock()
	metric, ok = m.getMetricWithHashAndLabelValues(hash, lvs, curry)
	if !ok {
		inlinedLVs := inlineLabelValues(lvs, curry)
		metric = m.newMetric(inlinedLVs...)
		m.metrics[hash] = append(m.metrics[hash], metricWithLabelValues{values: inlinedLVs, metric: metric})
	}
	return metric
}
988697
func (f EmptyReplicaSetLister) GetPodReplicaSets(pod *v1.Pod) (rss []*apps.ReplicaSet, err error) {
	return nil, nil
}
226194
func GetReplicaCountForDeployments(deployments []*v1.ReplicationController) int32 {
	totalReplicaCount := int32(0)
	for _, deployment := range deployments {
		count := deployment.Spec.Replicas
		if count == nil {
			continue
		}
		totalReplicaCount += *count
	}
	return totalReplicaCount
}
802945
func (m *metricMap) getMetricWithHashAndLabels(
	h uint64, labels Labels, curry []curriedLabelValue,
) (Metric, bool) {
	metrics, ok := m.metrics[h]
	if ok {
		if i := findMetricWithLabels(m.desc, metrics, labels, curry); i < len(metrics) {
			return metrics[i].metric, true
		}
	}
	return nil, false
}
442796
func (a *HistoricalApi) podListMetrics(request *restful.Request, response *restful.Response) {
	start, end, err := getStartEndTimeHistorical(request)
	if err != nil {
		response.WriteError(http.StatusBadRequest, err)
		return
	}

	keys := []core.HistoricalKey{}
	if request.PathParameter("pod-id-list") != "" {
		for _, podId := range strings.Split(request.PathParameter("pod-id-list"), ",") {
			key := core.HistoricalKey{
				ObjectType: core.MetricSetTypePod,
				PodId:      podId,
			}
			keys = append(keys, key)
		}
	} else {
		for _, podName := range strings.Split(request.PathParameter("pod-list"), ",") {
			key := core.HistoricalKey{
				ObjectType:    core.MetricSetTypePod,
				NamespaceName: request.PathParameter("namespace-name"),
				PodName:       podName,
			}
			keys = append(keys, key)
		}
	}

	labels, err := getLabels(request)
	if err != nil {
		response.WriteError(http.StatusBadRequest, err)
		return
	}

	metricName := request.PathParameter("metric-name")
	convertedMetricName := convertMetricName(metricName)

	var metrics map[core.HistoricalKey][]core.TimestampedMetricValue
	if labels != nil {
		metrics, err = a.historicalSource.GetLabeledMetric(convertedMetricName, labels, keys, start, end)
	} else {
		metrics, err = a.historicalSource.GetMetric(convertedMetricName, keys, start, end)
	}

	if err != nil {
		response.WriteError(http.StatusInternalServerError, err)
		return
	}

	result := types.MetricResultList{
		Items: make([]types.MetricResult, 0, len(keys)),
	}
	for _, key := range keys {
		result.Items = append(result.Items, exportTimestampedMetricValue(metrics[key]))
	}
	response.PrettyPrint(false)
	response.WriteEntity(result)
}
1341494
func GetReplicaCountForReplicaSets(replicaSets []*apps.ReplicaSet) int32 {
	totalReplicas := int32(0)
	for _, rs := range replicaSets {
		if rs != nil {
			totalReplicas += *(rs.Spec.Replicas)
		}
	}
	return totalReplicas
}
116263
func GetReplicaCountForRCs(replicationControllers []*api.ReplicationController) int {
	totalReplicaCount := 0
	for _, rc := range replicationControllers {
		totalReplicaCount += rc.Spec.Replicas
	}
	return totalReplicaCount
}
177327
func (a *HorizontalController) computeStatusForExternalMetric(currentReplicas int32, metricSpec autoscalingv2.MetricSpec, hpa *autoscalingv2.HorizontalPodAutoscaler, selector labels.Selector, status *autoscalingv2.MetricStatus) (int32, time.Time, string, error) {
	if metricSpec.External.Target.AverageValue != nil {
		replicaCountProposal, utilizationProposal, timestampProposal, err := a.replicaCalc.GetExternalPerPodMetricReplicas(currentReplicas, metricSpec.External.Target.AverageValue.MilliValue(), metricSpec.External.Metric.Name, hpa.Namespace, metricSpec.External.Metric.Selector)
		if err != nil {
			a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", err.Error())
			setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %v", err)
			return 0, time.Time{}, "", fmt.Errorf("failed to get %s external metric: %v", metricSpec.External.Metric.Name, err)
		}
		*status = autoscalingv2.MetricStatus{
			Type: autoscalingv2.ExternalMetricSourceType,
			External: &autoscalingv2.ExternalMetricStatus{
				Metric: autoscalingv2.MetricIdentifier{
					Name:     metricSpec.External.Metric.Name,
					Selector: metricSpec.External.Metric.Selector,
				},
				Current: autoscalingv2.MetricValueStatus{
					AverageValue: resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI),
				},
			},
		}
		return replicaCountProposal, timestampProposal, fmt.Sprintf("external metric %s(%+v)", metricSpec.External.Metric.Name, metricSpec.External.Metric.Selector), nil
	}
	if metricSpec.External.Target.Value != nil {
		replicaCountProposal, utilizationProposal, timestampProposal, err := a.replicaCalc.GetExternalMetricReplicas(currentReplicas, metricSpec.External.Target.Value.MilliValue(), metricSpec.External.Metric.Name, hpa.Namespace, metricSpec.External.Metric.Selector, selector)
		if err != nil {
			a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", err.Error())
			setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %v", err)
			return 0, time.Time{}, "", fmt.Errorf("failed to get external metric %s: %v", metricSpec.External.Metric.Name, err)
		}
		*status = autoscalingv2.MetricStatus{
			Type: autoscalingv2.ExternalMetricSourceType,
			External: &autoscalingv2.ExternalMetricStatus{
				Metric: autoscalingv2.MetricIdentifier{
					Name:     metricSpec.External.Metric.Name,
					Selector: metricSpec.External.Metric.Selector,
				},
				Current: autoscalingv2.MetricValueStatus{
					Value: resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI),
				},
			},
		}
		return replicaCountProposal, timestampProposal, fmt.Sprintf("external metric %s(%+v)", metricSpec.External.Metric.Name, metricSpec.External.Metric.Selector), nil
	}
	errMsg := "invalid external metric source: neither a value target nor an average value target was set"
	a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", errMsg)
	setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %s", errMsg)
	return 0, time.Time{}, "", fmt.Errorf(errMsg)
}
297492
func GetAvailablePodsForRCs(c client.Interface, rcs []*api.ReplicationController, minReadySeconds int) (int, error) {
	allPods, err := getPodsForRCs(c, rcs)
	if err != nil {
		return 0, err
	}
	return getReadyPodsCount(allPods, minReadySeconds), nil
}
824149
func (p *pluginControl) getMetricsAndCollectors(requested []core.RequestedMetric, configTree *cdata.ConfigDataTree) (map[string]metricTypes, []core.SubscribedPlugin, []serror.SnapError) {
	newMetricsGroupedByPlugin := make(map[string]metricTypes)
	newPlugins := []core.SubscribedPlugin{}
	var serrs []serror.SnapError
	for _, r := range requested {
		// get all metric types available in metricCatalog which fulfill the requested namespace and version (if ver <=0 the latest version will be taken)
		newMetrics, err := p.metricCatalog.GetMetrics(r.Namespace(), r.Version())
		if err != nil {
			log.WithFields(log.Fields{
				"_block": "control",
				"action": "expanding-requested-metrics",
				"query":  r.Namespace(),
				"err":    err,
			}).Error("error matching requested namespace with metric catalog")
			serrs = append(serrs, serror.New(err))
			continue
		}

		if controlLogger.Level >= log.DebugLevel {
			for _, m := range newMetrics {
				controlLogger.WithFields(log.Fields{
					"_block":  "control",
					"ns":      m.Namespace().String(),
					"version": m.Version(),
				}).Debug("Expanded namespaces found in metric catalog")
			}
		}

		for _, mt := range newMetrics {
			// in case config tree doesn't have any configuration for current namespace
			// it's needed to initialize config, otherwise it will stay nil and panic later on
			cfg := configTree.Get(mt.Namespace().Strings())
			if cfg == nil {
				cfg = cdata.NewNode()
			}
			// set config to metric
			mt.config = cfg

			// apply the defaults from the global (plugin) config
			plType, _ := core.ToPluginType(mt.Plugin.TypeName())
			cfgNode := p.pluginManager.GetPluginConfig().getPluginConfigDataNode(plType, mt.Plugin.Name(), mt.Plugin.Version())
			cfg.ApplyDefaults(cfgNode.Table())

			// apply defaults to the metric that may be present in the plugins
			// configpolicy
			if pluginCfg := mt.Plugin.Policy().Get(mt.Namespace().Strings()); pluginCfg != nil {
				mt.config.ApplyDefaults(pluginCfg.Defaults())
			}

			// cataloged plugin which exposes the metric
			cp := mt.Plugin
			key := fmt.Sprintf("%s"+core.Separator+"%s"+core.Separator+"%d", cp.TypeName(), cp.Name(), cp.Version())

			// groups metricTypes by a plugin.Key()
			pmt, _ := newMetricsGroupedByPlugin[key]

			// pmt (plugin-metric-type) contains plugin and metrics types grouped to this plugin
			pmt.plugin = cp
			pmt.metricTypes = append(pmt.metricTypes, mt)
			newMetricsGroupedByPlugin[key] = pmt

			plugin := subscribedPlugin{
				name:     cp.Name(),
				typeName: cp.TypeName(),
				version:  cp.Version(),
				config:   cdata.NewNode(),
			}

			if !containsPlugin(newPlugins, plugin) {
				newPlugins = append(newPlugins, plugin)
			}
		}
	}
	if controlLogger.Level >= log.DebugLevel {
		for _, pmt := range newMetricsGroupedByPlugin {
			for _, m := range pmt.Metrics() {
				log.WithFields(log.Fields{
					"_block": "control",
					"action": "gather",
					"metric": fmt.Sprintf("%s:%d", m.Namespace().String(), m.Version()),
				}).Debug("gathered metrics from workflow request")
			}

		}
		for _, p := range newPlugins {
			log.WithFields(log.Fields{
				"_block": "control",
				"action": "gather",
				"metric": fmt.Sprintf("%s:%s:%d", p.TypeName(), p.Name(), p.Version()),
			}).Debug("gathered plugins from workflow request")
		}
	}

	return newMetricsGroupedByPlugin, newPlugins, serrs
}
155321
func (mtt *mttNode) GetMetrics(ns []string, ver int) ([]*metricType, error) {
	nodes := []*mttNode{}
	mts := []*metricType{}

	if len(ns) == 0 {
		return nil, errorEmptyNamespace()
	}
	// search returns all of the nodes fulfilling the 'ns'
	// even for some of them there is no metric (empty node.mts)
	nodes = mtt.search(nodes, ns)

	for _, node := range nodes {
		// choose the queried version of metric types (or the latest if ver < 1)
		// and concatenate them into a single slice
		mt, err := getVersion(node.mts, ver)
		if err != nil {
			continue
		}
		mts = append(mts, mt)
	}
	if len(mts) == 0 {
		return nil, errorMetricNotFound("/"+strings.Join(ns, "/"), ver)
	}
	return mts, nil
}
1218168
func (dc *DisruptionController) getPodReplicaSet(pod *v1.Pod) (*controllerAndScale, error) {
	controllerRef := metav1.GetControllerOf(pod)
	if controllerRef == nil {
		return nil, nil
	}
	if controllerRef.Kind != controllerKindRS.Kind {
		return nil, nil
	}
	rs, err := dc.rsLister.ReplicaSets(pod.Namespace).Get(controllerRef.Name)
	if err != nil {
		// The only possible error is NotFound, which is ok here.
		return nil, nil
	}
	if rs.UID != controllerRef.UID {
		return nil, nil
	}
	controllerRef = metav1.GetControllerOf(rs)
	if controllerRef != nil && controllerRef.Kind == controllerKindDep.Kind {
		// Skip RS if it's controlled by a Deployment.
		return nil, nil
	}
	return &controllerAndScale{rs.UID, *(rs.Spec.Replicas)}, nil
}
772187
func GetReadyReplicaCountForReplicaSets(replicaSets []*apps.ReplicaSet) int32 {
	totalReadyReplicas := int32(0)
	for _, rs := range replicaSets {
		if rs != nil {
			totalReadyReplicas += rs.Status.ReadyReplicas
		}
	}
	return totalReadyReplicas
}