<commit_before>// Copyright 2013 Prometheus Team
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package metric

import (
	"fmt"
	"github.com/prometheus/prometheus/model"
	"github.com/ryszard/goskiplist/skiplist"
	"sort"
	"time"
)

var (
	_ = fmt.Sprintf("")

	// firstSupertime is the smallest valid supertime that may be seeked to.
	firstSupertime = []byte{0, 0, 0, 0, 0, 0, 0, 0}
	// lastSupertime is the largest valid supertime that may be seeked to.
	lastSupertime = []byte{127, 255, 255, 255, 255, 255, 255, 255}
)

// Represents the summation of all datastore queries that shall be performed to
// extract values.  Each operation mutates the state of the builder.
type ViewRequestBuilder interface {
	GetMetricAtTime(fingerprint model.Fingerprint, time time.Time)
	GetMetricAtInterval(fingerprint model.Fingerprint, from, through time.Time, interval time.Duration)
	GetMetricRange(fingerprint model.Fingerprint, from, through time.Time)
	ScanJobs() scanJobs
}

// Contains the various unoptimized requests for data.
type viewRequestBuilder struct {
	operations map[model.Fingerprint]ops
}

// Furnishes a ViewRequestBuilder for remarking what types of queries to perform.
func NewViewRequestBuilder() viewRequestBuilder {
	return viewRequestBuilder{
		operations: make(map[model.Fingerprint]ops),
	}
}

// Gets for the given Fingerprint either the value at that time if there is an
// match or the one or two values adjacent thereto.
func (v viewRequestBuilder) GetMetricAtTime(fingerprint model.Fingerprint, time time.Time) {
	ops := v.operations[fingerprint]
	ops = append(ops, &getValuesAtTimeOp{
		time: time,
	})
	v.operations[fingerprint] = ops
}

// Gets for the given Fingerprint either the value at that interval from From
// through Through  if there is an match or the one or two values adjacent
// for each point.
func (v viewRequestBuilder) GetMetricAtInterval(fingerprint model.Fingerprint, from, through time.Time, interval time.Duration) {
	ops := v.operations[fingerprint]
	ops = append(ops, &getValuesAtIntervalOp{
		from:     from,
		through:  through,
		interval: interval,
	})
	v.operations[fingerprint] = ops
}

// Gets for the given Fingerprint either the values that occur inclusively from
// From through Through.
func (v viewRequestBuilder) GetMetricRange(fingerprint model.Fingerprint, from, through time.Time) {
	ops := v.operations[fingerprint]
	ops = append(ops, &getValuesAlongRangeOp{
		from:    from,
		through: through,
	})
	v.operations[fingerprint] = ops
}

// Emits the optimized scans that will occur in the data store.  This
// effectively resets the ViewRequestBuilder back to a pristine state.
func (v viewRequestBuilder) ScanJobs() (j scanJobs) {
	for fingerprint, operations := range v.operations {
		sort.Sort(startsAtSort{operations})

		j = append(j, scanJob{
			fingerprint: fingerprint,
			operations:  optimize(operations),
		})

		delete(v.operations, fingerprint)
	}

	sort.Sort(j)

	return
}

type view struct {
	fingerprintToSeries map[model.Fingerprint]viewStream
}

func (v view) appendSample(fingerprint model.Fingerprint, timestamp time.Time, value model.SampleValue) {
	var (
		series, ok = v.fingerprintToSeries[fingerprint]
	)

	if !ok {
		series = newViewStream()
		v.fingerprintToSeries[fingerprint] = series
	}

	series.add(timestamp, value)
}

func (v view) Close() {
	v.fingerprintToSeries = make(map[model.Fingerprint]viewStream)
}

func (v view) GetValueAtTime(f model.Fingerprint, t time.Time) (s []model.SamplePair) {
	var (
		series, ok = v.fingerprintToSeries[f]
	)
	if !ok {
		return
	}

	var (
		iterator = series.values.Seek(skipListTime(t))
	)
	if iterator == nil {
		return
	}

	defer iterator.Close()

	if iterator.Key() == nil || iterator.Value() == nil {
		return
	}

	s = append(s, model.SamplePair{
		Timestamp: time.Time(iterator.Key().(skipListTime)),
		Value:     iterator.Value().(value).get(),
	})

	if iterator.Previous() {
		s = append(s, model.SamplePair{
			Timestamp: time.Time(iterator.Key().(skipListTime)),
			Value:     iterator.Value().(value).get(),
		})
	}

	return
}

func (v view) GetBoundaryValues(f model.Fingerprint, i model.Interval) (s []model.SamplePair) {
	return
}

func (v view) GetRangeValues(f model.Fingerprint, i model.Interval) (s []model.SamplePair) {
	return
}

func newView() view {
	return view{
		fingerprintToSeries: make(map[model.Fingerprint]viewStream),
	}
}

type viewStream struct {
	values *skiplist.SkipList
}

func (s viewStream) add(timestamp time.Time, value model.SampleValue) {
	s.values.Set(skipListTime(timestamp), singletonValue(value))
}

func newViewStream() viewStream {
	return viewStream{
		values: skiplist.New(),
	}
}
<commit_msg>Fix iterator behavior in view.GetSampleAtTime()<commit_after>// Copyright 2013 Prometheus Team
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package metric

import (
	"fmt"
	"github.com/prometheus/prometheus/model"
	"github.com/ryszard/goskiplist/skiplist"
	"sort"
	"time"
)

var (
	_ = fmt.Sprintf("")

	// firstSupertime is the smallest valid supertime that may be seeked to.
	firstSupertime = []byte{0, 0, 0, 0, 0, 0, 0, 0}
	// lastSupertime is the largest valid supertime that may be seeked to.
	lastSupertime = []byte{127, 255, 255, 255, 255, 255, 255, 255}
)

// Represents the summation of all datastore queries that shall be performed to
// extract values.  Each operation mutates the state of the builder.
type ViewRequestBuilder interface {
	GetMetricAtTime(fingerprint model.Fingerprint, time time.Time)
	GetMetricAtInterval(fingerprint model.Fingerprint, from, through time.Time, interval time.Duration)
	GetMetricRange(fingerprint model.Fingerprint, from, through time.Time)
	ScanJobs() scanJobs
}

// Contains the various unoptimized requests for data.
type viewRequestBuilder struct {
	operations map[model.Fingerprint]ops
}

// Furnishes a ViewRequestBuilder for remarking what types of queries to perform.
func NewViewRequestBuilder() viewRequestBuilder {
	return viewRequestBuilder{
		operations: make(map[model.Fingerprint]ops),
	}
}

// Gets for the given Fingerprint either the value at that time if there is an
// match or the one or two values adjacent thereto.
func (v viewRequestBuilder) GetMetricAtTime(fingerprint model.Fingerprint, time time.Time) {
	ops := v.operations[fingerprint]
	ops = append(ops, &getValuesAtTimeOp{
		time: time,
	})
	v.operations[fingerprint] = ops
}

// Gets for the given Fingerprint either the value at that interval from From
// through Through  if there is an match or the one or two values adjacent
// for each point.
func (v viewRequestBuilder) GetMetricAtInterval(fingerprint model.Fingerprint, from, through time.Time, interval time.Duration) {
	ops := v.operations[fingerprint]
	ops = append(ops, &getValuesAtIntervalOp{
		from:     from,
		through:  through,
		interval: interval,
	})
	v.operations[fingerprint] = ops
}

// Gets for the given Fingerprint either the values that occur inclusively from
// From through Through.
func (v viewRequestBuilder) GetMetricRange(fingerprint model.Fingerprint, from, through time.Time) {
	ops := v.operations[fingerprint]
	ops = append(ops, &getValuesAlongRangeOp{
		from:    from,
		through: through,
	})
	v.operations[fingerprint] = ops
}

// Emits the optimized scans that will occur in the data store.  This
// effectively resets the ViewRequestBuilder back to a pristine state.
func (v viewRequestBuilder) ScanJobs() (j scanJobs) {
	for fingerprint, operations := range v.operations {
		sort.Sort(startsAtSort{operations})

		j = append(j, scanJob{
			fingerprint: fingerprint,
			operations:  optimize(operations),
		})

		delete(v.operations, fingerprint)
	}

	sort.Sort(j)

	return
}

type view struct {
	fingerprintToSeries map[model.Fingerprint]viewStream
}

func (v view) appendSample(fingerprint model.Fingerprint, timestamp time.Time, value model.SampleValue) {
	var (
		series, ok = v.fingerprintToSeries[fingerprint]
	)

	if !ok {
		series = newViewStream()
		v.fingerprintToSeries[fingerprint] = series
	}

	series.add(timestamp, value)
}

func (v view) Close() {
	v.fingerprintToSeries = make(map[model.Fingerprint]viewStream)
}

func (v view) GetValueAtTime(f model.Fingerprint, t time.Time) (s []model.SamplePair) {
	series, ok := v.fingerprintToSeries[f]
	if !ok {
		return
	}

	iterator := series.values.Seek(skipListTime(t))
	if iterator == nil {
		// If the iterator is nil, it means we seeked past the end of the series,
		// so we seek to the last value instead. Due to the reverse ordering
		// defined on skipListTime, this corresponds to the sample with the
		// earliest timestamp.
		iterator = series.values.SeekToLast()
		if iterator == nil {
			// The list is empty.
			return
		}
	}

	defer iterator.Close()

	if iterator.Key() == nil || iterator.Value() == nil {
		return
	}

	s = append(s, model.SamplePair{
		Timestamp: time.Time(iterator.Key().(skipListTime)),
		Value:     iterator.Value().(value).get(),
	})

	if iterator.Previous() {
		s = append(s, model.SamplePair{
			Timestamp: time.Time(iterator.Key().(skipListTime)),
			Value:     iterator.Value().(value).get(),
		})
	}

	return
}

func (v view) GetBoundaryValues(f model.Fingerprint, i model.Interval) (s []model.SamplePair) {
	return
}

func (v view) GetRangeValues(f model.Fingerprint, i model.Interval) (s []model.SamplePair) {
	return
}

func newView() view {
	return view{
		fingerprintToSeries: make(map[model.Fingerprint]viewStream),
	}
}

type viewStream struct {
	values *skiplist.SkipList
}

func (s viewStream) add(timestamp time.Time, value model.SampleValue) {
	s.values.Set(skipListTime(timestamp), singletonValue(value))
}

func newViewStream() viewStream {
	return viewStream{
		values: skiplist.New(),
	}
}
<|endoftext|>


<commit_before>package deprecatedapirequest

import "k8s.io/apimachinery/pkg/runtime/schema"

var deprecatedApiRemovedRelease = map[schema.GroupVersionResource]string{
	{Group: "flowcontrol.apiserver.k8s.io", Version: "v1alpha1", Resource: "flowschemas"}:                    "1.21",
	{Group: "flowcontrol.apiserver.k8s.io", Version: "v1alpha1", Resource: "prioritylevelconfigurations"}:    "1.21",
	{Group: "extensions", Version: "v1beta1", Resource: "ingresses"}:                                         "1.22",
	{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "validatingwebhookconfigurations"}: "1.22",
	{Group: "apiextensions.k8s.io", Version: "v1beta1", Resource: "customresourcedefinitions"}:               "1.22",
	{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "mutatingwebhookconfigurations"}:   "1.22",
	{Group: "certificates.k8s.io", Version: "v1beta1", Resource: "certificatesigningrequests"}:               "1.22",
	{Group: "networking.k8s.io", Version: "v1beta1", Resource: "ingresses"}:                                  "1.22",
	{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "clusterrolebindings"}:                "1.22",
	{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "rolebindings"}:                       "1.22",
	{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "roles"}:                              "1.22",
}

// removedRelease of a specified resource.version.group.
func removedRelease(resource schema.GroupVersionResource) string {
	return deprecatedApiRemovedRelease[resource]
}
<commit_msg>UPSTREAM: <carry>: update list of deprecated apis<commit_after>package deprecatedapirequest

import "k8s.io/apimachinery/pkg/runtime/schema"

var deprecatedApiRemovedRelease = map[schema.GroupVersionResource]string{
	// Kubernetes APIs
	{Group: "apps", Version: "v1beta1", Resource: "controllerrevisions"}:                                     "1.16",
	{Group: "apps", Version: "v1beta1", Resource: "deploymentrollbacks"}:                                     "1.16",
	{Group: "apps", Version: "v1beta1", Resource: "deployments"}:                                             "1.16",
	{Group: "apps", Version: "v1beta1", Resource: "scales"}:                                                  "1.16",
	{Group: "apps", Version: "v1beta1", Resource: "statefulsets"}:                                            "1.16",
	{Group: "apps", Version: "v1beta2", Resource: "controllerrevisions"}:                                     "1.16",
	{Group: "apps", Version: "v1beta2", Resource: "daemonsets"}:                                              "1.16",
	{Group: "apps", Version: "v1beta2", Resource: "deployments"}:                                             "1.16",
	{Group: "apps", Version: "v1beta2", Resource: "replicasets"}:                                             "1.16",
	{Group: "apps", Version: "v1beta2", Resource: "scales"}:                                                  "1.16",
	{Group: "apps", Version: "v1beta2", Resource: "statefulsets"}:                                            "1.16",
	{Group: "extensions", Version: "v1beta1", Resource: "daemonsets"}:                                        "1.16",
	{Group: "extensions", Version: "v1beta1", Resource: "deploymentrollbacks"}:                               "1.16",
	{Group: "extensions", Version: "v1beta1", Resource: "deployments"}:                                       "1.16",
	{Group: "extensions", Version: "v1beta1", Resource: "networkpolicies"}:                                   "1.16",
	{Group: "extensions", Version: "v1beta1", Resource: "podsecuritypolicies"}:                               "1.16",
	{Group: "extensions", Version: "v1beta1", Resource: "replicasets"}:                                       "1.16",
	{Group: "extensions", Version: "v1beta1", Resource: "scales"}:                                            "1.16",
	{Group: "flowcontrol.apiserver.k8s.io", Version: "v1alpha1", Resource: "flowschemas"}:                    "1.21",
	{Group: "flowcontrol.apiserver.k8s.io", Version: "v1alpha1", Resource: "prioritylevelconfigurations"}:    "1.21",
	{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "mutatingwebhookconfigurations"}:   "1.22",
	{Group: "admissionregistration.k8s.io", Version: "v1beta1", Resource: "validatingwebhookconfigurations"}: "1.22",
	{Group: "apiextensions.k8s.io", Version: "v1beta1", Resource: "customresourcedefinitions"}:               "1.22",
	{Group: "certificates.k8s.io", Version: "v1beta1", Resource: "certificatesigningrequests"}:               "1.22",
	{Group: "extensions", Version: "v1beta1", Resource: "ingresses"}:                                         "1.22",
	{Group: "networking.k8s.io", Version: "v1beta1", Resource: "ingresses"}:                                  "1.22",
	{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "clusterrolebindings"}:                "1.22",
	{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "clusterroles"}:                       "1.22",
	{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "rolebindings"}:                       "1.22",
	{Group: "rbac.authorization.k8s.io", Version: "v1beta1", Resource: "roles"}:                              "1.22",
	{Group: "scheduling.k8s.io", Version: "v1beta1", Resource: "priorityclasses"}:                            "1.22",
	{Group: "storage.k8s.io", Version: "v1beta1", Resource: "csinodes"}:                                      "1.22",
	{Group: "batch", Version: "v1beta1", Resource: "cronjobs"}:                                               "1.25",
	{Group: "discovery.k8s.io", Version: "v1beta1", Resource: "endpointslices"}:                              "1.25",
	{Group: "events.k8s.io", Version: "v1beta1", Resource: "events"}:                                         "1.25",
	{Group: "autoscaling", Version: "v2beta1", Resource: "horizontalpodautoscalers"}:                         "1.25",
	{Group: "policy", Version: "v1beta1", Resource: "poddisruptionbudgets"}:                                  "1.25",
	{Group: "policy", Version: "v1beta1", Resource: "podsecuritypolicies"}:                                   "1.25",
	{Group: "node.k8s.io", Version: "v1beta1", Resource: "runtimeclasses"}:                                   "1.25",
	{Group: "autoscaling", Version: "v2beta2", Resource: "horizontalpodautoscalers"}:                         "1.26",
	// OpenShift APIs
	{Group: "operator.openshift.io", Version: "v1beta1", Resource: "kubedeschedulers"}: "1.22",
}

// removedRelease of a specified resource.version.group.
func removedRelease(resource schema.GroupVersionResource) string {
	return deprecatedApiRemovedRelease[resource]
}
<|endoftext|>


<commit_before>package cmp

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/internal"
	"github.com/influxdata/telegraf/plugins/outputs"
)

type Cmp struct {
	ApiUser     string
	ApiKey      string
	ResourceId  string
	CmpInstance string
	Timeout     internal.Duration

	client *http.Client
}

var sampleConfig = `
  # Cmp Api User and Key
  api_user = "my-api-user" # required.
  api_key = "my-api-key" # required.
  resource_id = "1234"

  # Cmp Instance URL
  cmp_instance = "https://yourcmpinstance" # required

  # Connection timeout.
  # timeout = "5s"
`

var translateMap = map[string]Translation{
	"cpu-usage.user": {
		Name: "cpu-usage.user",
		Unit: "percent",
	},
	"cpu-usage.system": {
		Name: "cpu-usage.system",
		Unit: "percent",
	},
	"mem-available.percent": {
		Name:       "memory-usage",
		Unit:       "percent",
		Conversion: memory_used_from_available,
	},
	"system-load1": {
		Name: "load-avg-1",
	},
	"system-load5": {
		Name: "load-avg-5",
	},
	"system-load15": {
		Name: "load-avg-15",
	},
	"disk-used.percent": {
		Name: "disk-usage",
	},
	//     "system-uptime": {
	//         Name: "uptime",
	//     },
	"docker_cpu-usage.percent": {
		Name: "docker-cpu-usage.system",
		Unit: "percent",
	},
	"docker_mem-usage.percent": {
		Name: "docker-memory-usage",
		Unit: "percent",
	},
}

type Translation struct {
	Name       string
	Unit       string
	Conversion func(interface{}) interface{}
}

func memory_used_from_available(available interface{}) interface{} {
	return (100.0 - available.(float64))
}

type CmpData struct {
	MonitoringSystem string      `json:"monitoring_system"`
	ResourceId       string      `json:"resource_id"`
	Metrics          []CmpMetric `json:"metrics"`
}

type CmpMetric struct {
	Metric string    `json:"metric"`
	Unit   string    `json:"unit"`
	Value  float64   `json:"value"`
	Time   time.Time `json:"time"`
}

func (data *CmpData) AddMetric(item CmpMetric) []CmpMetric {
	data.Metrics = append(data.Metrics, item)
	return data.Metrics
}

func (a *Cmp) Connect() error {
	if a.ApiUser == "" || a.ApiKey == "" || a.CmpInstance == "" || a.ResourceId == "" {
		return fmt.Errorf("api_user, api_key, resource_id and cmp_instance are required fields for cmp output")
	}
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	a.client = &http.Client{
		Transport: tr,
		Timeout:   a.Timeout.Duration,
	}
	return nil
}

func (a *Cmp) Write(metrics []telegraf.Metric) error {
	if len(metrics) == 0 {
		return nil
	}
	cmp_data := &CmpData{
		MonitoringSystem: "telegraf",
		ResourceId:       a.ResourceId,
	}

	for _, m := range metrics {

		suffix := ""
		cpu := m.Tags()["cpu"]
		path := m.Tags()["path"]
		container_name := m.Tags()["cont_name"]

		if len(cpu) > 0 && cpu != "cpu-total" {
			suffix = cpu[3:]
		} else if len(path) > 0 {
			suffix = path
		} else if len(container_name) > 0 {
			suffix = container_name
		}

		timestamp := m.Time()
		for k, v := range m.Fields() {
			metric_name := m.Name() + "-" + strings.Replace(k, "_", ".", -1)
			translation, found := translateMap[metric_name]
			if found {
				cmp_name := translation.Name
				if len(suffix) > 0 {
					cmp_name += "." + suffix
				}

				conversion := translation.Conversion
				if conversion != nil {
					v = conversion(v)
				}

				cmp_data.AddMetric(CmpMetric{
					Metric: cmp_name,
					Unit:   translation.Unit,
					Value:  v.(float64),
					Time:   timestamp,
				})
			}
		}
	}

	cmp_bytes, err := json.Marshal(cmp_data)
	if err != nil {
		return fmt.Errorf("unable to marshal TimeSeries, %s\n", err.Error())
	}
	req, err := http.NewRequest("POST", a.authenticatedUrl(), bytes.NewBuffer(cmp_bytes))
	if err != nil {
		return fmt.Errorf("unable to create http.Request, %s\n", err.Error())
	}
	req.Header.Add("Content-Type", "application/json")
	req.SetBasicAuth(a.ApiUser, a.ApiKey)

	resp, err := a.client.Do(req)
	if err != nil {
		return fmt.Errorf("error POSTing metrics, %s\n", err.Error())
	}
	defer resp.Body.Close()

	if resp.StatusCode < 200 || resp.StatusCode > 209 {
		return fmt.Errorf("received bad status code, %d\n", resp.StatusCode)
	}

	return nil
}

func (a *Cmp) SampleConfig() string {
	return sampleConfig
}

func (a *Cmp) Description() string {
	return "Configuration for Cmp Server to send metrics to."
}

func (a *Cmp) authenticatedUrl() string {

	return fmt.Sprintf("%s/metrics", a.CmpInstance)
}

func (a *Cmp) Close() error {
	return nil
}

func init() {
	outputs.Add("cmp", func() telegraf.Output {
		return &Cmp{}
	})
}
<commit_msg>Add elasticsearch mappings to cmp output, add cpu-usage (aggregated)<commit_after>package cmp

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/internal"
	"github.com/influxdata/telegraf/plugins/outputs"
)

type Cmp struct {
	ApiUser     string
	ApiKey      string
	ResourceId  string
	CmpInstance string
	Timeout     internal.Duration

	client *http.Client
}

var sampleConfig = `
  # Cmp Api User and Key
  api_user = "my-api-user" # required.
  api_key = "my-api-key" # required.
  resource_id = "1234"

  # Cmp Instance URL
  cmp_instance = "https://yourcmpinstance" # required

  # Connection timeout.
  # timeout = "5s"
`

var translateMap = map[string]Translation{
    "cpu-usage.idle": {
        Name: "cpu-usage",
        Unit: "percent",
        Conversion: subtract_from_100_percent,
    },
    "cpu-usage.user": {
        Name: "cpu-usage.user",
        Unit: "percent",
    },
	"cpu-usage.system": {
		Name: "cpu-usage.system",
		Unit: "percent",
	},
	"mem-available.percent": {
		Name:       "memory-usage",
		Unit:       "percent",
		Conversion: subtract_from_100_percent,
	},
	"system-load1": {
		Name: "load-avg-1",
	},
	"system-load5": {
		Name: "load-avg-5",
	},
	"system-load15": {
		Name: "load-avg-15",
	},
	"disk-used.percent": {
		Name: "disk-usage",
	},
	//     "system-uptime": {
	//         Name: "uptime",
	//     },
	"docker_cpu-usage.percent": {
		Name: "docker-cpu-usage.system",
		Unit: "percent",
	},
	"docker_mem-usage.percent": {
		Name: "docker-memory-usage",
		Unit: "percent",
	},
    "elasticsearch_cluster_health-status": {
        Name: "es-status",
        Unit: "",
        Conversion: es_cluster_health,
    },
    "elasticsearch_cluster_health-number.of.nodes": {
        Name: "es-nodes",
        Unit: "",
    },
    "elasticsearch_cluster_health-unassigned.shards": {
        Name: "es-unassigned-shards",
        Unit: "",
    },
    "elasticsearch_cluster_health-active.shards": {
        Name: "es-active-shards",
        Unit: "",
    },
    "elasticsearch_cluster_health-active.primary.shards": {
        Name: "es-primary-shards",
        Unit: "",
    },
    "elasticsearch_cluster_health-initializing.shards": {
        Name: "es-initializing-shards",
        Unit: "",
    },
    "elasticsearch_cluster_health-relocating.shards": {
        Name: "es-relocating-shards",
        Unit: "",
    },
    "elasticsearch_jvm-mem.heap.used.in.bytes": {
        Name: "es-heap.used",
        Unit: "B",
    },
    "elasticsearch_jvm-mem.heap.committed.in.bytes": {
        Name: "es-heap.committed",
        Unit: "B",
    },
    "elasticsearch_jvm-mem.non.heap.used.in.bytes": {
        Name: "es-nonheap.used",
        Unit: "B",
    },
    "elasticsearch_jvm-mem.non.heap.committed.in.bytes": {
        Name: "es-nonheap.committed",
        Unit: "B",
    },
    "elasticsearch_indices-search.query.total": {
        Name: "es-search-requests.query",
        Unit: "",
    },
    "elasticsearch_indices-search.fetch.total": {
        Name: "es-search-requests.fetch",
        Unit: "",
    },
    "elasticsearch_indices-search.query.time.in.millis": {
        Name: "es-search-time.query",
        Unit: "Ms",
    },
    "elasticsearch_indices-search.fetch.time.in.millis": {
        Name: "es-search-time.fetch",
        Unit: "Ms",
    },
    "elasticsearch_indices-get.total": {
        Name: "es-get-requests.get",
        Unit: "",
    },
    "elasticsearch_indices-get.exists.total": {
        Name: "es-get-requests.exists",
        Unit: "",
    },
    "elasticsearch_indices-get.missing.total": {
        Name: "es-get-requests.missing",
        Unit: "",
    },
    "elasticsearch_indices-get.time.in.millis": {
        Name: "es-get-time.get",
        Unit: "Ms",
    },
    "elasticsearch_indices-get.exists.time.in.millis": {
        Name: "es-get-time.exists",
        Unit: "Ms",
    },
    "elasticsearch_indices-get.missing.time.in.millis": {
        Name: "es-get-time.missing",
        Unit: "Ms",
    },
    "elasticsearch_indices-indexing.index.total": {
        Name: "es-index-requests.index",
        Unit: "",
    },
    "elasticsearch_indices-indexing.delete.total": {
        Name: "es-index-requests.delete",
        Unit: "",
    },
    "elasticsearch_indices-indexing.index.time.in.millis": {
        Name: "es-index-time.index",
        Unit: "",
    },
    "elasticsearch_indices-indexing.delete.time.in.millis": {
        Name: "es-index-time.delete",
        Unit: "",
    },
}

type Translation struct {
	Name       string
	Unit       string
	Conversion func(interface{}) interface{}
}

func subtract_from_100_percent(available interface{}) interface{} {
	return (100.0 - available.(float64))
}

func es_cluster_health(status interface{}) interface{} {
    switch status.(string) {
        case "green":
            return 0.0
        case "yellow":
            return 1.0
        case "red":
            return 2.0
        default:
            return 3.0
    }
}

func to_float64(value interface{}) float64 {
    switch v := value.(type) {
        case int64:
            return float64(v)
        default:
            return 0.0
    }
}

type CmpData struct {
	MonitoringSystem string      `json:"monitoring_system"`
	ResourceId       string      `json:"resource_id"`
	Metrics          []CmpMetric `json:"metrics"`
}

type CmpMetric struct {
	Metric string    `json:"metric"`
	Unit   string    `json:"unit"`
	Value  float64   `json:"value"`
	Time   time.Time `json:"time"`
}

func (data *CmpData) AddMetric(item CmpMetric) []CmpMetric {
	data.Metrics = append(data.Metrics, item)
	return data.Metrics
}

func (a *Cmp) Connect() error {
	if a.ApiUser == "" || a.ApiKey == "" || a.CmpInstance == "" || a.ResourceId == "" {
		return fmt.Errorf("api_user, api_key, resource_id and cmp_instance are required fields for cmp output")
	}
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	a.client = &http.Client{
		Transport: tr,
		Timeout:   a.Timeout.Duration,
	}
	return nil
}

func (a *Cmp) Write(metrics []telegraf.Metric) error {
	if len(metrics) == 0 {
		return nil
	}
	cmp_data := &CmpData{
		MonitoringSystem: "telegraf",
		ResourceId:       a.ResourceId,
	}

	for _, m := range metrics {

		suffix := ""
		cpu := m.Tags()["cpu"]
		path := m.Tags()["path"]
		container_name := m.Tags()["cont_name"]

		if len(cpu) > 0 && cpu != "cpu-total" {
			suffix = cpu[3:]
		} else if len(path) > 0 {
			suffix = path
		} else if len(container_name) > 0 {
			suffix = container_name
		}

		timestamp := m.Time()
		for k, v := range m.Fields() {
			metric_name := m.Name() + "-" + strings.Replace(k, "_", ".", -1)
			translation, found := translateMap[metric_name]
			if found {
				cmp_name := translation.Name
				if len(suffix) > 0 {
					cmp_name += "." + suffix
				}

				conversion := translation.Conversion
				if conversion != nil {
					v = conversion(v)
				}

				cmp_data.AddMetric(CmpMetric{
					Metric: cmp_name,
					Unit:   translation.Unit,
					Value:  to_float64(v),
					Time:   timestamp,
				})
			}
		}
	}

	cmp_bytes, err := json.Marshal(cmp_data)
	if err != nil {
		return fmt.Errorf("unable to marshal TimeSeries, %s\n", err.Error())
	}
	req, err := http.NewRequest("POST", a.authenticatedUrl(), bytes.NewBuffer(cmp_bytes))
	if err != nil {
		return fmt.Errorf("unable to create http.Request, %s\n", err.Error())
	}
	req.Header.Add("Content-Type", "application/json")
	req.SetBasicAuth(a.ApiUser, a.ApiKey)

	resp, err := a.client.Do(req)
	if err != nil {
		return fmt.Errorf("error POSTing metrics, %s\n", err.Error())
	}
	defer resp.Body.Close()

	if resp.StatusCode < 200 || resp.StatusCode > 209 {
		return fmt.Errorf("received bad status code, %d\n", resp.StatusCode)
	}

	return nil
}

func (a *Cmp) SampleConfig() string {
	return sampleConfig
}

func (a *Cmp) Description() string {
	return "Configuration for Cmp Server to send metrics to."
}

func (a *Cmp) authenticatedUrl() string {

	return fmt.Sprintf("%s/metrics", a.CmpInstance)
}

func (a *Cmp) Close() error {
	return nil
}

func init() {
	outputs.Add("cmp", func() telegraf.Output {
		return &Cmp{}
	})
}
<|endoftext|>


<commit_before>package scanner

import (
	"bytes"
	"fmt"
	"io"
	"syscall"
)

func compare(left *FileSystem, right *FileSystem, logWriter io.Writer) bool {
	if len(left.InodeTable) != len(right.InodeTable) {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "left vs. right: %d vs. %d inodes\n",
				len(left.InodeTable), len(right.InodeTable))
		}
		return false
	}
	if !compareDirectories(&left.Directory, &right.Directory, logWriter) {
		return false
	}
	if len(left.ObjectCache) != len(right.ObjectCache) {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "left vs. right: %d vs. %d objects\n",
				len(left.ObjectCache), len(right.ObjectCache))
		}
		return false
	}
	return compareObjects(left.ObjectCache, right.ObjectCache, logWriter)
}

func compareDirectories(left, right *Directory, logWriter io.Writer) bool {
	if left.name != right.name {
		fmt.Fprintf(logWriter, "dirname: left vs. right: %s vs. %s\n",
			left.name, right.name)
		return false
	}
	if !compareInodes(left.inode, right.inode, logWriter) {
		return false
	}
	if len(left.FileList) != len(right.FileList) {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "left vs. right: %d vs. %d files\n",
				len(left.FileList), len(right.FileList))
		}
		return false
	}
	if len(left.DirectoryList) != len(right.DirectoryList) {
		fmt.Fprintf(logWriter, "left vs. right: %d vs. %d subdirs\n",
			len(left.DirectoryList), len(right.DirectoryList))
		return false
	}
	for index := 0; index < len(left.FileList); index++ {
		if !compareFiles(left.FileList[index], right.FileList[index],
			logWriter) {
			return false
		}
	}
	for index := 0; index < len(left.DirectoryList); index++ {
		if !compareDirectories(left.DirectoryList[index],
			right.DirectoryList[index], logWriter) {
			return false
		}
	}
	return true
}

func compareFiles(left *File, right *File, logWriter io.Writer) bool {
	if left.name != right.name {
		fmt.Fprintf(logWriter, "filename: left vs. right: %s vs. %s\n",
			left.name, right.name)
		return false
	}
	if !compareInodes(left.inode, right.inode, logWriter) {
		return false
	}
	return true
}

func compareInodes(left *Inode, right *Inode, logWriter io.Writer) bool {
	if left.stat.Dev != right.stat.Dev {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "stat.Dev: left vs. right: %x vs. %x\n",
				left.stat.Dev, right.stat.Dev)
		}
		return false
	}
	if left.stat.Mode != right.stat.Mode {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "stat.Mode: left vs. right: %x vs. %x\n",
				left.stat.Mode, right.stat.Mode)
		}
		return false
	}
	if left.stat.Uid != right.stat.Uid {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "stat.Uid: left vs. right: %d vs. %d\n",
				left.stat.Uid, right.stat.Uid)
		}
		return false
	}
	if left.stat.Gid != right.stat.Gid {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "stat.Gid: left vs. right: %d vs. %d\n",
				left.stat.Gid, right.stat.Gid)
		}
		return false
	}
	if left.stat.Mode&syscall.S_IFMT != syscall.S_IFDIR {
		if left.stat.Size != right.stat.Size {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "stat.Size: left vs. right: %d vs. %d\n",
					left.stat.Size, right.stat.Size)
			}
			return false
		}
	}
	if left.stat.Mode&syscall.S_IFMT != syscall.S_IFDIR &&
		left.stat.Mode&syscall.S_IFMT != syscall.S_IFLNK {
		if left.stat.Mtim != right.stat.Mtim {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "stat.Mtim: left vs. right: %d vs. %d\n",
					left.stat.Mtim, right.stat.Mtim)
			}
			return false
		}
	}
	if left.stat.Mode&syscall.S_IFMT == syscall.S_IFREG {
		if bytes.Compare(left.hash, right.hash) != 0 {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "hash: left vs. right: %x vs. %x\n",
					left.hash, right.hash)
			}
			return false
		}
	}
	if left.stat.Mode&syscall.S_IFMT == syscall.S_IFBLK ||
		left.stat.Mode&syscall.S_IFMT == syscall.S_IFCHR {
		if left.stat.Rdev != right.stat.Rdev {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "stat.Rdev: left vs. right: %x vs. %x\n",
					left.stat.Rdev, right.stat.Rdev)
			}
			return false
		}
	}
	if left.stat.Mode&syscall.S_IFMT == syscall.S_IFLNK {
		if left.symlink != right.symlink {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "symlink: left vs. right: %s vs. %s\n",
					left.symlink, right.symlink)
			}
			return false
		}
	}
	return true
}

func compareObjects(left [][]byte, right [][]byte, logWriter io.Writer) bool {
	for index, leftHash := range left {
		if bytes.Compare(leftHash, right[index]) != 0 {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "hash: left vs. right: %x vs. %x\n",
					leftHash, right[index])
			}
			return false
		}
	}
	return true
}
<commit_msg>Minor idiomatic changes in for loops.<commit_after>package scanner

import (
	"bytes"
	"fmt"
	"io"
	"syscall"
)

func compare(left *FileSystem, right *FileSystem, logWriter io.Writer) bool {
	if len(left.InodeTable) != len(right.InodeTable) {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "left vs. right: %d vs. %d inodes\n",
				len(left.InodeTable), len(right.InodeTable))
		}
		return false
	}
	if !compareDirectories(&left.Directory, &right.Directory, logWriter) {
		return false
	}
	if len(left.ObjectCache) != len(right.ObjectCache) {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "left vs. right: %d vs. %d objects\n",
				len(left.ObjectCache), len(right.ObjectCache))
		}
		return false
	}
	return compareObjects(left.ObjectCache, right.ObjectCache, logWriter)
}

func compareDirectories(left, right *Directory, logWriter io.Writer) bool {
	if left.name != right.name {
		fmt.Fprintf(logWriter, "dirname: left vs. right: %s vs. %s\n",
			left.name, right.name)
		return false
	}
	if !compareInodes(left.inode, right.inode, logWriter) {
		return false
	}
	if len(left.FileList) != len(right.FileList) {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "left vs. right: %d vs. %d files\n",
				len(left.FileList), len(right.FileList))
		}
		return false
	}
	if len(left.DirectoryList) != len(right.DirectoryList) {
		fmt.Fprintf(logWriter, "left vs. right: %d vs. %d subdirs\n",
			len(left.DirectoryList), len(right.DirectoryList))
		return false
	}
	for index, leftFile := range left.FileList {
		if !compareFiles(leftFile, right.FileList[index], logWriter) {
			return false
		}
	}
	for index, leftDirectory := range left.DirectoryList {
		if !compareDirectories(leftDirectory, right.DirectoryList[index],
			logWriter) {
			return false
		}
	}
	return true
}

func compareFiles(left *File, right *File, logWriter io.Writer) bool {
	if left.name != right.name {
		fmt.Fprintf(logWriter, "filename: left vs. right: %s vs. %s\n",
			left.name, right.name)
		return false
	}
	if !compareInodes(left.inode, right.inode, logWriter) {
		return false
	}
	return true
}

func compareInodes(left *Inode, right *Inode, logWriter io.Writer) bool {
	if left.stat.Dev != right.stat.Dev {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "stat.Dev: left vs. right: %x vs. %x\n",
				left.stat.Dev, right.stat.Dev)
		}
		return false
	}
	if left.stat.Mode != right.stat.Mode {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "stat.Mode: left vs. right: %x vs. %x\n",
				left.stat.Mode, right.stat.Mode)
		}
		return false
	}
	if left.stat.Uid != right.stat.Uid {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "stat.Uid: left vs. right: %d vs. %d\n",
				left.stat.Uid, right.stat.Uid)
		}
		return false
	}
	if left.stat.Gid != right.stat.Gid {
		if logWriter != nil {
			fmt.Fprintf(logWriter, "stat.Gid: left vs. right: %d vs. %d\n",
				left.stat.Gid, right.stat.Gid)
		}
		return false
	}
	if left.stat.Mode&syscall.S_IFMT != syscall.S_IFDIR {
		if left.stat.Size != right.stat.Size {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "stat.Size: left vs. right: %d vs. %d\n",
					left.stat.Size, right.stat.Size)
			}
			return false
		}
	}
	if left.stat.Mode&syscall.S_IFMT != syscall.S_IFDIR &&
		left.stat.Mode&syscall.S_IFMT != syscall.S_IFLNK {
		if left.stat.Mtim != right.stat.Mtim {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "stat.Mtim: left vs. right: %d vs. %d\n",
					left.stat.Mtim, right.stat.Mtim)
			}
			return false
		}
	}
	if left.stat.Mode&syscall.S_IFMT == syscall.S_IFREG {
		if bytes.Compare(left.hash, right.hash) != 0 {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "hash: left vs. right: %x vs. %x\n",
					left.hash, right.hash)
			}
			return false
		}
	}
	if left.stat.Mode&syscall.S_IFMT == syscall.S_IFBLK ||
		left.stat.Mode&syscall.S_IFMT == syscall.S_IFCHR {
		if left.stat.Rdev != right.stat.Rdev {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "stat.Rdev: left vs. right: %x vs. %x\n",
					left.stat.Rdev, right.stat.Rdev)
			}
			return false
		}
	}
	if left.stat.Mode&syscall.S_IFMT == syscall.S_IFLNK {
		if left.symlink != right.symlink {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "symlink: left vs. right: %s vs. %s\n",
					left.symlink, right.symlink)
			}
			return false
		}
	}
	return true
}

func compareObjects(left [][]byte, right [][]byte, logWriter io.Writer) bool {
	for index, leftHash := range left {
		if bytes.Compare(leftHash, right[index]) != 0 {
			if logWriter != nil {
				fmt.Fprintf(logWriter, "hash: left vs. right: %x vs. %x\n",
					leftHash, right[index])
			}
			return false
		}
	}
	return true
}
<|endoftext|>


<commit_before><commit_msg>Check type before use type<commit_after><|endoftext|>


<commit_before>package build

import (
	"os"
	"path/filepath"
	"testing"

	api "github.com/goreleaser/goreleaser/build"
	"github.com/goreleaser/goreleaser/config"
	"github.com/goreleaser/goreleaser/context"
	"github.com/goreleaser/goreleaser/internal/artifact"
	"github.com/goreleaser/goreleaser/internal/testlib"
	"github.com/stretchr/testify/assert"
)

type fakeBuilder struct{}

func (*fakeBuilder) Default(build config.Build) config.Build {
	return build
}

func (*fakeBuilder) Build(ctx *context.Context, build config.Build, options api.Options) error {
	ctx.Artifacts.Add(artifact.Artifact{})
	return nil
}

func init() {
	api.Register("fake", &fakeBuilder{})
}

func TestPipeDescription(t *testing.T) {
	assert.NotEmpty(t, Pipe{}.String())
}

func TestBuild(t *testing.T) {
	var builder = &fakeBuilder{}
	api.Register("fake", builder)
	var config = config.Project{
		Builds: []config.Build{
			{
				Lang:   "fake",
				Binary: "testing",
				Flags:  "-n",
				Env:    []string{"BLAH=1"},
			},
		},
	}
	var ctx = context.New(config)
	assert.NoError(t, doBuild(ctx, ctx.Config.Builds[0], "darwin_amd64"))
}

func TestRunFullPipe(t *testing.T) {
	folder, back := testlib.Mktmp(t)
	defer back()
	var pre = filepath.Join(folder, "pre")
	var post = filepath.Join(folder, "post")
	var config = config.Project{
		Builds: []config.Build{
			{
				Lang:    "fake",
				Binary:  "testing",
				Flags:   "-v",
				Ldflags: "-X main.test=testing",
				Hooks: config.Hooks{
					Pre:  "touch " + pre,
					Post: "touch " + post,
				},
				Targets: []string{"whatever"},
			},
		},
		Archive: config.Archive{
			Replacements: map[string]string{
				"linux":  "linuxx",
				"darwin": "darwinn",
			},
		},
	}
	var ctx = context.New(config)
	assert.NoError(t, Pipe{}.Run(ctx))
	assert.Len(t, ctx.Artifacts.List(), 1)
	assert.True(t, exists(pre), pre)
	assert.True(t, exists(post), post)
}

func TestRunPipeFailingHooks(t *testing.T) {
	var config = config.Project{
		Builds: []config.Build{
			{
				Lang:    "fake",
				Binary:  "hooks",
				Hooks:   config.Hooks{},
				Targets: []string{"whatever"},
			},
		},
	}
	t.Run("pre-hook", func(t *testing.T) {
		var ctx = context.New(config)
		ctx.Config.Builds[0].Hooks.Pre = "exit 1"
		ctx.Config.Builds[0].Hooks.Post = "echo post"
		assert.EqualError(t, Pipe{}.Run(ctx), `pre hook failed: `)
	})
	t.Run("post-hook", func(t *testing.T) {
		var ctx = context.New(config)
		ctx.Config.Builds[0].Hooks.Pre = "echo pre"
		ctx.Config.Builds[0].Hooks.Post = "exit 1"
		assert.EqualError(t, Pipe{}.Run(ctx), `post hook failed: `)
	})
}

func TestDefaultNoBuilds(t *testing.T) {
	var ctx = &context.Context{
		Config: config.Project{},
	}
	assert.NoError(t, Pipe{}.Default(ctx))
}

func TestDefaultEmptyBuild(t *testing.T) {
	var ctx = &context.Context{
		Config: config.Project{
			Release: config.Release{
				GitHub: config.Repo{
					Name: "foo",
				},
			},
			Builds: []config.Build{
				{},
			},
		},
	}
	assert.NoError(t, Pipe{}.Default(ctx))
	var build = ctx.Config.Builds[0]
	assert.Equal(t, ctx.Config.Release.GitHub.Name, build.Binary)
	assert.Equal(t, ".", build.Main)
	assert.Equal(t, []string{"linux", "darwin"}, build.Goos)
	assert.Equal(t, []string{"amd64", "386"}, build.Goarch)
	assert.Equal(t, []string{"6"}, build.Goarm)
	assert.Equal(t, "-s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}}", build.Ldflags)
}

func TestDefaultPartialBuilds(t *testing.T) {
	var ctx = &context.Context{
		Config: config.Project{
			Builds: []config.Build{
				{
					Binary: "bar",
					Goos:   []string{"linux"},
					Main:   "./cmd/main.go",
				},
				{
					Binary:  "foo",
					Ldflags: "-s -w",
					Goarch:  []string{"386"},
				},
			},
		},
	}
	assert.NoError(t, Pipe{}.Default(ctx))
	t.Run("build0", func(t *testing.T) {
		var build = ctx.Config.Builds[0]
		assert.Equal(t, "bar", build.Binary)
		assert.Equal(t, "./cmd/main.go", build.Main)
		assert.Equal(t, []string{"linux"}, build.Goos)
		assert.Equal(t, []string{"amd64", "386"}, build.Goarch)
		assert.Equal(t, []string{"6"}, build.Goarm)
		assert.Equal(t, "-s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}}", build.Ldflags)
	})
	t.Run("build1", func(t *testing.T) {
		var build = ctx.Config.Builds[1]
		assert.Equal(t, "foo", build.Binary)
		assert.Equal(t, ".", build.Main)
		assert.Equal(t, []string{"linux", "darwin"}, build.Goos)
		assert.Equal(t, []string{"386"}, build.Goarch)
		assert.Equal(t, []string{"6"}, build.Goarm)
		assert.Equal(t, "-s -w", build.Ldflags)
	})
}

func TestDefaultFillSingleBuild(t *testing.T) {
	_, back := testlib.Mktmp(t)
	defer back()

	var ctx = &context.Context{
		Config: config.Project{
			Release: config.Release{
				GitHub: config.Repo{
					Name: "foo",
				},
			},
			SingleBuild: config.Build{
				Main: "testreleaser",
			},
		},
	}
	assert.NoError(t, Pipe{}.Default(ctx))
	assert.Len(t, ctx.Config.Builds, 1)
	assert.Equal(t, ctx.Config.Builds[0].Binary, "foo")
}

func TestExtWindows(t *testing.T) {
	assert.Equal(t, ".exe", extFor("windows_amd64"))
	assert.Equal(t, ".exe", extFor("windows_386"))
}

func TestExtOthers(t *testing.T) {
	assert.Empty(t, "", extFor("linux_amd64"))
	assert.Empty(t, "", extFor("linuxwin_386"))
	assert.Empty(t, "", extFor("winasdasd_sad"))
}

//
// Helpers
//

func exists(file string) bool {
	_, err := os.Stat(file)
	return !os.IsNotExist(err)
}
<commit_msg>test: cover pipeline/build 100%<commit_after>package build

import (
	"errors"
	"os"
	"path/filepath"
	"testing"

	api "github.com/goreleaser/goreleaser/build"
	"github.com/goreleaser/goreleaser/config"
	"github.com/goreleaser/goreleaser/context"
	"github.com/goreleaser/goreleaser/internal/artifact"
	"github.com/goreleaser/goreleaser/internal/testlib"
	"github.com/stretchr/testify/assert"
)

type fakeBuilder struct {
	fail bool
}

func (*fakeBuilder) Default(build config.Build) config.Build {
	return build
}

var errFailedBuild = errors.New("fake builder failed")

func (f *fakeBuilder) Build(ctx *context.Context, build config.Build, options api.Options) error {
	if f.fail {
		return errFailedBuild
	}
	ctx.Artifacts.Add(artifact.Artifact{})
	return nil
}

func init() {
	api.Register("fake", &fakeBuilder{})
	api.Register("fakeFail", &fakeBuilder{
		fail: true,
	})
}

func TestPipeDescription(t *testing.T) {
	assert.NotEmpty(t, Pipe{}.String())
}

func TestBuild(t *testing.T) {
	var config = config.Project{
		Builds: []config.Build{
			{
				Lang:   "fake",
				Binary: "testing",
				Flags:  "-n",
				Env:    []string{"BLAH=1"},
			},
		},
	}
	var ctx = context.New(config)
	assert.NoError(t, doBuild(ctx, ctx.Config.Builds[0], "darwin_amd64"))
}

func TestRunPipe(t *testing.T) {
	var config = config.Project{
		Builds: []config.Build{
			{
				Lang:    "fake",
				Binary:  "testing",
				Flags:   "-v",
				Ldflags: "-X main.test=testing",
				Targets: []string{"whatever"},
			},
		},
	}
	var ctx = context.New(config)
	assert.NoError(t, Pipe{}.Run(ctx))
	assert.Len(t, ctx.Artifacts.List(), 1)
}

func TestRunFullPipe(t *testing.T) {
	folder, back := testlib.Mktmp(t)
	defer back()
	var pre = filepath.Join(folder, "pre")
	var post = filepath.Join(folder, "post")
	var config = config.Project{
		Builds: []config.Build{
			{
				Lang:    "fake",
				Binary:  "testing",
				Flags:   "-v",
				Ldflags: "-X main.test=testing",
				Hooks: config.Hooks{
					Pre:  "touch " + pre,
					Post: "touch " + post,
				},
				Targets: []string{"whatever"},
			},
		},
	}
	var ctx = context.New(config)
	assert.NoError(t, Pipe{}.Run(ctx))
	assert.Len(t, ctx.Artifacts.List(), 1)
	assert.True(t, exists(pre), pre)
	assert.True(t, exists(post), post)
}

func TestRunFullPipeFail(t *testing.T) {
	folder, back := testlib.Mktmp(t)
	defer back()
	var pre = filepath.Join(folder, "pre")
	var post = filepath.Join(folder, "post")
	var config = config.Project{
		Builds: []config.Build{
			{
				Lang:    "fakeFail",
				Binary:  "testing",
				Flags:   "-v",
				Ldflags: "-X main.test=testing",
				Hooks: config.Hooks{
					Pre:  "touch " + pre,
					Post: "touch " + post,
				},
				Targets: []string{"whatever"},
			},
		},
	}
	var ctx = context.New(config)
	assert.EqualError(t, Pipe{}.Run(ctx), errFailedBuild.Error())
	assert.Len(t, ctx.Artifacts.List(), 0)
	assert.True(t, exists(pre), pre)
	assert.False(t, exists(post), post)
}

func TestRunPipeFailingHooks(t *testing.T) {
	var config = config.Project{
		Builds: []config.Build{
			{
				Lang:    "fake",
				Binary:  "hooks",
				Hooks:   config.Hooks{},
				Targets: []string{"whatever"},
			},
		},
	}
	t.Run("pre-hook", func(t *testing.T) {
		var ctx = context.New(config)
		ctx.Config.Builds[0].Hooks.Pre = "exit 1"
		ctx.Config.Builds[0].Hooks.Post = "echo post"
		assert.EqualError(t, Pipe{}.Run(ctx), `pre hook failed: `)
	})
	t.Run("post-hook", func(t *testing.T) {
		var ctx = context.New(config)
		ctx.Config.Builds[0].Hooks.Pre = "echo pre"
		ctx.Config.Builds[0].Hooks.Post = "exit 1"
		assert.EqualError(t, Pipe{}.Run(ctx), `post hook failed: `)
	})
}

func TestDefaultNoBuilds(t *testing.T) {
	var ctx = &context.Context{
		Config: config.Project{},
	}
	assert.NoError(t, Pipe{}.Default(ctx))
}

func TestDefaultEmptyBuild(t *testing.T) {
	var ctx = &context.Context{
		Config: config.Project{
			Release: config.Release{
				GitHub: config.Repo{
					Name: "foo",
				},
			},
			Builds: []config.Build{
				{},
			},
		},
	}
	assert.NoError(t, Pipe{}.Default(ctx))
	var build = ctx.Config.Builds[0]
	assert.Equal(t, ctx.Config.Release.GitHub.Name, build.Binary)
	assert.Equal(t, ".", build.Main)
	assert.Equal(t, []string{"linux", "darwin"}, build.Goos)
	assert.Equal(t, []string{"amd64", "386"}, build.Goarch)
	assert.Equal(t, []string{"6"}, build.Goarm)
	assert.Equal(t, "-s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}}", build.Ldflags)
}

func TestDefaultPartialBuilds(t *testing.T) {
	var ctx = &context.Context{
		Config: config.Project{
			Builds: []config.Build{
				{
					Binary: "bar",
					Goos:   []string{"linux"},
					Main:   "./cmd/main.go",
				},
				{
					Binary:  "foo",
					Ldflags: "-s -w",
					Goarch:  []string{"386"},
				},
			},
		},
	}
	assert.NoError(t, Pipe{}.Default(ctx))
	t.Run("build0", func(t *testing.T) {
		var build = ctx.Config.Builds[0]
		assert.Equal(t, "bar", build.Binary)
		assert.Equal(t, "./cmd/main.go", build.Main)
		assert.Equal(t, []string{"linux"}, build.Goos)
		assert.Equal(t, []string{"amd64", "386"}, build.Goarch)
		assert.Equal(t, []string{"6"}, build.Goarm)
		assert.Equal(t, "-s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}}", build.Ldflags)
	})
	t.Run("build1", func(t *testing.T) {
		var build = ctx.Config.Builds[1]
		assert.Equal(t, "foo", build.Binary)
		assert.Equal(t, ".", build.Main)
		assert.Equal(t, []string{"linux", "darwin"}, build.Goos)
		assert.Equal(t, []string{"386"}, build.Goarch)
		assert.Equal(t, []string{"6"}, build.Goarm)
		assert.Equal(t, "-s -w", build.Ldflags)
	})
}

func TestDefaultFillSingleBuild(t *testing.T) {
	_, back := testlib.Mktmp(t)
	defer back()

	var ctx = &context.Context{
		Config: config.Project{
			Release: config.Release{
				GitHub: config.Repo{
					Name: "foo",
				},
			},
			SingleBuild: config.Build{
				Main: "testreleaser",
			},
		},
	}
	assert.NoError(t, Pipe{}.Default(ctx))
	assert.Len(t, ctx.Config.Builds, 1)
	assert.Equal(t, ctx.Config.Builds[0].Binary, "foo")
}

func TestExtWindows(t *testing.T) {
	assert.Equal(t, ".exe", extFor("windows_amd64"))
	assert.Equal(t, ".exe", extFor("windows_386"))
}

func TestExtOthers(t *testing.T) {
	assert.Empty(t, "", extFor("linux_amd64"))
	assert.Empty(t, "", extFor("linuxwin_386"))
	assert.Empty(t, "", extFor("winasdasd_sad"))
}

//
// Helpers
//

func exists(file string) bool {
	_, err := os.Stat(file)
	return !os.IsNotExist(err)
}
<|endoftext|>


<commit_before>package service

import (
	"github.com/boivie/lovebeat-go/alert"
	"github.com/boivie/lovebeat-go/backend"
	"github.com/op/go-logging"
	"math"
	"regexp"
	"sort"
	"time"
)

const (
	MAX_UNPROCESSED_PACKETS = 1000
	EXPIRY_INTERVAL         = 1

	// Number of samples (diffs) we require to be able to
	// properly calculate an "auto" timeout
	AUTO_MIN_SAMPLES = 5
)

var (
	log          = logging.MustGetLogger("lovebeat")
	EMPTY_REGEXP = regexp.MustCompile("^$")
)

type Services struct {
	be                   backend.Backend
	alerters             []alert.Alerter
	services             map[string]*Service
	views                map[string]*View
	beatCmdChan          chan string
	upsertServiceCmdChan chan *upsertServiceCmd
	deleteServiceCmdChan chan string
	deleteViewCmdChan    chan string
	upsertViewCmdChan    chan *upsertViewCmd
	getServicesChan      chan *getServicesCmd
	getServiceChan       chan *getServiceCmd
	getViewsChan         chan *getViewsCmd
	getViewChan          chan *getViewCmd
}

type Service struct {
	svcs *Services
	data backend.StoredService
}

type View struct {
	svcs *Services
	data backend.StoredView
	ree  *regexp.Regexp
}

func now() int64 { return time.Now().Unix() }

func (s *Service) getExpiry(timeout int64) int64 {
	if timeout <= 0 {
		return 0
	}
	return s.data.LastBeat + timeout
}

func (s *Service) name() string { return s.data.Name }
func (v *View) name() string    { return v.data.Name }

func calcTimeout(values []int64) int64 {
	diffs := calcDiffs(values)
	if len(diffs) < AUTO_MIN_SAMPLES {
		log.Debug("AUTO-TIMEOUT: Not enough samples to calculate")
		return TIMEOUT_AUTO
	}

	ret := int64(math.Ceil(float64(median(diffs)) * 1.5))
	log.Debug("AUTO-TIMEOUT: vale calculated as %d", ret)
	return ret
}

func calcDiffs(values []int64) []int64 {
	var p []int64
	for i := 1; i < len(values); i++ {
		if values[i-1] != 0 && values[i] != 0 {
			p = append(p, values[i]-values[i-1])
		}
	}
	return p
}

type int64arr []int64

func (a int64arr) Len() int           { return len(a) }
func (a int64arr) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a int64arr) Less(i, j int) bool { return a[i] < a[j] }

func median(numbers []int64) int64 {
	sort.Sort(int64arr(numbers))
	middle := len(numbers) / 2
	result := numbers[middle]
	if len(numbers)%2 == 0 {
		result = (result + numbers[middle-1]) / 2
	}
	return result
}

// Called before saving - to update internal states
func (s *Service) update(ts int64) {
	s.data.State = s.stateAt(ts)

	if s.data.WarningTimeout == TIMEOUT_AUTO {
		s.data.WarningTimeout = calcTimeout(s.data.PreviousBeats)
	}
	if s.data.ErrorTimeout == TIMEOUT_AUTO {
		s.data.ErrorTimeout = calcTimeout(s.data.PreviousBeats)
	}
}

func (s *Service) stateAt(ts int64) string {
	var state = backend.STATE_OK
	var warningExpiry = s.getExpiry(s.data.WarningTimeout)
	var errorExpiry = s.getExpiry(s.data.ErrorTimeout)
	if warningExpiry > 0 && ts >= warningExpiry {
		state = backend.STATE_WARNING
	}
	if errorExpiry > 0 && ts >= errorExpiry {
		state = backend.STATE_ERROR
	}
	return state
}

func (s *Service) registerBeat(ts int64) {
	s.data.LastBeat = ts
	s.data.PreviousBeats = append(s.data.PreviousBeats[1:], ts)
}

func (s *Service) save(ref *Service, ts int64) {
	if s.data.State != ref.data.State {
		log.Info("SERVICE '%s', state %s -> %s",
			s.name(), ref.data.State, s.data.State)
	}
	if s.data.WarningTimeout != ref.data.WarningTimeout {
		log.Info("SERVICE '%s', warn %d -> %d",
			s.name(), ref.data.WarningTimeout,
			s.data.WarningTimeout)
	}
	if s.data.ErrorTimeout != ref.data.ErrorTimeout {
		log.Info("SERVICE '%s', err %d -> %d",
			s.name(), ref.data.ErrorTimeout,
			s.data.ErrorTimeout)
	}
	s.data.LastUpdated = ts
	s.svcs.be.SaveService(&s.data)
}

func (v *View) refresh(ts int64) {
	v.data.State = backend.STATE_OK
	for _, s := range v.svcs.services {
		if v.ree.Match([]byte(s.name())) {
			if s.data.State == backend.STATE_WARNING && v.data.State == backend.STATE_OK {
				v.data.State = backend.STATE_WARNING
			} else if s.data.State == backend.STATE_ERROR {
				v.data.State = backend.STATE_ERROR
			}
		}
	}
}

func (v *View) contains(serviceName string) bool {
	return v.ree.Match([]byte(serviceName))
}

func (v *View) save(ref *View, ts int64) {
	if v.data.State != ref.data.State {
		if ref.data.State == backend.STATE_OK {
			v.data.IncidentNbr += 1
		}
	}
	v.data.LastUpdated = ts
	v.svcs.be.SaveView(&v.data)
}

func (v *View) sendAlerts(ref *View, ts int64) {
	if v.data.State != ref.data.State {
		log.Info("VIEW '%s', %d: state %s -> %s",
			v.name(), v.data.IncidentNbr, ref.data.State,
			v.data.State)

		var services = make([]backend.StoredService, 0, 10)
		for _, s := range v.svcs.services {
			if (s.data.State == backend.STATE_WARNING ||
				s.data.State == backend.STATE_ERROR) &&
				v.contains(s.name()) {
				services = append(services, s.data)
				if len(services) == 10 {
					break
				}
			}
		}

		for _, a := range v.svcs.alerters {
			a.Notify(ref.data, v.data, services)
		}
	}
}

func (s *Service) updateViews(ts int64) {
	for _, view := range s.svcs.views {
		if view.ree.Match([]byte(s.name())) {
			var ref = *view
			view.refresh(ts)
			view.save(&ref, ts)
			view.sendAlerts(&ref, ts)
		}
	}
}

func (svcs *Services) getService(name string) *Service {
	var s, ok = svcs.services[name]
	if !ok {
		log.Debug("Asked for unknown service %s", name)
		s = &Service{
			svcs: svcs,
			data: backend.StoredService{
				Name:           name,
				LastValue:      -1,
				LastBeat:       -1,
				PreviousBeats:  make([]int64, backend.PREVIOUS_BEATS_COUNT),
				LastUpdated:    -1,
				WarningTimeout: -1,
				ErrorTimeout:   -1,
				State:          backend.STATE_PAUSED,
			},
		}
		svcs.services[name] = s
	}
	return s
}

func (svcs *Services) getView(name string) *View {
	var s, ok = svcs.views[name]
	if !ok {
		log.Debug("Asked for unknown view %s", name)
		s = &View{
			svcs: svcs,
			data: backend.StoredView{
				Name:        name,
				State:       backend.STATE_OK,
				LastUpdated: -1,
				Regexp:      "^$",
			},
			ree: EMPTY_REGEXP}
		svcs.views[name] = s
	}
	return s
}

func (svcs *Services) createView(name string, expr string, alertMail string,
	webhooks string, ts int64) {
	var ree, err = regexp.Compile(expr)
	if err != nil {
		log.Error("Invalid regexp: %s", err)
		return
	}

	var view = svcs.getView(name)
	var ref = *view
	view.data.Regexp = expr
	view.ree = ree
	view.data.AlertMail = alertMail
	view.data.Webhooks = webhooks
	view.refresh(ts)
	view.save(&ref, ts)

	log.Info("VIEW '%s' created or updated.", name)
}

func (svcs *Services) Monitor() {
	period := time.Duration(EXPIRY_INTERVAL) * time.Second
	ticker := time.NewTicker(period)
	for {
		select {
		case <-ticker.C:
			var ts = now()
			for _, s := range svcs.services {
				if s.data.State == backend.STATE_PAUSED || s.data.State == s.stateAt(ts) {
					continue
				}
				var ref = *s
				s.update(ts)
				s.save(&ref, ts)
				s.updateViews(ts)
			}
		case c := <-svcs.upsertViewCmdChan:
			log.Debug("Create or update view %s", c.View)
			svcs.createView(c.View, c.Regexp, c.AlertMail,
				c.Webhooks, now())
		case c := <-svcs.deleteViewCmdChan:
			log.Debug("Delete view %s", c)
			delete(svcs.views, c)
			svcs.be.DeleteView(c)
		case c := <-svcs.getServicesChan:
			var ret []backend.StoredService
			var view, ok = svcs.views[c.View]
			if ok {
				for _, s := range svcs.services {
					if view.contains(s.name()) {
						ret = append(ret, s.data)
					}
				}
			}
			c.Reply <- ret
		case c := <-svcs.getServiceChan:
			var ret = svcs.services[c.Name]
			c.Reply <- ret.data
		case c := <-svcs.getViewsChan:
			var ret []backend.StoredView
			for _, v := range svcs.views {
				ret = append(ret, v.data)
			}
			c.Reply <- ret
		case c := <-svcs.getViewChan:
			var ret = svcs.views[c.Name]
			c.Reply <- ret.data
		case c := <-svcs.beatCmdChan:
			var ts = now()
			var s = svcs.getService(c)
			var ref = *s
			s.registerBeat(ts)
			log.Debug("Beat from %s", s.name())
			s.update(ts)
			s.save(&ref, ts)
			s.updateViews(ts)
		case c := <-svcs.deleteServiceCmdChan:
			var ts = now()
			var s = svcs.getService(c)
			delete(svcs.services, s.name())
			svcs.be.DeleteService(s.name())
			s.updateViews(ts)
		case c := <-svcs.upsertServiceCmdChan:
			var ts = now()
			var s = svcs.getService(c.Service)
			var ref = *s
			// Don't re-calculate 'auto' if we already have values
			if c.WarningTimeout == TIMEOUT_AUTO &&
				s.data.WarningTimeout == -1 {
				s.data.WarningTimeout = TIMEOUT_AUTO
				s.data.PreviousBeats = make([]int64, backend.PREVIOUS_BEATS_COUNT)
			} else if c.WarningTimeout == TIMEOUT_CLEAR {
				s.data.WarningTimeout = TIMEOUT_CLEAR
			} else if c.WarningTimeout > 0 {
				s.data.WarningTimeout = c.WarningTimeout
			}
			if c.ErrorTimeout == TIMEOUT_AUTO &&
				s.data.ErrorTimeout == -1 {
				s.data.ErrorTimeout = TIMEOUT_AUTO
				s.data.PreviousBeats = make([]int64, backend.PREVIOUS_BEATS_COUNT)
			} else if c.ErrorTimeout == TIMEOUT_CLEAR {
				s.data.ErrorTimeout = TIMEOUT_CLEAR
			} else if c.ErrorTimeout > 0 {
				s.data.ErrorTimeout = c.ErrorTimeout
			}
			s.update(ts)
			s.save(&ref, ts)
			s.updateViews(ts)
		}
	}
}

func NewServices(beiface backend.Backend, alerters []alert.Alerter) *Services {
	svcs := new(Services)
	svcs.be = beiface
	svcs.alerters = alerters
	svcs.beatCmdChan = make(chan string, MAX_UNPROCESSED_PACKETS)
	svcs.deleteServiceCmdChan = make(chan string, 5)
	svcs.upsertServiceCmdChan = make(chan *upsertServiceCmd, 5)
	svcs.deleteViewCmdChan = make(chan string, 5)
	svcs.upsertViewCmdChan = make(chan *upsertViewCmd, 5)
	svcs.getServicesChan = make(chan *getServicesCmd, 5)
	svcs.getServiceChan = make(chan *getServiceCmd, 5)
	svcs.getViewsChan = make(chan *getViewsCmd, 5)
	svcs.getViewChan = make(chan *getViewCmd, 5)
	svcs.services = make(map[string]*Service)
	svcs.views = make(map[string]*View)

	for _, s := range svcs.be.LoadServices() {
		var svc = &Service{svcs: svcs, data: *s}
		if svc.data.PreviousBeats == nil || len(svc.data.PreviousBeats) != backend.PREVIOUS_BEATS_COUNT {
			svc.data.PreviousBeats = make([]int64, backend.PREVIOUS_BEATS_COUNT)
		}
		svcs.services[s.Name] = svc
	}

	for _, v := range svcs.be.LoadViews() {
		var ree, _ = regexp.Compile(v.Regexp)
		svcs.views[v.Name] = &View{svcs: svcs, data: *v, ree: ree}
	}

	return svcs
}
<commit_msg>Refactoring (3/10)<commit_after>package service

import (
	"github.com/boivie/lovebeat-go/alert"
	"github.com/boivie/lovebeat-go/backend"
	"github.com/op/go-logging"
	"math"
	"regexp"
	"sort"
	"time"
)

const (
	MAX_UNPROCESSED_PACKETS = 1000
	EXPIRY_INTERVAL         = 1

	// Number of samples (diffs) we require to be able to
	// properly calculate an "auto" timeout
	AUTO_MIN_SAMPLES = 5
)

var (
	log          = logging.MustGetLogger("lovebeat")
	EMPTY_REGEXP = regexp.MustCompile("^$")
)

type Services struct {
	be                   backend.Backend
	alerters             []alert.Alerter
	services             map[string]*Service
	views                map[string]*View
	beatCmdChan          chan string
	upsertServiceCmdChan chan *upsertServiceCmd
	deleteServiceCmdChan chan string
	deleteViewCmdChan    chan string
	upsertViewCmdChan    chan *upsertViewCmd
	getServicesChan      chan *getServicesCmd
	getServiceChan       chan *getServiceCmd
	getViewsChan         chan *getViewsCmd
	getViewChan          chan *getViewCmd
}

type Service struct {
	svcs *Services
	data backend.StoredService
}

type View struct {
	svcs *Services
	data backend.StoredView
	ree  *regexp.Regexp
}

func now() int64 { return time.Now().Unix() }

func (s *Service) getExpiry(timeout int64) int64 {
	if timeout <= 0 {
		return 0
	}
	return s.data.LastBeat + timeout
}

func (s *Service) name() string { return s.data.Name }
func (v *View) name() string    { return v.data.Name }

func calcTimeout(values []int64) int64 {
	diffs := calcDiffs(values)
	if len(diffs) < AUTO_MIN_SAMPLES {
		log.Debug("AUTO-TIMEOUT: Not enough samples to calculate")
		return TIMEOUT_AUTO
	}

	ret := int64(math.Ceil(float64(median(diffs)) * 1.5))
	log.Debug("AUTO-TIMEOUT: vale calculated as %d", ret)
	return ret
}

func calcDiffs(values []int64) []int64 {
	var p []int64
	for i := 1; i < len(values); i++ {
		if values[i-1] != 0 && values[i] != 0 {
			p = append(p, values[i]-values[i-1])
		}
	}
	return p
}

type int64arr []int64

func (a int64arr) Len() int           { return len(a) }
func (a int64arr) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a int64arr) Less(i, j int) bool { return a[i] < a[j] }

func median(numbers []int64) int64 {
	sort.Sort(int64arr(numbers))
	middle := len(numbers) / 2
	result := numbers[middle]
	if len(numbers)%2 == 0 {
		result = (result + numbers[middle-1]) / 2
	}
	return result
}

// Called before saving - to update internal states
func (s *Service) update(ts int64) {
	s.data.State = s.stateAt(ts)

	if s.data.WarningTimeout == TIMEOUT_AUTO {
		s.data.WarningTimeout = calcTimeout(s.data.PreviousBeats)
	}
	if s.data.ErrorTimeout == TIMEOUT_AUTO {
		s.data.ErrorTimeout = calcTimeout(s.data.PreviousBeats)
	}
}

func (s *Service) stateAt(ts int64) string {
	var state = backend.STATE_OK
	var warningExpiry = s.getExpiry(s.data.WarningTimeout)
	var errorExpiry = s.getExpiry(s.data.ErrorTimeout)
	if warningExpiry > 0 && ts >= warningExpiry {
		state = backend.STATE_WARNING
	}
	if errorExpiry > 0 && ts >= errorExpiry {
		state = backend.STATE_ERROR
	}
	return state
}

func (s *Service) registerBeat(ts int64) {
	s.data.LastBeat = ts
	s.data.PreviousBeats = append(s.data.PreviousBeats[1:], ts)
}

func (s *Service) save(ref *Service, ts int64) {
	if s.data.State != ref.data.State {
		log.Info("SERVICE '%s', state %s -> %s",
			s.name(), ref.data.State, s.data.State)
	}
	if s.data.WarningTimeout != ref.data.WarningTimeout {
		log.Info("SERVICE '%s', warn %d -> %d",
			s.name(), ref.data.WarningTimeout,
			s.data.WarningTimeout)
	}
	if s.data.ErrorTimeout != ref.data.ErrorTimeout {
		log.Info("SERVICE '%s', err %d -> %d",
			s.name(), ref.data.ErrorTimeout,
			s.data.ErrorTimeout)
	}
	s.data.LastUpdated = ts
	s.svcs.be.SaveService(&s.data)
}

func (v *View) refresh(ts int64) {
	v.data.State = backend.STATE_OK
	for _, s := range v.svcs.services {
		if v.ree.Match([]byte(s.name())) {
			if s.data.State == backend.STATE_WARNING && v.data.State == backend.STATE_OK {
				v.data.State = backend.STATE_WARNING
			} else if s.data.State == backend.STATE_ERROR {
				v.data.State = backend.STATE_ERROR
			}
		}
	}
}

func (v *View) contains(serviceName string) bool {
	return v.ree.Match([]byte(serviceName))
}

func (v *View) save(ref *View, ts int64) {
	if v.data.State != ref.data.State {
		if ref.data.State == backend.STATE_OK {
			v.data.IncidentNbr += 1
		}
	}
	v.data.LastUpdated = ts
	v.svcs.be.SaveView(&v.data)
}

func (v *View) sendAlerts(ref *View, ts int64) {
	if v.data.State != ref.data.State {
		log.Info("VIEW '%s', %d: state %s -> %s",
			v.name(), v.data.IncidentNbr, ref.data.State,
			v.data.State)

		var services = make([]backend.StoredService, 0, 10)
		for _, s := range v.svcs.services {
			if (s.data.State == backend.STATE_WARNING ||
				s.data.State == backend.STATE_ERROR) &&
				v.contains(s.name()) {
				services = append(services, s.data)
				if len(services) == 10 {
					break
				}
			}
		}

		for _, a := range v.svcs.alerters {
			a.Notify(ref.data, v.data, services)
		}
	}
}

func (svcs *Services) updateViews(ts int64, serviceName string) {
	for _, view := range svcs.views {
		if view.ree.Match([]byte(serviceName)) {
			var ref = *view
			view.refresh(ts)
			view.save(&ref, ts)
			view.sendAlerts(&ref, ts)
		}
	}
}

func (svcs *Services) getService(name string) *Service {
	var s, ok = svcs.services[name]
	if !ok {
		log.Debug("Asked for unknown service %s", name)
		s = &Service{
			svcs: svcs,
			data: backend.StoredService{
				Name:           name,
				LastValue:      -1,
				LastBeat:       -1,
				PreviousBeats:  make([]int64, backend.PREVIOUS_BEATS_COUNT),
				LastUpdated:    -1,
				WarningTimeout: -1,
				ErrorTimeout:   -1,
				State:          backend.STATE_PAUSED,
			},
		}
		svcs.services[name] = s
	}
	return s
}

func (svcs *Services) getView(name string) *View {
	var s, ok = svcs.views[name]
	if !ok {
		log.Debug("Asked for unknown view %s", name)
		s = &View{
			svcs: svcs,
			data: backend.StoredView{
				Name:        name,
				State:       backend.STATE_OK,
				LastUpdated: -1,
				Regexp:      "^$",
			},
			ree: EMPTY_REGEXP}
		svcs.views[name] = s
	}
	return s
}

func (svcs *Services) createView(name string, expr string, alertMail string,
	webhooks string, ts int64) {
	var ree, err = regexp.Compile(expr)
	if err != nil {
		log.Error("Invalid regexp: %s", err)
		return
	}

	var view = svcs.getView(name)
	var ref = *view
	view.data.Regexp = expr
	view.ree = ree
	view.data.AlertMail = alertMail
	view.data.Webhooks = webhooks
	view.refresh(ts)
	view.save(&ref, ts)

	log.Info("VIEW '%s' created or updated.", name)
}

func (svcs *Services) Monitor() {
	period := time.Duration(EXPIRY_INTERVAL) * time.Second
	ticker := time.NewTicker(period)
	for {
		select {
		case <-ticker.C:
			var ts = now()
			for _, s := range svcs.services {
				if s.data.State == backend.STATE_PAUSED || s.data.State == s.stateAt(ts) {
					continue
				}
				var ref = *s
				s.update(ts)
				s.save(&ref, ts)
				svcs.updateViews(ts, s.name())
			}
		case c := <-svcs.upsertViewCmdChan:
			log.Debug("Create or update view %s", c.View)
			svcs.createView(c.View, c.Regexp, c.AlertMail,
				c.Webhooks, now())
		case c := <-svcs.deleteViewCmdChan:
			log.Debug("Delete view %s", c)
			delete(svcs.views, c)
			svcs.be.DeleteView(c)
		case c := <-svcs.getServicesChan:
			var ret []backend.StoredService
			var view, ok = svcs.views[c.View]
			if ok {
				for _, s := range svcs.services {
					if view.contains(s.name()) {
						ret = append(ret, s.data)
					}
				}
			}
			c.Reply <- ret
		case c := <-svcs.getServiceChan:
			var ret = svcs.services[c.Name]
			c.Reply <- ret.data
		case c := <-svcs.getViewsChan:
			var ret []backend.StoredView
			for _, v := range svcs.views {
				ret = append(ret, v.data)
			}
			c.Reply <- ret
		case c := <-svcs.getViewChan:
			var ret = svcs.views[c.Name]
			c.Reply <- ret.data
		case c := <-svcs.beatCmdChan:
			var ts = now()
			var s = svcs.getService(c)
			var ref = *s
			s.registerBeat(ts)
			log.Debug("Beat from %s", s.name())
			s.update(ts)
			s.save(&ref, ts)
			svcs.updateViews(ts, s.name())
		case c := <-svcs.deleteServiceCmdChan:
			var ts = now()
			var s = svcs.getService(c)
			delete(svcs.services, s.name())
			svcs.be.DeleteService(s.name())
			svcs.updateViews(ts, s.name())
		case c := <-svcs.upsertServiceCmdChan:
			var ts = now()
			var s = svcs.getService(c.Service)
			var ref = *s
			// Don't re-calculate 'auto' if we already have values
			if c.WarningTimeout == TIMEOUT_AUTO &&
				s.data.WarningTimeout == -1 {
				s.data.WarningTimeout = TIMEOUT_AUTO
				s.data.PreviousBeats = make([]int64, backend.PREVIOUS_BEATS_COUNT)
			} else if c.WarningTimeout == TIMEOUT_CLEAR {
				s.data.WarningTimeout = TIMEOUT_CLEAR
			} else if c.WarningTimeout > 0 {
				s.data.WarningTimeout = c.WarningTimeout
			}
			if c.ErrorTimeout == TIMEOUT_AUTO &&
				s.data.ErrorTimeout == -1 {
				s.data.ErrorTimeout = TIMEOUT_AUTO
				s.data.PreviousBeats = make([]int64, backend.PREVIOUS_BEATS_COUNT)
			} else if c.ErrorTimeout == TIMEOUT_CLEAR {
				s.data.ErrorTimeout = TIMEOUT_CLEAR
			} else if c.ErrorTimeout > 0 {
				s.data.ErrorTimeout = c.ErrorTimeout
			}
			s.update(ts)
			s.save(&ref, ts)
			svcs.updateViews(ts, s.name())
		}
	}
}

func NewServices(beiface backend.Backend, alerters []alert.Alerter) *Services {
	svcs := new(Services)
	svcs.be = beiface
	svcs.alerters = alerters
	svcs.beatCmdChan = make(chan string, MAX_UNPROCESSED_PACKETS)
	svcs.deleteServiceCmdChan = make(chan string, 5)
	svcs.upsertServiceCmdChan = make(chan *upsertServiceCmd, 5)
	svcs.deleteViewCmdChan = make(chan string, 5)
	svcs.upsertViewCmdChan = make(chan *upsertViewCmd, 5)
	svcs.getServicesChan = make(chan *getServicesCmd, 5)
	svcs.getServiceChan = make(chan *getServiceCmd, 5)
	svcs.getViewsChan = make(chan *getViewsCmd, 5)
	svcs.getViewChan = make(chan *getViewCmd, 5)
	svcs.services = make(map[string]*Service)
	svcs.views = make(map[string]*View)

	for _, s := range svcs.be.LoadServices() {
		var svc = &Service{svcs: svcs, data: *s}
		if svc.data.PreviousBeats == nil || len(svc.data.PreviousBeats) != backend.PREVIOUS_BEATS_COUNT {
			svc.data.PreviousBeats = make([]int64, backend.PREVIOUS_BEATS_COUNT)
		}
		svcs.services[s.Name] = svc
	}

	for _, v := range svcs.be.LoadViews() {
		var ree, _ = regexp.Compile(v.Regexp)
		svcs.views[v.Name] = &View{svcs: svcs, data: *v, ree: ree}
	}

	return svcs
}
<|endoftext|>


<commit_before><commit_msg>gapic: gen protobuf v2 import for iterator usage (#664)<commit_after><|endoftext|>


<commit_before>/*
Copyright 2018 The Knative Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package autoscaler

import (
	"context"
	"errors"
	"math"
	"sync"
	"time"

	"go.uber.org/zap"

	"knative.dev/pkg/logging"
	"knative.dev/serving/pkg/apis/autoscaling"
	"knative.dev/serving/pkg/resources"

	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/types"
	corev1listers "k8s.io/client-go/listers/core/v1"
)

// Autoscaler stores current state of an instance of an autoscaler.
type Autoscaler struct {
	namespace    string
	revision     string
	metricClient MetricClient
	lister       corev1listers.EndpointsLister
	reporter     StatsReporter

	// State in panic mode. Carries over multiple Scale calls. Guarded
	// by the stateMux.
	stateMux     sync.Mutex
	panicTime    time.Time
	maxPanicPods int32

	// specMux guards the current DeciderSpec and the PodCounter.
	specMux     sync.RWMutex
	deciderSpec *DeciderSpec
	podCounter  resources.EndpointsCounter
}

// New creates a new instance of autoscaler
func New(
	namespace string,
	revision string,
	metricClient MetricClient,
	lister corev1listers.EndpointsLister,
	deciderSpec *DeciderSpec,
	reporter StatsReporter) (*Autoscaler, error) {
	if lister == nil {
		return nil, errors.New("'lister' must not be nil")
	}
	if reporter == nil {
		return nil, errors.New("stats reporter must not be nil")
	}

	// We always start in the panic mode, if the deployment is scaled up over 1 pod.
	// If the scale is 0 or 1, normal Autoscaler behavior is fine.
	// When Autoscaler restarts we lose metric history, which causes us to
	// momentarily scale down, and that is not a desired behaviour.
	// Thus, we're keeping at least the current scale until we
	// accumulate enough data to make conscious decisions.
	podCounter := resources.NewScopedEndpointsCounter(lister,
		namespace, deciderSpec.ServiceName)
	curC, err := podCounter.ReadyCount()
	if err != nil {
		// This always happens on new revision creation, since decider
		// is reconciled before SKS has even chance of creating the service/endpoints.
		curC = 0
	}
	var pt time.Time
	if curC > 1 {
		pt = time.Now()
		// A new instance of autoscaler is created in panic mode.
		reporter.ReportPanic(1)
	} else {
		reporter.ReportPanic(0)
	}

	return &Autoscaler{
		namespace:    namespace,
		revision:     revision,
		metricClient: metricClient,
		lister:       lister,
		reporter:     reporter,

		deciderSpec: deciderSpec,
		podCounter:  podCounter,

		panicTime:    pt,
		maxPanicPods: int32(curC),
	}, nil
}

// Update reconfigures the UniScaler according to the DeciderSpec.
func (a *Autoscaler) Update(deciderSpec *DeciderSpec) error {
	a.specMux.Lock()
	defer a.specMux.Unlock()

	// Update the podCounter if service name changes.
	if deciderSpec.ServiceName != a.deciderSpec.ServiceName {
		a.podCounter = resources.NewScopedEndpointsCounter(a.lister, a.namespace,
			deciderSpec.ServiceName)
	}
	a.deciderSpec = deciderSpec
	return nil
}

// Scale calculates the desired scale based on current statistics given the current time.
// desiredPodCount is the calculated pod count the autoscaler would like to set.
// validScale signifies whether the desiredPodCount should be applied or not.
func (a *Autoscaler) Scale(ctx context.Context, now time.Time) (desiredPodCount int32, excessBC int32, validScale bool) {
	logger := logging.FromContext(ctx)

	spec, podCounter := a.currentSpecAndPC()
	originalReadyPodsCount, err := podCounter.ReadyCount()
	// If the error is NotFound, then presume 0.
	if err != nil && !apierrors.IsNotFound(err) {
		logger.Errorw("Failed to get Endpoints via K8S Lister", zap.Error(err))
		return 0, 0, false
	}
	// Use 1 if there are zero current pods.
	readyPodsCount := math.Max(1, float64(originalReadyPodsCount))

	metricKey := types.NamespacedName{Namespace: a.namespace, Name: a.revision}

	metricName := spec.ScalingMetric
	var observedStableValue, observedPanicValue float64
	switch spec.ScalingMetric {
	case autoscaling.RPS:
		observedStableValue, observedPanicValue, err = a.metricClient.StableAndPanicRPS(metricKey, now)
		a.reporter.ReportStableRPS(observedStableValue)
		a.reporter.ReportPanicRPS(observedPanicValue)
		a.reporter.ReportTargetRPS(spec.TargetValue)
	default:
		metricName = autoscaling.Concurrency // concurrency is used by default
		observedStableValue, observedPanicValue, err = a.metricClient.StableAndPanicConcurrency(metricKey, now)
		a.reporter.ReportStableRequestConcurrency(observedStableValue)
		a.reporter.ReportPanicRequestConcurrency(observedPanicValue)
		a.reporter.ReportTargetRequestConcurrency(spec.TargetValue)
	}

	// Put the scaling metric to logs.
	logger = logger.With(zap.String("metric", metricName))

	if err != nil {
		if err == ErrNoData {
			logger.Debug("No data to scale on yet")
		} else {
			logger.Errorw("Failed to obtain metrics", zap.Error(err))
		}
		return 0, 0, false
	}

	// Make sure we don't get stuck with the same number of pods, if the scale up rate
	// is too conservative and MaxScaleUp*RPC==RPC, so this permits us to grow at least by a single
	// pod if we need to scale up.
	// E.g. MSUR=1.1, OCC=3, RPC=2, TV=1 => OCC/TV=3, MSU=2.2 => DSPC=2, while we definitely, need
	// 3 pods. See the unit test for this scenario in action.
	maxScaleUp := math.Ceil(spec.MaxScaleUpRate * readyPodsCount)
	// Same logic, opposite math applies here.
	maxScaleDown := math.Floor(readyPodsCount / spec.MaxScaleDownRate)

	dspc := math.Ceil(observedStableValue / spec.TargetValue)
	dppc := math.Ceil(observedPanicValue / spec.TargetValue)
	logger.Debugf("DesiredStablePodCount = %0.3f, DesiredPanicPodCount = %0.3f, MaxScaleUp = %0.3f, MaxScaleDown = %0.3f",
		dspc, dppc, maxScaleUp, maxScaleDown)

	// We want to keep desired pod count in the  [maxScaleDown, maxScaleUp] range.
	desiredStablePodCount := int32(math.Min(math.Max(dspc, maxScaleDown), maxScaleUp))
	desiredPanicPodCount := int32(math.Min(math.Max(dppc, maxScaleDown), maxScaleUp))

	logger.With(zap.String("mode", "stable")).Debugf("Observed average scaling metric value: %0.3f, targeting %0.3f.",
		observedStableValue, spec.TargetValue)
	logger.With(zap.String("mode", "panic")).Debugf("Observed average scaling metric value: %0.3f, targeting %0.3f.",
		observedPanicValue, spec.TargetValue)

	isOverPanicThreshold := observedPanicValue/readyPodsCount >= spec.PanicThreshold

	a.stateMux.Lock()
	defer a.stateMux.Unlock()
	if a.panicTime.IsZero() && isOverPanicThreshold {
		// Begin panicking when we cross the threshold in the panic window.
		logger.Info("PANICKING")
		a.panicTime = now
		a.reporter.ReportPanic(1)
	} else if !a.panicTime.IsZero() && !isOverPanicThreshold && a.panicTime.Add(spec.StableWindow).Before(now) {
		// Stop panicking after the surge has made its way into the stable metric.
		logger.Info("Un-panicking.")
		a.panicTime = time.Time{}
		a.maxPanicPods = 0
		a.reporter.ReportPanic(0)
	}

	if !a.panicTime.IsZero() {
		logger.Debug("Operating in panic mode.")
		// We do not scale down while in panic mode. Only increases will be applied.
		if desiredPanicPodCount > a.maxPanicPods {
			logger.Infof("Increasing pods from %d to %d.", originalReadyPodsCount, desiredPanicPodCount)
			a.panicTime = now
			a.maxPanicPods = desiredPanicPodCount
		} else if desiredPanicPodCount < a.maxPanicPods {
			logger.Debugf("Skipping decrease from %d to %d.", a.maxPanicPods, desiredPanicPodCount)
		}
		desiredPodCount = a.maxPanicPods
	} else {
		logger.Debug("Operating in stable mode.")
		desiredPodCount = desiredStablePodCount
	}

	// Compute the excess burst capacity based on stable value for now, since we don't want to
	// be making knee-jerk decisions about Activator in the request path. Negative EBC means
	// that the deployment does not have enough capacity to serve the desired burst off hand.
	// EBC = TotCapacity - Cur#ReqInFlight - TargetBurstCapacity
	excessBC = int32(-1)
	switch {
	case a.deciderSpec.TargetBurstCapacity == 0:
		excessBC = 0
	case a.deciderSpec.TargetBurstCapacity >= 0:
		excessBC = int32(math.Floor(float64(originalReadyPodsCount)*a.deciderSpec.TotalValue - observedStableValue -
			a.deciderSpec.TargetBurstCapacity))
		logger.Infof("PodCount=%v Total1PodCapacity=%v ObservedStableValue=%v TargetBC=%v ExcessBC=%v",
			originalReadyPodsCount,
			a.deciderSpec.TotalValue,
			observedStableValue, a.deciderSpec.TargetBurstCapacity, excessBC)
	}

	a.reporter.ReportExcessBurstCapacity(float64(excessBC))
	a.reporter.ReportDesiredPodCount(int64(desiredPodCount))

	return desiredPodCount, excessBC, true
}

func (a *Autoscaler) currentSpecAndPC() (*DeciderSpec, resources.EndpointsCounter) {
	a.specMux.RLock()
	defer a.specMux.RUnlock()
	return a.deciderSpec, a.podCounter
}
<commit_msg>Add the actual # of endpoints observed. (#6643)<commit_after>/*
Copyright 2018 The Knative Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package autoscaler

import (
	"context"
	"errors"
	"math"
	"sync"
	"time"

	"go.uber.org/zap"

	"knative.dev/pkg/logging"
	"knative.dev/serving/pkg/apis/autoscaling"
	"knative.dev/serving/pkg/resources"

	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/types"
	corev1listers "k8s.io/client-go/listers/core/v1"
)

// Autoscaler stores current state of an instance of an autoscaler.
type Autoscaler struct {
	namespace    string
	revision     string
	metricClient MetricClient
	lister       corev1listers.EndpointsLister
	reporter     StatsReporter

	// State in panic mode. Carries over multiple Scale calls. Guarded
	// by the stateMux.
	stateMux     sync.Mutex
	panicTime    time.Time
	maxPanicPods int32

	// specMux guards the current DeciderSpec and the PodCounter.
	specMux     sync.RWMutex
	deciderSpec *DeciderSpec
	podCounter  resources.EndpointsCounter
}

// New creates a new instance of autoscaler
func New(
	namespace string,
	revision string,
	metricClient MetricClient,
	lister corev1listers.EndpointsLister,
	deciderSpec *DeciderSpec,
	reporter StatsReporter) (*Autoscaler, error) {
	if lister == nil {
		return nil, errors.New("'lister' must not be nil")
	}
	if reporter == nil {
		return nil, errors.New("stats reporter must not be nil")
	}

	// We always start in the panic mode, if the deployment is scaled up over 1 pod.
	// If the scale is 0 or 1, normal Autoscaler behavior is fine.
	// When Autoscaler restarts we lose metric history, which causes us to
	// momentarily scale down, and that is not a desired behaviour.
	// Thus, we're keeping at least the current scale until we
	// accumulate enough data to make conscious decisions.
	podCounter := resources.NewScopedEndpointsCounter(lister,
		namespace, deciderSpec.ServiceName)
	curC, err := podCounter.ReadyCount()
	if err != nil {
		// This always happens on new revision creation, since decider
		// is reconciled before SKS has even chance of creating the service/endpoints.
		curC = 0
	}
	var pt time.Time
	if curC > 1 {
		pt = time.Now()
		// A new instance of autoscaler is created in panic mode.
		reporter.ReportPanic(1)
	} else {
		reporter.ReportPanic(0)
	}

	return &Autoscaler{
		namespace:    namespace,
		revision:     revision,
		metricClient: metricClient,
		lister:       lister,
		reporter:     reporter,

		deciderSpec: deciderSpec,
		podCounter:  podCounter,

		panicTime:    pt,
		maxPanicPods: int32(curC),
	}, nil
}

// Update reconfigures the UniScaler according to the DeciderSpec.
func (a *Autoscaler) Update(deciderSpec *DeciderSpec) error {
	a.specMux.Lock()
	defer a.specMux.Unlock()

	// Update the podCounter if service name changes.
	if deciderSpec.ServiceName != a.deciderSpec.ServiceName {
		a.podCounter = resources.NewScopedEndpointsCounter(a.lister, a.namespace,
			deciderSpec.ServiceName)
	}
	a.deciderSpec = deciderSpec
	return nil
}

// Scale calculates the desired scale based on current statistics given the current time.
// desiredPodCount is the calculated pod count the autoscaler would like to set.
// validScale signifies whether the desiredPodCount should be applied or not.
func (a *Autoscaler) Scale(ctx context.Context, now time.Time) (desiredPodCount int32, excessBC int32, validScale bool) {
	logger := logging.FromContext(ctx)

	spec, podCounter := a.currentSpecAndPC()
	originalReadyPodsCount, err := podCounter.ReadyCount()
	// If the error is NotFound, then presume 0.
	if err != nil && !apierrors.IsNotFound(err) {
		logger.Errorw("Failed to get Endpoints via K8S Lister", zap.Error(err))
		return 0, 0, false
	}
	// Use 1 if there are zero current pods.
	readyPodsCount := math.Max(1, float64(originalReadyPodsCount))

	metricKey := types.NamespacedName{Namespace: a.namespace, Name: a.revision}

	metricName := spec.ScalingMetric
	var observedStableValue, observedPanicValue float64
	switch spec.ScalingMetric {
	case autoscaling.RPS:
		observedStableValue, observedPanicValue, err = a.metricClient.StableAndPanicRPS(metricKey, now)
		a.reporter.ReportStableRPS(observedStableValue)
		a.reporter.ReportPanicRPS(observedPanicValue)
		a.reporter.ReportTargetRPS(spec.TargetValue)
	default:
		metricName = autoscaling.Concurrency // concurrency is used by default
		observedStableValue, observedPanicValue, err = a.metricClient.StableAndPanicConcurrency(metricKey, now)
		a.reporter.ReportStableRequestConcurrency(observedStableValue)
		a.reporter.ReportPanicRequestConcurrency(observedPanicValue)
		a.reporter.ReportTargetRequestConcurrency(spec.TargetValue)
	}

	// Put the scaling metric to logs.
	logger = logger.With(zap.String("metric", metricName))

	if err != nil {
		if err == ErrNoData {
			logger.Debug("No data to scale on yet")
		} else {
			logger.Errorw("Failed to obtain metrics", zap.Error(err))
		}
		return 0, 0, false
	}

	// Make sure we don't get stuck with the same number of pods, if the scale up rate
	// is too conservative and MaxScaleUp*RPC==RPC, so this permits us to grow at least by a single
	// pod if we need to scale up.
	// E.g. MSUR=1.1, OCC=3, RPC=2, TV=1 => OCC/TV=3, MSU=2.2 => DSPC=2, while we definitely, need
	// 3 pods. See the unit test for this scenario in action.
	maxScaleUp := math.Ceil(spec.MaxScaleUpRate * readyPodsCount)
	// Same logic, opposite math applies here.
	maxScaleDown := math.Floor(readyPodsCount / spec.MaxScaleDownRate)

	dspc := math.Ceil(observedStableValue / spec.TargetValue)
	dppc := math.Ceil(observedPanicValue / spec.TargetValue)
	logger.Debugf("DesiredStablePodCount = %0.3f, DesiredPanicPodCount = %0.3f, ReadyEndpointCount = %d, MaxScaleUp = %0.3f, MaxScaleDown = %0.3f",
		dspc, dppc, originalReadyPodsCount, maxScaleUp, maxScaleDown)

	// We want to keep desired pod count in the  [maxScaleDown, maxScaleUp] range.
	desiredStablePodCount := int32(math.Min(math.Max(dspc, maxScaleDown), maxScaleUp))
	desiredPanicPodCount := int32(math.Min(math.Max(dppc, maxScaleDown), maxScaleUp))

	logger.With(zap.String("mode", "stable")).Debugf("Observed average scaling metric value: %0.3f, targeting %0.3f.",
		observedStableValue, spec.TargetValue)
	logger.With(zap.String("mode", "panic")).Debugf("Observed average scaling metric value: %0.3f, targeting %0.3f.",
		observedPanicValue, spec.TargetValue)

	isOverPanicThreshold := observedPanicValue/readyPodsCount >= spec.PanicThreshold

	a.stateMux.Lock()
	defer a.stateMux.Unlock()
	if a.panicTime.IsZero() && isOverPanicThreshold {
		// Begin panicking when we cross the threshold in the panic window.
		logger.Info("PANICKING")
		a.panicTime = now
		a.reporter.ReportPanic(1)
	} else if !a.panicTime.IsZero() && !isOverPanicThreshold && a.panicTime.Add(spec.StableWindow).Before(now) {
		// Stop panicking after the surge has made its way into the stable metric.
		logger.Info("Un-panicking.")
		a.panicTime = time.Time{}
		a.maxPanicPods = 0
		a.reporter.ReportPanic(0)
	}

	if !a.panicTime.IsZero() {
		logger.Debug("Operating in panic mode.")
		// We do not scale down while in panic mode. Only increases will be applied.
		if desiredPanicPodCount > a.maxPanicPods {
			logger.Infof("Increasing pods from %d to %d.", originalReadyPodsCount, desiredPanicPodCount)
			a.panicTime = now
			a.maxPanicPods = desiredPanicPodCount
		} else if desiredPanicPodCount < a.maxPanicPods {
			logger.Debugf("Skipping decrease from %d to %d.", a.maxPanicPods, desiredPanicPodCount)
		}
		desiredPodCount = a.maxPanicPods
	} else {
		logger.Debug("Operating in stable mode.")
		desiredPodCount = desiredStablePodCount
	}

	// Compute the excess burst capacity based on stable value for now, since we don't want to
	// be making knee-jerk decisions about Activator in the request path. Negative EBC means
	// that the deployment does not have enough capacity to serve the desired burst off hand.
	// EBC = TotCapacity - Cur#ReqInFlight - TargetBurstCapacity
	excessBC = int32(-1)
	switch {
	case a.deciderSpec.TargetBurstCapacity == 0:
		excessBC = 0
	case a.deciderSpec.TargetBurstCapacity >= 0:
		excessBC = int32(math.Floor(float64(originalReadyPodsCount)*a.deciderSpec.TotalValue - observedStableValue -
			a.deciderSpec.TargetBurstCapacity))
		logger.Infof("PodCount=%v Total1PodCapacity=%v ObservedStableValue=%v TargetBC=%v ExcessBC=%v",
			originalReadyPodsCount,
			a.deciderSpec.TotalValue,
			observedStableValue, a.deciderSpec.TargetBurstCapacity, excessBC)
	}

	a.reporter.ReportExcessBurstCapacity(float64(excessBC))
	a.reporter.ReportDesiredPodCount(int64(desiredPodCount))

	return desiredPodCount, excessBC, true
}

func (a *Autoscaler) currentSpecAndPC() (*DeciderSpec, resources.EndpointsCounter) {
	a.specMux.RLock()
	defer a.specMux.RUnlock()
	return a.deciderSpec, a.podCounter
}
<|endoftext|>


<commit_before>package service

import (
	"code.google.com/p/go-uuid/uuid"
	"fmt"
	"github.com/ninjasphere/app-presets/model"

	"github.com/ninjasphere/go-ninja/config"
	"github.com/ninjasphere/go-ninja/logger"
	nmodel "github.com/ninjasphere/go-ninja/model"
	"github.com/ninjasphere/go-ninja/rpc"
)

type Connection interface {
	ExportService(service interface{}, topic string, ann *nmodel.ServiceAnnouncement) (*rpc.ExportedService, error)
}

type PresetsService struct {
	Model       *model.Presets
	Save        func(*model.Presets)
	Conn        Connection
	Log         *logger.Logger
	initialized bool
}

func (ps *PresetsService) Init() error {
	if ps.Log == nil {
		return fmt.Errorf("illegal state: no logger")
	}
	if ps.Model == nil {
		return fmt.Errorf("illegal state: Model is nil")
	}
	if ps.Save == nil {
		return fmt.Errorf("illegal state: Save is nil")
	}
	if ps.Conn == nil {
		return fmt.Errorf("illegal state: Conn is nil")
	}
	ps.initialized = true
	return nil
}

func (ps *PresetsService) Destroy() error {
	ps.initialized = false
	return nil
}

func (ps *PresetsService) checkInit() {
	if ps.Log == nil {
		ps.Log = logger.GetLogger("com.ninja.app-presets")
	}
	if !ps.initialized {
		ps.Log.Fatalf("illegal state: the service is not initialized")
	}
}

// see: http://schema.ninjablocks.com/service/presets#listPresetable
func (ps *PresetsService) ListPresetable(scope string) ([]*model.ThingState, error) {
	ps.checkInit()
	return make([]*model.ThingState, 0, 0), fmt.Errorf("unimplemented function: ListPresetable")
}

// see: http://schema.ninjablocks.com/service/presets#fetchScenes
func (ps *PresetsService) FetchScenes(scope string) ([]*model.Scene, error) {
	ps.checkInit()
	collect := make([]*model.Scene, 0, 0)
	for _, m := range ps.Model.Scenes {
		if m.Scope == scope {
			collect = append(collect, m)
		}
	}
	return collect, nil
}

// see: http://schema.ninjablocks.com/service/presets#fetchScene
func (ps *PresetsService) FetchScene(id string) (*model.Scene, error) {
	ps.checkInit()
	for _, m := range ps.Model.Scenes {
		if m.ID == id {
			return m, nil
		}
	}
	return nil, fmt.Errorf("No such scene: %s", id)
}

// see: http://schema.ninjablocks.com/service/presets#storeScene
func (ps *PresetsService) StoreScene(model *model.Scene) (*model.Scene, error) {
	ps.checkInit()
	var found int

	if model.Scope == "" {
		return nil, fmt.Errorf("illegal argument: model.Scope is empty")
	}

	for i, m := range ps.Model.Scenes {
		if model.ID == "" {
			if m.Scope == model.Scope && m.Slot == model.Slot {
				found = i
			}
		} else {
			if m.ID == model.ID {
				found = i
			}
		}
	}

	if model.ID == "" {
		model.ID = uuid.NewUUID().String()
	}

	if found >= len(ps.Model.Scenes) {
		ps.Model.Scenes = append(ps.Model.Scenes, model)
	} else {
		ps.Model.Scenes[found] = model
	}
	ps.Save(ps.Model)
	return model, nil
}

// see: http://schema.ninjablocks.com/service/presets#applyScene
func (ps *PresetsService) ApplyScene(id string) error {
	ps.checkInit()
	return fmt.Errorf("unimplemented function: ApplyScene")
}
<commit_msg>Add the export of the presets service.<commit_after>package service

import (
	"code.google.com/p/go-uuid/uuid"
	"fmt"
	"github.com/ninjasphere/app-presets/model"

	"github.com/ninjasphere/go-ninja/config"
	"github.com/ninjasphere/go-ninja/logger"
	nmodel "github.com/ninjasphere/go-ninja/model"
	"github.com/ninjasphere/go-ninja/rpc"
)

type Connection interface {
	ExportService(service interface{}, topic string, ann *nmodel.ServiceAnnouncement) (*rpc.ExportedService, error)
}

type PresetsService struct {
	Model       *model.Presets
	Save        func(*model.Presets)
	Conn        Connection
	Log         *logger.Logger
	initialized bool
}

func (ps *PresetsService) Init() error {
	if ps.Log == nil {
		return fmt.Errorf("illegal state: no logger")
	}
	if ps.Model == nil {
		return fmt.Errorf("illegal state: Model is nil")
	}
	if ps.Save == nil {
		return fmt.Errorf("illegal state: Save is nil")
	}
	if ps.Conn == nil {
		return fmt.Errorf("illegal state: Conn is nil")
	}

	var err error
	siteID := config.MustString("siteId")
	topic := fmt.Sprintf("$site/%s/service/%s", siteID, "presets")
	announcement := &nmodel.ServiceAnnouncement{
		Schema: "http://schema.ninjablocks.com/service/presets",
	}
	if _, err = ps.Conn.ExportService(ps, topic, announcement); err != nil {
		return err
	}

	ps.initialized = true
	return nil
}

func (ps *PresetsService) Destroy() error {
	ps.initialized = false
	return nil
}

func (ps *PresetsService) checkInit() {
	if ps.Log == nil {
		ps.Log = logger.GetLogger("com.ninja.app-presets")
	}
	if !ps.initialized {
		ps.Log.Fatalf("illegal state: the service is not initialized")
	}
}

// see: http://schema.ninjablocks.com/service/presets#listPresetable
func (ps *PresetsService) ListPresetable(scope string) ([]*model.ThingState, error) {
	ps.checkInit()
	return make([]*model.ThingState, 0, 0), fmt.Errorf("unimplemented function: ListPresetable")
}

// see: http://schema.ninjablocks.com/service/presets#fetchScenes
func (ps *PresetsService) FetchScenes(scope string) ([]*model.Scene, error) {
	ps.checkInit()
	collect := make([]*model.Scene, 0, 0)
	for _, m := range ps.Model.Scenes {
		if m.Scope == scope {
			collect = append(collect, m)
		}
	}
	return collect, nil
}

// see: http://schema.ninjablocks.com/service/presets#fetchScene
func (ps *PresetsService) FetchScene(id string) (*model.Scene, error) {
	ps.checkInit()
	for _, m := range ps.Model.Scenes {
		if m.ID == id {
			return m, nil
		}
	}
	return nil, fmt.Errorf("No such scene: %s", id)
}

// see: http://schema.ninjablocks.com/service/presets#storeScene
func (ps *PresetsService) StoreScene(model *model.Scene) (*model.Scene, error) {
	ps.checkInit()
	var found int

	if model.Scope == "" {
		return nil, fmt.Errorf("illegal argument: model.Scope is empty")
	}

	for i, m := range ps.Model.Scenes {
		if model.ID == "" {
			if m.Scope == model.Scope && m.Slot == model.Slot {
				found = i
			}
		} else {
			if m.ID == model.ID {
				found = i
			}
		}
	}

	if model.ID == "" {
		model.ID = uuid.NewUUID().String()
	}

	if found >= len(ps.Model.Scenes) {
		ps.Model.Scenes = append(ps.Model.Scenes, model)
	} else {
		ps.Model.Scenes[found] = model
	}
	ps.Save(ps.Model)
	return model, nil
}

// see: http://schema.ninjablocks.com/service/presets#applyScene
func (ps *PresetsService) ApplyScene(id string) error {
	ps.checkInit()
	return fmt.Errorf("unimplemented function: ApplyScene")
}
<|endoftext|>


<commit_before><commit_msg>x/ref/lib/testutil tidy up: step 1 MultiPart: 2/2<commit_after><|endoftext|>