repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
events/sinks/influxdb/influxdb.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/events/sinks/influxdb/influxdb.go#L61-L68
go
train
// Generate point value for event
func getEventValue(event *kube_api.Event) (string, error)
// Generate point value for event func getEventValue(event *kube_api.Event) (string, error)
{ // TODO: check whether indenting is required. bytes, err := json.MarshalIndent(event, "", " ") if err != nil { return "", err } return string(bytes), nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
events/sinks/influxdb/influxdb.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/events/sinks/influxdb/influxdb.go#L230-L239
go
train
// Returns a thread-safe implementation of core.EventSink for InfluxDB.
func newSink(c influxdb_common.InfluxdbConfig) core.EventSink
// Returns a thread-safe implementation of core.EventSink for InfluxDB. func newSink(c influxdb_common.InfluxdbConfig) core.EventSink
{ client, err := influxdb_common.NewClient(c) if err != nil { glog.Errorf("issues while creating an InfluxDB sink: %v, will retry on use", err) } return &influxdbSink{ client: client, // can be nil c: c, } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
common/elasticsearch/aws.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/common/elasticsearch/aws.go#L29-L31
go
train
// RoundTrip implementation
func (a AWSSigningTransport) RoundTrip(req *http.Request) (*http.Response, error)
// RoundTrip implementation func (a AWSSigningTransport) RoundTrip(req *http.Request) (*http.Response, error)
{ return a.HTTPClient.Do(awsauth.Sign4(req, a.Credentials)) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/opentsdb/driver.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/opentsdb/driver.go#L106-L113
go
train
// Converts the given OpenTSDB metric or tag name/value to a form that is // accepted by OpenTSDB. As the OpenTSDB documentation states: // 'Metric names, tag names and tag values have to be made of alpha numeric // characters, dash "-", underscore "_", period ".", and forward slash "/".'
func toValidOpenTsdbName(name string) (validName string)
// Converts the given OpenTSDB metric or tag name/value to a form that is // accepted by OpenTSDB. As the OpenTSDB documentation states: // 'Metric names, tag names and tag values have to be made of alpha numeric // characters, dash "-", underscore "_", period ".", and forward slash "/".' func toValidOpenTsdbName(name string) (validName string)
{ // This takes care of some cases where dash "-" characters were // encoded as '\\x2d' in received Timeseries Points validName = fmt.Sprintf("%s", name) // replace all illegal characters with '_' return disallowedCharsRegexp.ReplaceAllLiteralString(validName, "_") }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/opentsdb/driver.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/opentsdb/driver.go#L117-L146
go
train
// timeSeriesToPoint transfers the contents holding in the given pointer of sink_api.Timeseries // into the instance of opentsdbclient.DataPoint
func (tsdbSink *openTSDBSink) metricToPoint(name string, value core.MetricValue, timestamp time.Time, labels map[string]string) opentsdbclient.DataPoint
// timeSeriesToPoint transfers the contents holding in the given pointer of sink_api.Timeseries // into the instance of opentsdbclient.DataPoint func (tsdbSink *openTSDBSink) metricToPoint(name string, value core.MetricValue, timestamp time.Time, labels map[string]string) opentsdbclient.DataPoint
{ seriesName := strings.Replace(toValidOpenTsdbName(name), "/", "_", -1) if value.MetricType.String() != "" { seriesName = fmt.Sprintf("%s_%s", seriesName, value.MetricType.String()) } datapoint := opentsdbclient.DataPoint{ Metric: seriesName, Tags: make(map[string]string, len(labels)), Timestamp: timestamp.Unix(), } if value.ValueType == core.ValueInt64 { datapoint.Value = value.IntValue } else { datapoint.Value = value.FloatValue } for key, value := range labels { key = toValidOpenTsdbName(key) value = toValidOpenTsdbName(value) if value != "" { datapoint.Tags[key] = value } } tsdbSink.putDefaultTags(&datapoint) return datapoint }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/opentsdb/driver.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/opentsdb/driver.go#L151-L153
go
train
// putDefaultTags just fills in the default key-value pair for the tags. // OpenTSDB requires at least one non-empty tag otherwise the OpenTSDB will return error and the operation of putting // datapoint will be failed.
func (tsdbSink *openTSDBSink) putDefaultTags(datapoint *opentsdbclient.DataPoint)
// putDefaultTags just fills in the default key-value pair for the tags. // OpenTSDB requires at least one non-empty tag otherwise the OpenTSDB will return error and the operation of putting // datapoint will be failed. func (tsdbSink *openTSDBSink) putDefaultTags(datapoint *opentsdbclient.DataPoint)
{ datapoint.Tags[clusterNameTagName] = tsdbSink.clusterName }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/api.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/api.go#L42-L72
go
train
// Create a new Api to serve from the specified cache.
func NewApi(runningInKubernetes bool, metricSink *metricsink.MetricSink, historicalSource core.HistoricalSource, disableMetricExport bool) *Api
// Create a new Api to serve from the specified cache. func NewApi(runningInKubernetes bool, metricSink *metricsink.MetricSink, historicalSource core.HistoricalSource, disableMetricExport bool) *Api
{ gkeMetrics := make(map[string]core.MetricDescriptor) gkeLabels := make(map[string]core.LabelDescriptor) for _, val := range core.StandardMetrics { gkeMetrics[val.Name] = val.MetricDescriptor } for _, val := range core.LabeledMetrics { gkeMetrics[val.Name] = val.MetricDescriptor } gkeMetrics[core.MetricCpuLimit.Name] = core.MetricCpuLimit.MetricDescriptor gkeMetrics[core.MetricMemoryLimit.Name] = core.MetricMemoryLimit.MetricDescriptor for _, val := range core.CommonLabels() { gkeLabels[val.Key] = val } for _, val := range core.ContainerLabels() { gkeLabels[val.Key] = val } for _, val := range core.PodLabels() { gkeLabels[val.Key] = val } return &Api{ runningInKubernetes: runningInKubernetes, metricSink: metricSink, historicalSource: historicalSource, gkeMetrics: gkeMetrics, gkeLabels: gkeLabels, disabled: disableMetricExport, } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/api.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/api.go#L75-L104
go
train
// Register the mainApi on the specified endpoint.
func (a *Api) Register(container *restful.Container)
// Register the mainApi on the specified endpoint. func (a *Api) Register(container *restful.Container)
{ ws := new(restful.WebService) ws.Path("/api/v1/metric-export"). Doc("Exports the latest point for all Heapster metrics"). Produces(restful.MIME_JSON) ws.Route(ws.GET(""). To(a.exportMetrics). Doc("export the latest data point for all metrics"). Operation("exportMetrics"). Writes([]*types.Timeseries{})) container.Add(ws) ws = new(restful.WebService) ws.Path("/api/v1/metric-export-schema"). Doc("Schema for metrics exported by heapster"). Produces(restful.MIME_JSON) ws.Route(ws.GET(""). To(a.exportMetricsSchema). Doc("export the schema for all metrics"). Operation("exportmetricsSchema"). Writes(types.TimeseriesSchema{})) container.Add(ws) if a.metricSink != nil { a.RegisterModel(container) } if a.historicalSource != nil { a.RegisterHistorical(container) } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/hawkular/driver.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/hawkular/driver.go#L54-L70
go
train
// START: ExternalSink interface implementations
func (h *hawkularSink) Register(mds []core.MetricDescriptor) error
// START: ExternalSink interface implementations func (h *hawkularSink) Register(mds []core.MetricDescriptor) error
{ // Create model definitions based on the MetricDescriptors for _, md := range mds { hmd := h.descriptorToDefinition(&md) h.models[md.Name] = &hmd } if !h.disablePreCaching { // Fetch currently known metrics from Hawkular-Metrics and cache them err := h.cacheDefinitions() if err != nil { return err } } return nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/hawkular/driver.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/hawkular/driver.go#L178-L193
go
train
// NewHawkularSink Creates and returns a new hawkularSink instance
func NewHawkularSink(u *url.URL) (core.DataSink, error)
// NewHawkularSink Creates and returns a new hawkularSink instance func NewHawkularSink(u *url.URL) (core.DataSink, error)
{ sink := &hawkularSink{ uri: u, batchSize: 1000, } if err := sink.init(); err != nil { return nil, err } metrics := make([]core.MetricDescriptor, 0, len(core.AllMetrics)) for _, metric := range core.AllMetrics { metrics = append(metrics, metric.MetricDescriptor) } sink.Register(metrics) return sink, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
common/elasticsearch/elasticsearch.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/common/elasticsearch/elasticsearch.go#L54-L122
go
train
// SaveDataIntoES save metrics and events to ES by using ES client
func (esSvc *ElasticSearchService) SaveData(date time.Time, typeName string, sinkData []interface{}) error
// SaveDataIntoES save metrics and events to ES by using ES client func (esSvc *ElasticSearchService) SaveData(date time.Time, typeName string, sinkData []interface{}) error
{ if typeName == "" || len(sinkData) == 0 { return nil } indexName := esSvc.Index(date) // Use the IndexExists service to check if a specified index exists. exists, err := esSvc.EsClient.IndexExists(indexName) if err != nil { return err } if !exists { // Create a new index. createIndex, err := esSvc.EsClient.CreateIndex(indexName, mapping) if err != nil { return err } ack := false switch i := createIndex.(type) { case *elastic2.IndicesCreateResult: ack = i.Acknowledged case *elastic5.IndicesCreateResult: ack = i.Acknowledged } if !ack { return errors.New("Failed to acknoledge index creation") } } aliases, err := esSvc.EsClient.GetAliases(indexName) if err != nil { return err } aliasName := esSvc.IndexAlias(typeName) hasAlias := false switch a := aliases.(type) { case *elastic2.AliasesResult: hasAlias = a.Indices[indexName].HasAlias(aliasName) case *elastic5.AliasesResult: hasAlias = a.Indices[indexName].HasAlias(aliasName) } if !hasAlias { createAlias, err := esSvc.EsClient.AddAlias(indexName, esSvc.IndexAlias(typeName)) if err != nil { return err } ack := false switch i := createAlias.(type) { case *elastic2.AliasResult: ack = i.Acknowledged case *elastic5.AliasResult: ack = i.Acknowledged } if !ack { return errors.New("Failed to acknoledge index alias creation") } } for _, data := range sinkData { esSvc.EsClient.AddBulkReq(indexName, typeName, data) } return nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
common/elasticsearch/elasticsearch.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/common/elasticsearch/elasticsearch.go#L126-L252
go
train
// CreateElasticSearchConfig creates an ElasticSearch configuration struct // which contains an ElasticSearch client for later use
func CreateElasticSearchService(uri *url.URL) (*ElasticSearchService, error)
// CreateElasticSearchConfig creates an ElasticSearch configuration struct // which contains an ElasticSearch client for later use func CreateElasticSearchService(uri *url.URL) (*ElasticSearchService, error)
{ var esSvc ElasticSearchService opts, err := url.ParseQuery(uri.RawQuery) if err != nil { return nil, fmt.Errorf("Failed to parse url's query string: %s", err) } version := 5 if len(opts["ver"]) > 0 { version, err = strconv.Atoi(opts["ver"][0]) if err != nil { return nil, fmt.Errorf("Failed to parse URL's version value into an int: %v", err) } } esSvc.ClusterName = ESClusterName if len(opts["cluster_name"]) > 0 { esSvc.ClusterName = opts["cluster_name"][0] } // set the index for es,the default value is "heapster" esSvc.baseIndex = ESIndex if len(opts["index"]) > 0 { esSvc.baseIndex = opts["index"][0] } var startupFnsV5 []elastic5.ClientOptionFunc var startupFnsV2 []elastic2.ClientOptionFunc // Set the URL endpoints of the ES's nodes. Notice that when sniffing is // enabled, these URLs are used to initially sniff the cluster on startup. if len(opts["nodes"]) > 0 { startupFnsV2 = append(startupFnsV2, elastic2.SetURL(opts["nodes"]...)) startupFnsV5 = append(startupFnsV5, elastic5.SetURL(opts["nodes"]...)) } else if uri.Scheme != "" && uri.Host != "" { startupFnsV2 = append(startupFnsV2, elastic2.SetURL(uri.Scheme+"://"+uri.Host)) startupFnsV5 = append(startupFnsV5, elastic5.SetURL(uri.Scheme+"://"+uri.Host)) } else { return nil, errors.New("There is no node assigned for connecting ES cluster") } // If the ES cluster needs authentication, the username and secret // should be set in sink config.Else, set the Authenticate flag to false if len(opts["esUserName"]) > 0 && len(opts["esUserSecret"]) > 0 { startupFnsV2 = append(startupFnsV2, elastic2.SetBasicAuth(opts["esUserName"][0], opts["esUserSecret"][0])) startupFnsV5 = append(startupFnsV5, elastic5.SetBasicAuth(opts["esUserName"][0], opts["esUserSecret"][0])) } if len(opts["maxRetries"]) > 0 { maxRetries, err := strconv.Atoi(opts["maxRetries"][0]) if err != nil { return nil, errors.New("Failed to parse URL's maxRetries value into an int") } startupFnsV2 = append(startupFnsV2, elastic2.SetMaxRetries(maxRetries)) startupFnsV5 = append(startupFnsV5, elastic5.SetMaxRetries(maxRetries)) } if len(opts["healthCheck"]) > 0 { healthCheck, err := strconv.ParseBool(opts["healthCheck"][0]) if err != nil { return nil, errors.New("Failed to parse URL's healthCheck value into a bool") } startupFnsV2 = append(startupFnsV2, elastic2.SetHealthcheck(healthCheck)) startupFnsV5 = append(startupFnsV5, elastic5.SetHealthcheck(healthCheck)) } if len(opts["startupHealthcheckTimeout"]) > 0 { timeout, err := time.ParseDuration(opts["startupHealthcheckTimeout"][0] + "s") if err != nil { return nil, fmt.Errorf("Failed to parse URL's startupHealthcheckTimeout: %s", err.Error()) } startupFnsV2 = append(startupFnsV2, elastic2.SetHealthcheckTimeoutStartup(timeout)) startupFnsV5 = append(startupFnsV5, elastic5.SetHealthcheckTimeoutStartup(timeout)) } if os.Getenv("AWS_ACCESS_KEY_ID") != "" || os.Getenv("AWS_ACCESS_KEY") != "" || os.Getenv("AWS_SECRET_ACCESS_KEY") != "" || os.Getenv("AWS_SECRET_KEY") != "" { glog.Info("Configuring with AWS credentials..") awsClient, err := createAWSClient() if err != nil { return nil, err } startupFnsV2 = append(startupFnsV2, elastic2.SetHttpClient(awsClient), elastic2.SetSniff(false)) startupFnsV5 = append(startupFnsV5, elastic5.SetHttpClient(awsClient), elastic5.SetSniff(false)) } else { if len(opts["sniff"]) > 0 { sniff, err := strconv.ParseBool(opts["sniff"][0]) if err != nil { return nil, errors.New("Failed to parse URL's sniff value into a bool") } startupFnsV2 = append(startupFnsV2, elastic2.SetSniff(sniff)) startupFnsV5 = append(startupFnsV5, elastic5.SetSniff(sniff)) } } bulkWorkers := 5 if len(opts["bulkWorkers"]) > 0 { bulkWorkers, err = strconv.Atoi(opts["bulkWorkers"][0]) if err != nil { return nil, errors.New("Failed to parse URL's bulkWorkers value into an int") } } pipeline := "" if len(opts["pipeline"]) > 0 { pipeline = opts["pipeline"][0] } switch version { case 2: esSvc.EsClient, err = newEsClientV2(startupFnsV2, bulkWorkers) case 5: esSvc.EsClient, err = newEsClientV5(startupFnsV5, bulkWorkers, pipeline) default: return nil, UnsupportedVersion{} } if err != nil { return nil, fmt.Errorf("Failed to create ElasticSearch client: %v", err) } glog.V(2).Infof("ElasticSearch sink configure successfully") return &esSvc, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb.go#L294-L304
go
train
// Returns a thread-compatible implementation of influxdb interactions.
func newSink(c influxdb_common.InfluxdbConfig) core.DataSink
// Returns a thread-compatible implementation of influxdb interactions. func newSink(c influxdb_common.InfluxdbConfig) core.DataSink
{ client, err := influxdb_common.NewClient(c) if err != nil { glog.Errorf("issues while creating an InfluxDB sink: %v, will retry on use", err) } return &influxdbSink{ client: client, // can be nil c: c, conChan: make(chan struct{}, c.Concurrency), } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
integration/framework.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/integration/framework.go#L402-L413
go
train
// Parses and Returns a RBAC object contained in 'filePath'
func (self *realKubeFramework) ParseRBAC(filePath string) (*rbacv1.ClusterRoleBinding, error)
// Parses and Returns a RBAC object contained in 'filePath' func (self *realKubeFramework) ParseRBAC(filePath string) (*rbacv1.ClusterRoleBinding, error)
{ obj, err := self.loadRBACObject(filePath) if err != nil { return nil, err } rbac, ok := obj.(*rbacv1.ClusterRoleBinding) if !ok { return nil, fmt.Errorf("Failed to cast clusterrolebinding: %v", obj) } return rbac, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
integration/framework.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/integration/framework.go#L416-L419
go
train
// CreateRBAC creates the RBAC object
func (self *realKubeFramework) CreateRBAC(rbac *rbacv1.ClusterRoleBinding) error
// CreateRBAC creates the RBAC object func (self *realKubeFramework) CreateRBAC(rbac *rbacv1.ClusterRoleBinding) error
{ _, err := self.kubeClient.RbacV1().ClusterRoleBindings().Create(rbac) return err }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
integration/framework.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/integration/framework.go#L422-L433
go
train
// Parses and Returns a ServiceAccount object contained in 'filePath'
func (self *realKubeFramework) ParseServiceAccount(filePath string) (*v1.ServiceAccount, error)
// Parses and Returns a ServiceAccount object contained in 'filePath' func (self *realKubeFramework) ParseServiceAccount(filePath string) (*v1.ServiceAccount, error)
{ obj, err := self.loadObject(filePath) if err != nil { return nil, err } sa, ok := obj.(*v1.ServiceAccount) if !ok { return nil, fmt.Errorf("Failed to cast serviceaccount: %v", obj) } return sa, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
integration/framework.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/integration/framework.go#L436-L439
go
train
// CreateServiceAccount creates the ServiceAccount object
func (self *realKubeFramework) CreateServiceAccount(sa *v1.ServiceAccount) error
// CreateServiceAccount creates the ServiceAccount object func (self *realKubeFramework) CreateServiceAccount(sa *v1.ServiceAccount) error
{ _, err := self.kubeClient.CoreV1().ServiceAccounts(sa.Namespace).Create(sa) return err }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
common/honeycomb/honeycomb.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/common/honeycomb/honeycomb.go#L108-L130
go
train
// SendBatch splits the top-level batch into sub-batches if needed. Otherwise, // requests that are too large will be rejected by the Honeycomb API.
func (c *HoneycombClient) SendBatch(batch Batch) error
// SendBatch splits the top-level batch into sub-batches if needed. Otherwise, // requests that are too large will be rejected by the Honeycomb API. func (c *HoneycombClient) SendBatch(batch Batch) error
{ if len(batch) == 0 { // Nothing to send return nil } errs := []string{} for i := 0; i < len(batch); i += maxBatchSize { offset := i + maxBatchSize if offset > len(batch) { offset = len(batch) } if err := c.sendBatch(batch[i:offset]); err != nil { errs = append(errs, err.Error()) } } if len(errs) > 0 { return errors.New(strings.Join(errs, "\n")) } return nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/storage/nodemetrics/reststorage.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/storage/nodemetrics/reststorage.go#L75-L99
go
train
// Lister interface
func (m *MetricStorage) List(ctx genericapirequest.Context, options *metainternalversion.ListOptions) (runtime.Object, error)
// Lister interface func (m *MetricStorage) List(ctx genericapirequest.Context, options *metainternalversion.ListOptions) (runtime.Object, error)
{ labelSelector := labels.Everything() if options != nil && options.LabelSelector != nil { labelSelector = options.LabelSelector } nodes, err := m.nodeLister.ListWithPredicate(func(node *v1.Node) bool { if labelSelector.Empty() { return true } return labelSelector.Matches(labels.Set(node.Labels)) }) if err != nil { errMsg := fmt.Errorf("Error while listing nodes: %v", err) glog.Error(errMsg) return &metrics.NodeMetricsList{}, errMsg } res := metrics.NodeMetricsList{} for _, node := range nodes { if m := m.getNodeMetrics(node.Name); m != nil { res.Items = append(res.Items, *m) } } return &res, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/storage/nodemetrics/reststorage.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/storage/nodemetrics/reststorage.go#L102-L109
go
train
// Getter interface
func (m *MetricStorage) Get(ctx genericapirequest.Context, name string, opts *metav1.GetOptions) (runtime.Object, error)
// Getter interface func (m *MetricStorage) Get(ctx genericapirequest.Context, name string, opts *metav1.GetOptions) (runtime.Object, error)
{ // TODO: pay attention to get options nodeMetrics := m.getNodeMetrics(name) if nodeMetrics == nil { return &metrics.NodeMetrics{}, errors.NewNotFound(m.groupResource, name) } return nodeMetrics, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L50-L74
go
train
// checkSanitizedKey errors out if invalid characters are found in the key, since InfluxDB does not widely // support bound parameters yet (see https://github.com/influxdata/influxdb/pull/6634) and we need to // sanitize our inputs.
func (sink *influxdbSink) checkSanitizedKey(key *core.HistoricalKey) error
// checkSanitizedKey errors out if invalid characters are found in the key, since InfluxDB does not widely // support bound parameters yet (see https://github.com/influxdata/influxdb/pull/6634) and we need to // sanitize our inputs. func (sink *influxdbSink) checkSanitizedKey(key *core.HistoricalKey) error
{ if key.NodeName != "" && !nameAllowedChars.MatchString(key.NodeName) { return fmt.Errorf("Invalid node name %q", key.NodeName) } if key.NamespaceName != "" && !nameAllowedChars.MatchString(key.NamespaceName) { return fmt.Errorf("Invalid namespace name %q", key.NamespaceName) } if key.PodName != "" && !nameAllowedChars.MatchString(key.PodName) { return fmt.Errorf("Invalid pod name %q", key.PodName) } // NB: this prevents access to some of the free containers with slashes in their name // (e.g. system.slice/foo.bar), but the Heapster API seems to choke on the slashes anyway if key.ContainerName != "" && !nameAllowedChars.MatchString(key.ContainerName) { return fmt.Errorf("Invalid container name %q", key.ContainerName) } if key.PodId != "" && !nameAllowedChars.MatchString(key.PodId) { return fmt.Errorf("Invalid pod id %q", key.PodId) } return nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L78-L84
go
train
// checkSanitizedMetricName errors out if invalid characters are found in the metric name, since InfluxDB // does not widely support bound parameters yet, and we need to sanitize our inputs.
func (sink *influxdbSink) checkSanitizedMetricName(name string) error
// checkSanitizedMetricName errors out if invalid characters are found in the metric name, since InfluxDB // does not widely support bound parameters yet, and we need to sanitize our inputs. func (sink *influxdbSink) checkSanitizedMetricName(name string) error
{ if !metricAllowedChars.MatchString(name) { return fmt.Errorf("Invalid metric name %q", name) } return nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L88-L110
go
train
// checkSanitizedMetricLabels errors out if invalid characters are found in the label name or label value, since // InfluxDb does not widely support bound parameters yet, and we need to sanitize our inputs.
func (sink *influxdbSink) checkSanitizedMetricLabels(labels map[string]string) error
// checkSanitizedMetricLabels errors out if invalid characters are found in the label name or label value, since // InfluxDb does not widely support bound parameters yet, and we need to sanitize our inputs. func (sink *influxdbSink) checkSanitizedMetricLabels(labels map[string]string) error
{ // label names have the same restrictions as metric names, here for k, v := range labels { if !metricAllowedChars.MatchString(k) { return fmt.Errorf("Invalid label name %q", k) } // for metric values, we're somewhat more permissive. We allow any // Printable unicode character, except quotation marks, which are used // to delimit things. if strings.ContainsRune(v, '"') || strings.ContainsRune(v, '\'') { return fmt.Errorf("Invalid label value %q", v) } for _, runeVal := range v { if !unicode.IsPrint(runeVal) { return fmt.Errorf("Invalid label value %q", v) } } } return nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L114-L136
go
train
// aggregationFunc converts an aggregation name into the equivalent call to an InfluxQL // aggregation function
func (sink *influxdbSink) aggregationFunc(aggregationName core.AggregationType, fieldName string) string
// aggregationFunc converts an aggregation name into the equivalent call to an InfluxQL // aggregation function func (sink *influxdbSink) aggregationFunc(aggregationName core.AggregationType, fieldName string) string
{ switch aggregationName { case core.AggregationTypeAverage: return fmt.Sprintf("MEAN(%q)", fieldName) case core.AggregationTypeMaximum: return fmt.Sprintf("MAX(%q)", fieldName) case core.AggregationTypeMinimum: return fmt.Sprintf("MIN(%q)", fieldName) case core.AggregationTypeMedian: return fmt.Sprintf("MEDIAN(%q)", fieldName) case core.AggregationTypeCount: return fmt.Sprintf("COUNT(%q)", fieldName) case core.AggregationTypePercentile50: return fmt.Sprintf("PERCENTILE(%q, 50)", fieldName) case core.AggregationTypePercentile95: return fmt.Sprintf("PERCENTILE(%q, 95)", fieldName) case core.AggregationTypePercentile99: return fmt.Sprintf("PERCENTILE(%q, 99)", fieldName) } // This should have been checked by the API level, so something's seriously wrong here panic(fmt.Sprintf("Unknown aggregation type %q", aggregationName)) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L139-L166
go
train
// keyToSelector converts a HistoricalKey to an InfluxQL predicate
func (sink *influxdbSink) keyToSelector(key core.HistoricalKey) string
// keyToSelector converts a HistoricalKey to an InfluxQL predicate func (sink *influxdbSink) keyToSelector(key core.HistoricalKey) string
{ typeSel := fmt.Sprintf("type = '%s'", key.ObjectType) switch key.ObjectType { case core.MetricSetTypeNode: return fmt.Sprintf("%s AND %s = '%s'", typeSel, core.LabelNodename.Key, key.NodeName) case core.MetricSetTypeSystemContainer: return fmt.Sprintf("%s AND %s = '%s' AND %s = '%s'", typeSel, core.LabelContainerName.Key, key.ContainerName, core.LabelNodename.Key, key.NodeName) case core.MetricSetTypeCluster: return typeSel case core.MetricSetTypeNamespace: return fmt.Sprintf("%s AND %s = '%s'", typeSel, core.LabelNamespaceName.Key, key.NamespaceName) case core.MetricSetTypePod: if key.PodId != "" { return fmt.Sprintf("%s AND %s = '%s'", typeSel, core.LabelPodId.Key, key.PodId) } else { return fmt.Sprintf("%s AND %s = '%s' AND %s = '%s'", typeSel, core.LabelNamespaceName.Key, key.NamespaceName, core.LabelPodName.Key, key.PodName) } case core.MetricSetTypePodContainer: if key.PodId != "" { return fmt.Sprintf("%s AND %s = '%s' AND %s = '%s'", typeSel, core.LabelPodId.Key, key.PodId, core.LabelContainerName.Key, key.ContainerName) } else { return fmt.Sprintf("%s AND %s = '%s' AND %s = '%s' AND %s = '%s'", typeSel, core.LabelNamespaceName.Key, key.NamespaceName, core.LabelPodName.Key, key.PodName, core.LabelContainerName.Key, key.ContainerName) } } // These are assigned by the API, so it shouldn't be possible to reach this unless things are really broken panic(fmt.Sprintf("Unknown metric type %q", key.ObjectType)) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L169-L180
go
train
// labelsToPredicate composes an InfluxQL predicate based on the given map of labels
func (sink *influxdbSink) labelsToPredicate(labels map[string]string) string
// labelsToPredicate composes an InfluxQL predicate based on the given map of labels func (sink *influxdbSink) labelsToPredicate(labels map[string]string) string
{ if len(labels) == 0 { return "" } parts := make([]string, 0, len(labels)) for k, v := range labels { parts = append(parts, fmt.Sprintf("%q = '%s'", k, v)) } return strings.Join(parts, " AND ") }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L184-L195
go
train
// metricToSeriesAndField retrieves the appropriate field name and series name for a given metric // (this varies depending on whether or not WithFields is enabled)
func (sink *influxdbSink) metricToSeriesAndField(metricName string) (string, string)
// metricToSeriesAndField retrieves the appropriate field name and series name for a given metric // (this varies depending on whether or not WithFields is enabled) func (sink *influxdbSink) metricToSeriesAndField(metricName string) (string, string)
{ if sink.c.WithFields { seriesName := strings.SplitN(metricName, "/", 2) if len(seriesName) > 1 { return seriesName[0], seriesName[1] } else { return seriesName[0], "value" } } else { return metricName, "value" } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L198-L217
go
train
// composeRawQuery creates the InfluxQL query to fetch the given metric values
func (sink *influxdbSink) composeRawQuery(metricName string, labels map[string]string, metricKeys []core.HistoricalKey, start, end time.Time) string
// composeRawQuery creates the InfluxQL query to fetch the given metric values func (sink *influxdbSink) composeRawQuery(metricName string, labels map[string]string, metricKeys []core.HistoricalKey, start, end time.Time) string
{ seriesName, fieldName := sink.metricToSeriesAndField(metricName) queries := make([]string, len(metricKeys)) for i, key := range metricKeys { pred := sink.keyToSelector(key) if labels != nil { pred += fmt.Sprintf(" AND %s", sink.labelsToPredicate(labels)) } if !start.IsZero() { pred += fmt.Sprintf(" AND time > '%s'", start.Format(time.RFC3339)) } if !end.IsZero() { pred += fmt.Sprintf(" AND time < '%s'", end.Format(time.RFC3339)) } queries[i] = fmt.Sprintf("SELECT time, %q FROM %q WHERE %s", fieldName, seriesName, pred) } return strings.Join(queries, "; ") }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L221-L252
go
train
// parseRawQueryRow parses a set of timestamped metric values from unstructured JSON output into the // appropriate Heapster form
func (sink *influxdbSink) parseRawQueryRow(rawRow influx_models.Row) ([]core.TimestampedMetricValue, error)
// parseRawQueryRow parses a set of timestamped metric values from unstructured JSON output into the // appropriate Heapster form func (sink *influxdbSink) parseRawQueryRow(rawRow influx_models.Row) ([]core.TimestampedMetricValue, error)
{ vals := make([]core.TimestampedMetricValue, len(rawRow.Values)) wasInt := make(map[string]bool, 1) for i, rawVal := range rawRow.Values { val := core.TimestampedMetricValue{} if ts, err := time.Parse(time.RFC3339, rawVal[0].(string)); err != nil { return nil, fmt.Errorf("Unable to parse timestamp %q in series %q", rawVal[0].(string), rawRow.Name) } else { val.Timestamp = ts } if err := tryParseMetricValue("value", rawVal, &val.MetricValue, 1, wasInt); err != nil { glog.Errorf("Unable to parse field \"value\" in series %q: %v", rawRow.Name, err) return nil, fmt.Errorf("Unable to parse values in series %q", rawRow.Name) } vals[i] = val } if wasInt["value"] { for i := range vals { vals[i].MetricValue.ValueType = core.ValueInt64 } } else { for i := range vals { vals[i].MetricValue.ValueType = core.ValueFloat } } return vals, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L256-L291
go
train
// GetMetric retrieves the given metric for one or more objects (specified by metricKeys) of // the same type, within the given time interval
func (sink *influxdbSink) GetMetric(metricName string, metricKeys []core.HistoricalKey, start, end time.Time) (map[core.HistoricalKey][]core.TimestampedMetricValue, error)
// GetMetric retrieves the given metric for one or more objects (specified by metricKeys) of // the same type, within the given time interval func (sink *influxdbSink) GetMetric(metricName string, metricKeys []core.HistoricalKey, start, end time.Time) (map[core.HistoricalKey][]core.TimestampedMetricValue, error)
{ for _, key := range metricKeys { if err := sink.checkSanitizedKey(&key); err != nil { return nil, err } } if err := sink.checkSanitizedMetricName(metricName); err != nil { return nil, err } query := sink.composeRawQuery(metricName, nil, metricKeys, start, end) sink.RLock() defer sink.RUnlock() resp, err := sink.runQuery(query) if err != nil { return nil, err } res := make(map[core.HistoricalKey][]core.TimestampedMetricValue, len(metricKeys)) for i, key := range metricKeys { if len(resp[i].Series) < 1 { return nil, fmt.Errorf("No results for metric %q describing %q", metricName, key.String()) } vals, err := sink.parseRawQueryRow(resp[i].Series[0]) if err != nil { return nil, err } res[key] = vals } return res, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L337-L378
go
train
// composeAggregateQuery creates the InfluxQL query to fetch the given aggregation values
func (sink *influxdbSink) composeAggregateQuery(metricName string, labels map[string]string, aggregations []core.AggregationType, metricKeys []core.HistoricalKey, start, end time.Time, bucketSize time.Duration) string
// composeAggregateQuery creates the InfluxQL query to fetch the given aggregation values func (sink *influxdbSink) composeAggregateQuery(metricName string, labels map[string]string, aggregations []core.AggregationType, metricKeys []core.HistoricalKey, start, end time.Time, bucketSize time.Duration) string
{ seriesName, fieldName := sink.metricToSeriesAndField(metricName) var bucketSizeNanoSeconds int64 = 0 if bucketSize != 0 { bucketSizeNanoSeconds = int64(bucketSize.Nanoseconds() / int64(time.Microsecond/time.Nanosecond)) } queries := make([]string, len(metricKeys)) for i, key := range metricKeys { pred := sink.keyToSelector(key) if labels != nil { pred += fmt.Sprintf(" AND %s", sink.labelsToPredicate(labels)) } if !start.IsZero() { pred += fmt.Sprintf(" AND time > '%s'", start.Format(time.RFC3339)) } if !end.IsZero() { pred += fmt.Sprintf(" AND time < '%s'", end.Format(time.RFC3339)) } aggParts := make([]string, len(aggregations)) for i, agg := range aggregations { aggParts[i] = sink.aggregationFunc(agg, fieldName) } queries[i] = fmt.Sprintf("SELECT %s FROM %q WHERE %s", strings.Join(aggParts, ", "), seriesName, pred) if bucketSize != 0 { // group by time requires we have at least one time bound if start.IsZero() && end.IsZero() { queries[i] += fmt.Sprintf(" AND time < now()") } // fill(none) makes sure we skip data points will null values (otherwise we'll get a *bunch* of null // values when we go back beyond the time where we started collecting data). queries[i] += fmt.Sprintf(" GROUP BY time(%vu) fill(none)", bucketSizeNanoSeconds) } } return strings.Join(queries, "; ") }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L382-L422
go
train
// parseRawQueryRow parses a set of timestamped aggregation values from unstructured JSON output into the // appropriate Heapster form
func (sink *influxdbSink) parseAggregateQueryRow(rawRow influx_models.Row, aggregationLookup map[core.AggregationType]int, bucketSize time.Duration) ([]core.TimestampedAggregationValue, error)
// parseRawQueryRow parses a set of timestamped aggregation values from unstructured JSON output into the // appropriate Heapster form func (sink *influxdbSink) parseAggregateQueryRow(rawRow influx_models.Row, aggregationLookup map[core.AggregationType]int, bucketSize time.Duration) ([]core.TimestampedAggregationValue, error)
{ vals := make([]core.TimestampedAggregationValue, len(rawRow.Values)) wasInt := make(map[string]bool, len(aggregationLookup)) for i, rawVal := range rawRow.Values { val := core.TimestampedAggregationValue{ BucketSize: bucketSize, AggregationValue: core.AggregationValue{ Aggregations: map[core.AggregationType]core.MetricValue{}, }, } if ts, err := time.Parse(time.RFC3339, rawVal[0].(string)); err != nil { return nil, fmt.Errorf("Unable to parse timestamp %q in series %q", rawVal[0].(string), rawRow.Name) } else { val.Timestamp = ts } // The Influx client decods numeric fields to json.Number (a string), so we have to try decoding to both types of numbers // Count is always a uint64 if countIndex, ok := aggregationLookup[core.AggregationTypeCount]; ok { if err := json.Unmarshal([]byte(rawVal[countIndex].(json.Number).String()), &val.Count); err != nil { glog.Errorf("Unable to parse count value in series %q: %v", rawRow.Name, err) return nil, fmt.Errorf("Unable to parse values in series %q", rawRow.Name) } } // The rest of the aggregation values can be either float or int, so attempt to parse both if err := populateAggregations(rawRow.Name, rawVal, &val, aggregationLookup, wasInt); err != nil { return nil, err } vals[i] = val } // figure out whether each aggregation was full of float values, or int values setAggregationValueTypes(vals, wasInt) return vals, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L426-L469
go
train
// GetAggregation fetches the given aggregations for one or more objects (specified by metricKeys) of // the same type, within the given time interval, calculated over a series of buckets
func (sink *influxdbSink) GetAggregation(metricName string, aggregations []core.AggregationType, metricKeys []core.HistoricalKey, start, end time.Time, bucketSize time.Duration) (map[core.HistoricalKey][]core.TimestampedAggregationValue, error)
// GetAggregation fetches the given aggregations for one or more objects (specified by metricKeys) of // the same type, within the given time interval, calculated over a series of buckets func (sink *influxdbSink) GetAggregation(metricName string, aggregations []core.AggregationType, metricKeys []core.HistoricalKey, start, end time.Time, bucketSize time.Duration) (map[core.HistoricalKey][]core.TimestampedAggregationValue, error)
{ for _, key := range metricKeys { if err := sink.checkSanitizedKey(&key); err != nil { return nil, err } } if err := sink.checkSanitizedMetricName(metricName); err != nil { return nil, err } // make it easy to look up where the different aggregations are in the list aggregationLookup := make(map[core.AggregationType]int, len(aggregations)) for i, agg := range aggregations { aggregationLookup[agg] = i + 1 } query := sink.composeAggregateQuery(metricName, nil, aggregations, metricKeys, start, end, bucketSize) sink.RLock() defer sink.RUnlock() resp, err := sink.runQuery(query) if err != nil { return nil, err } // TODO: when there are too many points (e.g. certain times when a start time is not specified), Influx will sometimes return only a single bucket // instead of returning an error. We should detect this case and return an error ourselves (or maybe just require a start time at the API level) res := make(map[core.HistoricalKey][]core.TimestampedAggregationValue, len(metricKeys)) for i, key := range metricKeys { if len(resp[i].Series) < 1 { return nil, fmt.Errorf("No results for metric %q describing %q", metricName, key.String()) } vals, err := sink.parseAggregateQueryRow(resp[i].Series[0], aggregationLookup, bucketSize) if err != nil { return nil, err } res[key] = vals } return res, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L524-L535
go
train
// setAggregationValueIfPresent checks if the given metric value is present in the list of raw values, and if so, // copies it to the output format
func setAggregationValueIfPresent(aggName core.AggregationType, rawVal []interface{}, aggregations *core.AggregationValue, indexLookup map[core.AggregationType]int, wasInt map[string]bool) error
// setAggregationValueIfPresent checks if the given metric value is present in the list of raw values, and if so, // copies it to the output format func setAggregationValueIfPresent(aggName core.AggregationType, rawVal []interface{}, aggregations *core.AggregationValue, indexLookup map[core.AggregationType]int, wasInt map[string]bool) error
{ if fieldIndex, ok := indexLookup[aggName]; ok { targetValue := &core.MetricValue{} if err := tryParseMetricValue(string(aggName), rawVal, targetValue, fieldIndex, wasInt); err != nil { return err } aggregations.Aggregations[aggName] = *targetValue } return nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L538-L567
go
train
// tryParseMetricValue attempts to parse a raw metric value into the appropriate go type.
func tryParseMetricValue(aggName string, rawVal []interface{}, targetValue *core.MetricValue, fieldIndex int, wasInt map[string]bool) error
// tryParseMetricValue attempts to parse a raw metric value into the appropriate go type. func tryParseMetricValue(aggName string, rawVal []interface{}, targetValue *core.MetricValue, fieldIndex int, wasInt map[string]bool) error
{ // the Influx client decodes numeric fields to json.Number (a string), so we have to deal with that -- // assume, starting off, that values may be either float or int. Try int until we fail once, and always // try float. At the end, figure out which is which. var rv string if rvN, ok := rawVal[fieldIndex].(json.Number); !ok { return fmt.Errorf("Value %q of metric %q was not a json.Number", rawVal[fieldIndex], aggName) } else { rv = rvN.String() } tryInt := false isInt, triedBefore := wasInt[aggName] tryInt = isInt || !triedBefore if tryInt { if err := json.Unmarshal([]byte(rv), &targetValue.IntValue); err != nil { wasInt[aggName] = false } else { wasInt[aggName] = true } } if err := json.Unmarshal([]byte(rv), &targetValue.FloatValue); err != nil { return err } return nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L570-L575
go
train
// GetMetricNames retrieves the available metric names for the given object
func (sink *influxdbSink) GetMetricNames(metricKey core.HistoricalKey) ([]string, error)
// GetMetricNames retrieves the available metric names for the given object func (sink *influxdbSink) GetMetricNames(metricKey core.HistoricalKey) ([]string, error)
{ if err := sink.checkSanitizedKey(&metricKey); err != nil { return nil, err } return sink.stringListQuery(fmt.Sprintf("SHOW MEASUREMENTS WHERE %s", sink.keyToSelector(metricKey)), "Unable to list available metrics") }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L578-L580
go
train
// GetNodes retrieves the list of nodes in the cluster
func (sink *influxdbSink) GetNodes() ([]string, error)
// GetNodes retrieves the list of nodes in the cluster func (sink *influxdbSink) GetNodes() ([]string, error)
{ return sink.stringListQuery(fmt.Sprintf("SHOW TAG VALUES WITH KEY = %s", core.LabelNodename.Key), "Unable to list all nodes") }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L583-L585
go
train
// GetNamespaces retrieves the list of namespaces in the cluster
func (sink *influxdbSink) GetNamespaces() ([]string, error)
// GetNamespaces retrieves the list of namespaces in the cluster func (sink *influxdbSink) GetNamespaces() ([]string, error)
{ return sink.stringListQuery(fmt.Sprintf("SHOW TAG VALUES WITH KEY = %s", core.LabelNamespaceName.Key), "Unable to list all namespaces") }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L588-L597
go
train
// GetPodsFromNamespace retrieves the list of pods in a given namespace
func (sink *influxdbSink) GetPodsFromNamespace(namespace string) ([]string, error)
// GetPodsFromNamespace retrieves the list of pods in a given namespace func (sink *influxdbSink) GetPodsFromNamespace(namespace string) ([]string, error)
{ if !nameAllowedChars.MatchString(namespace) { return nil, fmt.Errorf("Invalid namespace name %q", namespace) } // This is a bit difficult for the influx query language, so we cheat a bit here -- // we just get all series for the uptime measurement for pods which match our namespace // (any measurement should work here, though) q := fmt.Sprintf("SHOW SERIES FROM %q WHERE %s = '%s' AND type = '%s'", core.MetricUptime.MetricDescriptor.Name, core.LabelNamespaceName.Key, namespace, core.MetricSetTypePod) return sink.stringListQueryCol(q, core.LabelPodName.Key, fmt.Sprintf("Unable to list pods in namespace %q", namespace)) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L600-L609
go
train
// GetSystemContainersFromNode retrieves the list of free containers for a given node
func (sink *influxdbSink) GetSystemContainersFromNode(node string) ([]string, error)
// GetSystemContainersFromNode retrieves the list of free containers for a given node func (sink *influxdbSink) GetSystemContainersFromNode(node string) ([]string, error)
{ if !nameAllowedChars.MatchString(node) { return nil, fmt.Errorf("Invalid node name %q", node) } // This is a bit difficult for the influx query language, so we cheat a bit here -- // we just get all series for the uptime measurement for system containers on our node // (any measurement should work here, though) q := fmt.Sprintf("SHOW SERIES FROM %q WHERE %s = '%s' AND type = '%s'", core.MetricUptime.MetricDescriptor.Name, core.LabelNodename.Key, node, core.MetricSetTypeSystemContainer) return sink.stringListQueryCol(q, core.LabelContainerName.Key, fmt.Sprintf("Unable to list system containers on node %q", node)) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L612-L643
go
train
// stringListQueryCol runs the given query, and returns all results from the given column as a string list
func (sink *influxdbSink) stringListQueryCol(q, colName string, errStr string) ([]string, error)
// stringListQueryCol runs the given query, and returns all results from the given column as a string list func (sink *influxdbSink) stringListQueryCol(q, colName string, errStr string) ([]string, error)
{ sink.RLock() defer sink.RUnlock() resp, err := sink.runQuery(q) if err != nil { return nil, fmt.Errorf(errStr) } if len(resp[0].Series) < 1 { return nil, fmt.Errorf(errStr) } colInd := -1 for i, col := range resp[0].Series[0].Columns { if col == colName { colInd = i break } } if colInd == -1 { glog.Errorf("%s: results did not contain the %q column", errStr, core.LabelPodName.Key) return nil, fmt.Errorf(errStr) } res := make([]string, len(resp[0].Series[0].Values)) for i, rv := range resp[0].Series[0].Values { res[i] = rv[colInd].(string) } return res, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L646-L664
go
train
// stringListQuery runs the given query, and returns all results from the first column as a string list
func (sink *influxdbSink) stringListQuery(q string, errStr string) ([]string, error)
// stringListQuery runs the given query, and returns all results from the first column as a string list func (sink *influxdbSink) stringListQuery(q string, errStr string) ([]string, error)
{ sink.RLock() defer sink.RUnlock() resp, err := sink.runQuery(q) if err != nil { return nil, fmt.Errorf(errStr) } if len(resp[0].Series) < 1 { return nil, fmt.Errorf(errStr) } res := make([]string, len(resp[0].Series[0].Values)) for i, rv := range resp[0].Series[0].Values { res[i] = rv[0].(string) } return res, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L668-L697
go
train
// runQuery executes the given query against InfluxDB (using the default database for this sink) // The caller is responsible for locking the sink before use.
func (sink *influxdbSink) runQuery(queryStr string) ([]influxdb.Result, error)
// runQuery executes the given query against InfluxDB (using the default database for this sink) // The caller is responsible for locking the sink before use. func (sink *influxdbSink) runQuery(queryStr string) ([]influxdb.Result, error)
{ // ensure we have a valid client handle before attempting to use it if err := sink.ensureClient(); err != nil { glog.Errorf("Unable to ensure InfluxDB client is present: %v", err) return nil, fmt.Errorf("unable to run query: unable to connect to database") } q := influxdb.Query{ Command: queryStr, Database: sink.c.DbName, } glog.V(4).Infof("Executing query %q against database %q", q.Command, q.Database) resp, err := sink.client.Query(q) if err != nil { glog.Errorf("Unable to perform query %q against database %q: %v", q.Command, q.Database, err) return nil, err } else if resp.Error() != nil { glog.Errorf("Unable to perform query %q against database %q: %v", q.Command, q.Database, resp.Error()) return nil, resp.Error() } if len(resp.Results) < 1 { glog.Errorf("Unable to perform query %q against database %q: no results returned", q.Command, q.Database) return nil, fmt.Errorf("No results returned") } return resp.Results, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L700-L709
go
train
// populateAggregations extracts aggregation values from a given data point
func populateAggregations(rawRowName string, rawVal []interface{}, val *core.TimestampedAggregationValue, aggregationLookup map[core.AggregationType]int, wasInt map[string]bool) error
// populateAggregations extracts aggregation values from a given data point func populateAggregations(rawRowName string, rawVal []interface{}, val *core.TimestampedAggregationValue, aggregationLookup map[core.AggregationType]int, wasInt map[string]bool) error
{ for _, aggregation := range core.MultiTypedAggregations { if err := setAggregationValueIfPresent(aggregation, rawVal, &val.AggregationValue, aggregationLookup, wasInt); err != nil { glog.Errorf("Unable to parse field %q in series %q: %v", aggregation, rawRowName, err) return fmt.Errorf("Unable to parse values in series %q", rawRowName) } } return nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/influxdb/influxdb_historical.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/influxdb/influxdb_historical.go#L713-L729
go
train
// setAggregationValueTypes inspects a set of aggregation values and figures out whether each aggregation value // returned as a float column, or an int column
func setAggregationValueTypes(vals []core.TimestampedAggregationValue, wasInt map[string]bool)
// setAggregationValueTypes inspects a set of aggregation values and figures out whether each aggregation value // returned as a float column, or an int column func setAggregationValueTypes(vals []core.TimestampedAggregationValue, wasInt map[string]bool)
{ for _, aggregation := range core.MultiTypedAggregations { if isInt, ok := wasInt[string(aggregation)]; ok && isInt { for i := range vals { val := vals[i].Aggregations[aggregation] val.ValueType = core.ValueInt64 vals[i].Aggregations[aggregation] = val } } else if ok { for i := range vals { val := vals[i].Aggregations[aggregation] val.ValueType = core.ValueFloat vals[i].Aggregations[aggregation] = val } } } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/metric/metric_sink.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/metric/metric_sink.go#L256-L260
go
train
/* * For debugging only. */
func (this *MetricSink) GetMetricSetKeys() []string
/* * For debugging only. */ func (this *MetricSink) GetMetricSetKeys() []string
{ return this.getAllNames( func(ms *core.MetricSet) bool { return true }, func(key string, ms *core.MetricSet) string { return key }) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/gcm/gcm.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/gcm/gcm.go#L217-L297
go
train
// Adds the specified metrics or updates them if they already exist.
func (sink *gcmSink) register(metrics []core.Metric) error
// Adds the specified metrics or updates them if they already exist. func (sink *gcmSink) register(metrics []core.Metric) error
{ sink.Lock() defer sink.Unlock() if sink.registered { return nil } for _, metric := range metrics { metricName := fullMetricName(sink.project, metric.MetricDescriptor.Name) metricType := fullMetricType(metric.MetricDescriptor.Name) if _, err := sink.gcmService.Projects.MetricDescriptors.Delete(metricName).Do(); err != nil { glog.Infof("[GCM] Deleting metric %v failed: %v", metricName, err) } labels := make([]*gcm.LabelDescriptor, 0) // Node autoscaling metrics have special labels. if core.IsNodeAutoscalingMetric(metric.MetricDescriptor.Name) { // All and autoscaling. Do not populate for other filters. if sink.metricFilter != metricsAll && sink.metricFilter != metricsOnlyAutoscaling { continue } for _, l := range core.GcmNodeAutoscalingLabels() { labels = append(labels, &gcm.LabelDescriptor{ Key: l.Key, Description: l.Description, }) } } else { // Only all. if sink.metricFilter != metricsAll { continue } for _, l := range core.GcmLabels() { labels = append(labels, &gcm.LabelDescriptor{ Key: l.Key, Description: l.Description, }) } } var metricKind string switch metric.MetricDescriptor.Type { case core.MetricCumulative: metricKind = "CUMULATIVE" case core.MetricGauge: metricKind = "GAUGE" case core.MetricDelta: metricKind = "DELTA" } var valueType string switch metric.MetricDescriptor.ValueType { case core.ValueInt64: valueType = "INT64" case core.ValueFloat: valueType = "DOUBLE" } desc := &gcm.MetricDescriptor{ Name: metricName, Description: metric.MetricDescriptor.Description, Labels: labels, MetricKind: metricKind, ValueType: valueType, Type: metricType, } if _, err := sink.gcmService.Projects.MetricDescriptors.Create(fullProjectName(sink.project), desc).Do(); err != nil { glog.Errorf("Metric registration of %v failed: %v", desc.Name, err) return err } } sink.registered = true return nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/manager.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/manager.go#L106-L124
go
train
// Guarantees that the export will complete in sinkExportDataTimeout.
func (this *sinkManager) ExportData(data *core.DataBatch)
// Guarantees that the export will complete in sinkExportDataTimeout. func (this *sinkManager) ExportData(data *core.DataBatch)
{ var wg sync.WaitGroup for _, sh := range this.sinkHolders { wg.Add(1) go func(sh sinkHolder, wg *sync.WaitGroup) { defer wg.Done() glog.V(2).Infof("Pushing data to: %s", sh.sink.Name()) select { case sh.dataBatchChannel <- data: glog.V(2).Infof("Data push completed: %s", sh.sink.Name()) // everything ok case <-time.After(this.exportDataTimeout): glog.Warningf("Failed to push data to sink: %s", sh.sink.Name()) } }(sh, &wg) } // Wait for all pushes to complete or timeout. wg.Wait() }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
events/sinks/riemann/driver.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/events/sinks/riemann/driver.go#L38-L49
go
train
// creates a Riemann sink. Returns a riemannSink
func CreateRiemannSink(uri *url.URL) (core.EventSink, error)
// creates a Riemann sink. Returns a riemannSink func CreateRiemannSink(uri *url.URL) (core.EventSink, error)
{ var sink, err = riemannCommon.CreateRiemannSink(uri) if err != nil { glog.Warningf("Error creating the Riemann metrics sink: %v", err) return nil, err } rs := &RiemannSink{ client: sink.Client, config: sink.Config, } return rs, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/cmd/heapster-apiserver/app/server.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/cmd/heapster-apiserver/app/server.go#L39-L42
go
train
// Run runs the specified APIServer. This should never exit.
func (h *HeapsterAPIServer) RunServer() error
// Run runs the specified APIServer. This should never exit. func (h *HeapsterAPIServer) RunServer() error
{ h.PrepareRun().Run(wait.NeverStop) return nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sources/kubelet/kubelet_client.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sources/kubelet/kubelet_client.go#L152-L156
go
train
// Get stats for all non-Kubernetes containers.
func (self *KubeletClient) GetAllRawContainers(host Host, start, end time.Time) ([]cadvisor.ContainerInfo, error)
// Get stats for all non-Kubernetes containers. func (self *KubeletClient) GetAllRawContainers(host Host, start, end time.Time) ([]cadvisor.ContainerInfo, error)
{ url := self.getUrl(host, "/stats/container/") return self.getAllContainers(url, start, end) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/util/metrics/http.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/util/metrics/http.go#L36-L103
go
train
// InstrumentRouteFunc works like Prometheus' InstrumentHandlerFunc but wraps // the go-restful RouteFunction instead of a HandlerFunc
func InstrumentRouteFunc(handlerName string, routeFunc restful.RouteFunction) restful.RouteFunction
// InstrumentRouteFunc works like Prometheus' InstrumentHandlerFunc but wraps // the go-restful RouteFunction instead of a HandlerFunc func InstrumentRouteFunc(handlerName string, routeFunc restful.RouteFunction) restful.RouteFunction
{ opts := prometheus.SummaryOpts{ Subsystem: "http", ConstLabels: prometheus.Labels{"handler": handlerName}, } reqCnt := prometheus.NewCounterVec( prometheus.CounterOpts{ Subsystem: opts.Subsystem, Name: "requests_total", Help: "Total number of HTTP requests made.", ConstLabels: opts.ConstLabels, }, instLabels, ) opts.Name = "request_duration_microseconds" opts.Help = "The HTTP request latencies in microseconds." reqDur := prometheus.NewSummary(opts) opts.Name = "request_size_bytes" opts.Help = "The HTTP request sizes in bytes." reqSz := prometheus.NewSummary(opts) opts.Name = "response_size_bytes" opts.Help = "The HTTP response sizes in bytes." resSz := prometheus.NewSummary(opts) regReqCnt := prometheus.MustRegisterOrGet(reqCnt).(*prometheus.CounterVec) regReqDur := prometheus.MustRegisterOrGet(reqDur).(prometheus.Summary) regReqSz := prometheus.MustRegisterOrGet(reqSz).(prometheus.Summary) regResSz := prometheus.MustRegisterOrGet(resSz).(prometheus.Summary) return restful.RouteFunction(func(request *restful.Request, response *restful.Response) { now := time.Now() delegate := &responseWriterDelegator{ResponseWriter: response.ResponseWriter} out := make(chan int) urlLen := 0 if request.Request.URL != nil { urlLen = len(request.Request.URL.String()) } go computeApproximateRequestSize(request.Request, out, urlLen) _, cn := response.ResponseWriter.(http.CloseNotifier) _, fl := response.ResponseWriter.(http.Flusher) _, hj := response.ResponseWriter.(http.Hijacker) _, rf := response.ResponseWriter.(io.ReaderFrom) var rw http.ResponseWriter if cn && fl && hj && rf { rw = &fancyResponseWriterDelegator{delegate} } else { rw = delegate } response.ResponseWriter = rw routeFunc(request, response) elapsed := float64(time.Since(now)) / float64(time.Microsecond) method := strings.ToLower(request.Request.Method) code := strconv.Itoa(delegate.status) regReqCnt.WithLabelValues(method, code).Inc() regReqDur.Observe(elapsed) regResSz.Observe(float64(delegate.written)) regReqSz.Observe(float64(<-out)) }) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/core/ms_keys.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/core/ms_keys.go#L26-L28
go
train
// MetricsSet keys are inside of DataBatch. The structure of the returned string is // an implementation detail and no component should rely on it as it may change // anytime. It only guaranteed that it is unique for the unique combination of // passed parameters.
func PodContainerKey(namespace, podName, containerName string) string
// MetricsSet keys are inside of DataBatch. The structure of the returned string is // an implementation detail and no component should rely on it as it may change // anytime. It only guaranteed that it is unique for the unique combination of // passed parameters. func PodContainerKey(namespace, podName, containerName string) string
{ return fmt.Sprintf("namespace:%s/pod:%s/container:%s", namespace, podName, containerName) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/processors/namespace_based_enricher.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/processors/namespace_based_enricher.go#L49-L78
go
train
// Adds UID to all namespaced elements.
func (this *NamespaceBasedEnricher) addNamespaceInfo(metricSet *core.MetricSet)
// Adds UID to all namespaced elements. func (this *NamespaceBasedEnricher) addNamespaceInfo(metricSet *core.MetricSet)
{ metricSetType, found := metricSet.Labels[core.LabelMetricSetType.Key] if !found { return } if metricSetType != core.MetricSetTypePodContainer && metricSetType != core.MetricSetTypePod && metricSetType != core.MetricSetTypeNamespace { return } namespaceName, found := metricSet.Labels[core.LabelNamespaceName.Key] if !found { return } nsObj, exists, err := this.store.GetByKey(namespaceName) if exists && err == nil { namespace, ok := nsObj.(*kube_api.Namespace) if ok { metricSet.Labels[core.LabelPodNamespaceUID.Key] = string(namespace.UID) } else { glog.Errorf("Wrong namespace store content") } } else if err != nil { glog.Warningf("Failed to get namespace %s: %v", namespaceName, err) } else if !exists { glog.Warningf("Namespace doesn't exist: %s", namespaceName) } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L79-L257
go
train
// addClusterMetricsRoutes adds all the standard model routes to a WebService. // It should already have a base path registered.
func addClusterMetricsRoutes(a clusterMetricsFetcher, ws *restful.WebService)
// addClusterMetricsRoutes adds all the standard model routes to a WebService. // It should already have a base path registered. func addClusterMetricsRoutes(a clusterMetricsFetcher, ws *restful.WebService)
{ // The /metrics/ endpoint returns a list of all available metrics for the Cluster entity of the model. ws.Route(ws.GET("/metrics/"). To(metrics.InstrumentRouteFunc("availableClusterMetrics", a.availableClusterMetrics)). Doc("Get a list of all available metrics for the Cluster entity"). Operation("availableClusterMetrics")) // The /metrics/{metric-name} endpoint exposes an aggregated metric for the Cluster entity of the model. ws.Route(ws.GET("/metrics/{metric-name:*}"). To(metrics.InstrumentRouteFunc("clusterMetrics", a.clusterMetrics)). Doc("Export an aggregated cluster-level metric"). Operation("clusterMetrics"). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metric").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricResult{})) // The /nodes/{node-name}/metrics endpoint returns a list of all nodes with some metrics. ws.Route(ws.GET("/nodes/"). To(metrics.InstrumentRouteFunc("nodeList", a.nodeList)). Doc("Get a list of all nodes that have some current metrics"). Operation("nodeList")) // The /nodes/{node-name}/metrics endpoint returns a list of all available metrics for a Node entity. ws.Route(ws.GET("/nodes/{node-name}/metrics/"). To(metrics.InstrumentRouteFunc("availableNodeMetrics", a.availableNodeMetrics)). Doc("Get a list of all available metrics for a Node entity"). Operation("availableNodeMetrics"). Param(ws.PathParameter("node-name", "The name of the node to lookup").DataType("string"))) // The /nodes/{node-name}/metrics/{metric-name} endpoint exposes a metric for a Node entity of the model. // The {node-name} parameter is the hostname of a specific node. ws.Route(ws.GET("/nodes/{node-name}/metrics/{metric-name:*}"). To(metrics.InstrumentRouteFunc("nodeMetrics", a.nodeMetrics)). Doc("Export a node-level metric"). Operation("nodeMetrics"). Param(ws.PathParameter("node-name", "The name of the node to lookup").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metric").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricResult{})) if a.isRunningInKubernetes() { ws.Route(ws.GET("/namespaces/"). To(metrics.InstrumentRouteFunc("namespaceList", a.namespaceList)). Doc("Get a list of all namespaces that have some current metrics"). Operation("namespaceList")) // The /namespaces/{namespace-name}/metrics endpoint returns a list of all available metrics for a Namespace entity. ws.Route(ws.GET("/namespaces/{namespace-name}/metrics"). To(metrics.InstrumentRouteFunc("availableNamespaceMetrics", a.availableNamespaceMetrics)). Doc("Get a list of all available metrics for a Namespace entity"). Operation("availableNamespaceMetrics"). Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string"))) // The /namespaces/{namespace-name}/metrics/{metric-name} endpoint exposes an aggregated metrics // for a Namespace entity of the model. ws.Route(ws.GET("/namespaces/{namespace-name}/metrics/{metric-name:*}"). To(metrics.InstrumentRouteFunc("namespaceMetrics", a.namespaceMetrics)). Doc("Export an aggregated namespace-level metric"). Operation("namespaceMetrics"). Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricResult{})) ws.Route(ws.GET("/namespaces/{namespace-name}/pods/"). To(metrics.InstrumentRouteFunc("namespacePodList", a.namespacePodList)). Doc("Get a list of pods from the given namespace that have some metrics"). Operation("namespacePodList"). Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string"))) // The /namespaces/{namespace-name}/pods/{pod-name}/metrics endpoint returns a list of all available metrics for a Pod entity. ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/metrics"). To(metrics.InstrumentRouteFunc("availablePodMetrics", a.availablePodMetrics)). Doc("Get a list of all available metrics for a Pod entity"). Operation("availablePodMetrics"). Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")). Param(ws.PathParameter("pod-name", "The name of the pod to lookup").DataType("string"))) // The /namespaces/{namespace-name}/pods/{pod-name}/metrics/{metric-name} endpoint exposes // an aggregated metric for a Pod entity of the model. ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/metrics/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podMetrics", a.podMetrics)). Doc("Export an aggregated pod-level metric"). Operation("podMetrics"). Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")). Param(ws.PathParameter("pod-name", "The name of the pod to lookup").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricResult{})) // The /namespaces/{namespace-name}/pods/{pod-name}/containers endpoint // returns a list of all containers for a Pod entity. ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/containers"). To(metrics.InstrumentRouteFunc("podContainerList", a.podContainerList)). Doc("Get a list of containers for a Pod entity "). Operation("podContainerList"). Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")). Param(ws.PathParameter("pod-name", "The name of the pod to lookup").DataType("string"))) // The /namespaces/{namespace-name}/pods/{pod-name}/containers/metrics/{container-name}/metrics endpoint // returns a list of all available metrics for a Pod Container entity. ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics"). To(metrics.InstrumentRouteFunc("availableContainerMetrics", a.availablePodContainerMetrics)). Doc("Get a list of all available metrics for a Pod entity"). Operation("availableContainerMetrics"). Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")). Param(ws.PathParameter("pod-name", "The name of the pod to lookup").DataType("string")). Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string"))) // The /namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics/{metric-name} endpoint exposes // a metric for a Container entity of the model. ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podContainerMetrics", a.podContainerMetrics)). Doc("Export an aggregated metric for a Pod Container"). Operation("podContainerMetrics"). Param(ws.PathParameter("namespace-name", "The name of the namespace to use").DataType("string")). Param(ws.PathParameter("pod-name", "The name of the pod to use").DataType("string")). Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricResult{})) } ws.Route(ws.GET("/nodes/{node-name}/freecontainers/"). To(metrics.InstrumentRouteFunc("systemContainerList", a.nodeSystemContainerList)). Doc("Get a list of all non-pod containers with some metrics"). Operation("systemContainerList"). Param(ws.PathParameter("node-name", "The name of the namespace to lookup").DataType("string"))) // The /nodes/{node-name}/freecontainers/{container-name}/metrics endpoint // returns a list of all available metrics for a Free Container entity. ws.Route(ws.GET("/nodes/{node-name}/freecontainers/{container-name}/metrics"). To(metrics.InstrumentRouteFunc("availableMetrics", a.availableFreeContainerMetrics)). Doc("Get a list of all available metrics for a free Container entity"). Operation("availableMetrics"). Param(ws.PathParameter("node-name", "The name of the namespace to lookup").DataType("string")). Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string"))) // The /nodes/{node-name}/freecontainers/{container-name}/metrics/{metric-name} endpoint exposes // a metric for a free Container entity of the model. ws.Route(ws.GET("/nodes/{node-name}/freecontainers/{container-name}/metrics/{metric-name:*}"). To(metrics.InstrumentRouteFunc("freeContainerMetrics", a.freeContainerMetrics)). Doc("Export a container-level metric for a free container"). Operation("freeContainerMetrics"). Param(ws.PathParameter("node-name", "The name of the node to use").DataType("string")). Param(ws.PathParameter("container-name", "The name of the container to use").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricResult{})) if a.isRunningInKubernetes() { // The /namespaces/{namespace-name}/pod-list/{pod-list}/metrics/{metric-name} endpoint exposes // metrics for a list of pods of the model. ws.Route(ws.GET("/namespaces/{namespace-name}/pod-list/{pod-list}/metrics/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podListMetric", a.podListMetrics)). Doc("Export a metric for all pods from the given list"). Operation("podListMetric"). Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")). Param(ws.PathParameter("pod-list", "Comma separated list of pod names to lookup").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricResult{})) } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L266-L280
go
train
// RegisterModel registers the Model API endpoints. // All endpoints that end with a {metric-name} also receive a start time query parameter. // The start and end times should be specified as a string, formatted according to RFC 3339.
func (a *Api) RegisterModel(container *restful.Container)
// RegisterModel registers the Model API endpoints. // All endpoints that end with a {metric-name} also receive a start time query parameter. // The start and end times should be specified as a string, formatted according to RFC 3339. func (a *Api) RegisterModel(container *restful.Container)
{ ws := new(restful.WebService) ws.Path("/api/v1/model"). Doc("Root endpoint of the stats model"). Consumes("*/*"). Produces(restful.MIME_JSON) addClusterMetricsRoutes(a, ws) ws.Route(ws.GET("/debug/allkeys"). To(metrics.InstrumentRouteFunc("debugAllKeys", a.allKeys)). Doc("Get keys of all metric sets available"). Operation("debugAllKeys")) container.Add(ws) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L283-L285
go
train
// availableMetrics returns a list of available cluster metric names.
func (a *Api) availableClusterMetrics(request *restful.Request, response *restful.Response)
// availableMetrics returns a list of available cluster metric names. func (a *Api) availableClusterMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricNamesRequest(core.ClusterKey(), response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L288-L290
go
train
// availableMetrics returns a list of available node metric names.
func (a *Api) availableNodeMetrics(request *restful.Request, response *restful.Response)
// availableMetrics returns a list of available node metric names. func (a *Api) availableNodeMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricNamesRequest(core.NodeKey(request.PathParameter("node-name")), response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L293-L295
go
train
// availableMetrics returns a list of available namespace metric names.
func (a *Api) availableNamespaceMetrics(request *restful.Request, response *restful.Response)
// availableMetrics returns a list of available namespace metric names. func (a *Api) availableNamespaceMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricNamesRequest(core.NamespaceKey(request.PathParameter("namespace-name")), response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L298-L302
go
train
// availableMetrics returns a list of available pod metric names.
func (a *Api) availablePodMetrics(request *restful.Request, response *restful.Response)
// availableMetrics returns a list of available pod metric names. func (a *Api) availablePodMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricNamesRequest( core.PodKey(request.PathParameter("namespace-name"), request.PathParameter("pod-name")), response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L305-L311
go
train
// availableMetrics returns a list of available pod metric names.
func (a *Api) availablePodContainerMetrics(request *restful.Request, response *restful.Response)
// availableMetrics returns a list of available pod metric names. func (a *Api) availablePodContainerMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricNamesRequest( core.PodContainerKey(request.PathParameter("namespace-name"), request.PathParameter("pod-name"), request.PathParameter("container-name"), ), response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L314-L319
go
train
// availableMetrics returns a list of available pod metric names.
func (a *Api) availableFreeContainerMetrics(request *restful.Request, response *restful.Response)
// availableMetrics returns a list of available pod metric names. func (a *Api) availableFreeContainerMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricNamesRequest( core.NodeContainerKey(request.PathParameter("node-name"), request.PathParameter("container-name"), ), response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L346-L348
go
train
// clusterMetrics returns a metric timeseries for a metric of the Cluster entity.
func (a *Api) clusterMetrics(request *restful.Request, response *restful.Response)
// clusterMetrics returns a metric timeseries for a metric of the Cluster entity. func (a *Api) clusterMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricRequest(core.ClusterKey(), request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L351-L354
go
train
// nodeMetrics returns a metric timeseries for a metric of the Node entity.
func (a *Api) nodeMetrics(request *restful.Request, response *restful.Response)
// nodeMetrics returns a metric timeseries for a metric of the Node entity. func (a *Api) nodeMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricRequest(core.NodeKey(request.PathParameter("node-name")), request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L357-L360
go
train
// namespaceMetrics returns a metric timeseries for a metric of the Namespace entity.
func (a *Api) namespaceMetrics(request *restful.Request, response *restful.Response)
// namespaceMetrics returns a metric timeseries for a metric of the Namespace entity. func (a *Api) namespaceMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricRequest(core.NamespaceKey(request.PathParameter("namespace-name")), request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L363-L368
go
train
// podMetrics returns a metric timeseries for a metric of the Pod entity.
func (a *Api) podMetrics(request *restful.Request, response *restful.Response)
// podMetrics returns a metric timeseries for a metric of the Pod entity. func (a *Api) podMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricRequest( core.PodKey(request.PathParameter("namespace-name"), request.PathParameter("pod-name")), request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L409-L416
go
train
// podContainerMetrics returns a metric timeseries for a metric of a Pod Container entity. // podContainerMetrics uses the namespace-name/pod-name/container-name path.
func (a *Api) podContainerMetrics(request *restful.Request, response *restful.Response)
// podContainerMetrics returns a metric timeseries for a metric of a Pod Container entity. // podContainerMetrics uses the namespace-name/pod-name/container-name path. func (a *Api) podContainerMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricRequest( core.PodContainerKey(request.PathParameter("namespace-name"), request.PathParameter("pod-name"), request.PathParameter("container-name"), ), request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L420-L426
go
train
// freeContainerMetrics returns a metric timeseries for a metric of the Container entity. // freeContainerMetrics addresses only free containers, by using the node-name/container-name path.
func (a *Api) freeContainerMetrics(request *restful.Request, response *restful.Response)
// freeContainerMetrics returns a metric timeseries for a metric of the Container entity. // freeContainerMetrics addresses only free containers, by using the node-name/container-name path. func (a *Api) freeContainerMetrics(request *restful.Request, response *restful.Response)
{ a.processMetricRequest( core.NodeContainerKey(request.PathParameter("node-name"), request.PathParameter("container-name"), ), request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/model_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/model_handlers.go#L429-L438
go
train
// parseRequestParam parses a time.Time from a named QueryParam, using the RFC3339 format.
func parseTimeParam(queryParam string, defaultValue time.Time) (time.Time, error)
// parseRequestParam parses a time.Time from a named QueryParam, using the RFC3339 format. func parseTimeParam(queryParam string, defaultValue time.Time) (time.Time, error)
{ if queryParam != "" { reqStamp, err := time.Parse(time.RFC3339, queryParam) if err != nil { return time.Time{}, fmt.Errorf("timestamp argument cannot be parsed: %s", err) } return reqStamp, nil } return defaultValue, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/riemann/driver.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/riemann/driver.go#L61-L85
go
train
// Receives a list of riemanngo.Event, the sink, and parameters. // Creates a new event using the parameters and the sink config, and add it into the Event list. // Can send events if events is full // Return the list.
func appendEvent(events []riemanngo.Event, sink *RiemannSink, host, name string, value interface{}, labels map[string]string, timestamp int64) []riemanngo.Event
// Receives a list of riemanngo.Event, the sink, and parameters. // Creates a new event using the parameters and the sink config, and add it into the Event list. // Can send events if events is full // Return the list. func appendEvent(events []riemanngo.Event, sink *RiemannSink, host, name string, value interface{}, labels map[string]string, timestamp int64) []riemanngo.Event
{ event := riemanngo.Event{ Time: timestamp, Service: name, Host: host, Description: "", Attributes: labels, Metric: value, Ttl: sink.config.Ttl, State: sink.config.State, Tags: sink.config.Tags, } // state everywhere events = append(events, event) if len(events) >= sink.config.BatchSize { err := riemannCommon.SendData(sink.client, events) if err != nil { glog.Warningf("Error sending events to Riemann: %v", err) // client will reconnect later sink.client = nil } events = nil } return events }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/sinks/riemann/driver.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/riemann/driver.go#L88-L137
go
train
// ExportData Send a collection of Timeseries to Riemann
func (sink *RiemannSink) ExportData(dataBatch *core.DataBatch)
// ExportData Send a collection of Timeseries to Riemann func (sink *RiemannSink) ExportData(dataBatch *core.DataBatch)
{ sink.Lock() defer sink.Unlock() if sink.client == nil { // the client could be nil here, so we reconnect client, err := riemannCommon.GetRiemannClient(sink.config) if err != nil { glog.Warningf("Riemann sink not connected: %v", err) return } sink.client = client } var events []riemanngo.Event for _, metricSet := range dataBatch.MetricSets { host := metricSet.Labels[core.LabelHostname.Key] for metricName, metricValue := range metricSet.MetricValues { if value := metricValue.GetValue(); value != nil { timestamp := dataBatch.Timestamp.Unix() // creates an event and add it to dataEvent events = appendEvent(events, sink, host, metricName, value, metricSet.Labels, timestamp) } } for _, metric := range metricSet.LabeledMetrics { if value := metric.GetValue(); value != nil { labels := make(map[string]string) for k, v := range metricSet.Labels { labels[k] = v } for k, v := range metric.Labels { labels[k] = v } timestamp := dataBatch.Timestamp.Unix() // creates an event and add it to dataEvent events = appendEvent(events, sink, host, metric.Name, value, labels, timestamp) } } } // Send events to Riemann if events is not empty if len(events) > 0 { err := riemannCommon.SendData(sink.client, events) if err != nil { glog.Warningf("Error sending events to Riemann: %v", err) // client will reconnect later sink.client = nil } } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L51-L199
go
train
// addAggregationRoutes adds routes to a webservice which point to a metricsAggregationFetcher's methods
func addAggregationRoutes(a metricsAggregationFetcher, ws *restful.WebService)
// addAggregationRoutes adds routes to a webservice which point to a metricsAggregationFetcher's methods func addAggregationRoutes(a metricsAggregationFetcher, ws *restful.WebService)
{ // The /metrics-aggregated/{aggregations}/{metric-name} endpoint exposes some aggregations for the Cluster entity of the historical API. ws.Route(ws.GET("/metrics-aggregated/{aggregations}/{metric-name:*}"). To(metrics.InstrumentRouteFunc("clusterMetrics", a.clusterAggregations)). Doc("Export some cluster-level metric aggregations"). Operation("clusterAggregations"). Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metric").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricAggregationResult{})) // The /nodes/{node-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes some aggregations for a Node entity of the historical API. // The {node-name} parameter is the hostname of a specific node. ws.Route(ws.GET("/nodes/{node-name}/metrics-aggregated/{aggregations}/{metric-name:*}"). To(metrics.InstrumentRouteFunc("nodeMetrics", a.nodeAggregations)). Doc("Export a node-level metric"). Operation("nodeAggregations"). Param(ws.PathParameter("node-name", "The name of the node to lookup").DataType("string")). Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metric").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricAggregationResult{})) if a.isRunningInKubernetes() { // The /namespaces/{namespace-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes some aggregations // for a Namespace entity of the historical API. ws.Route(ws.GET("/namespaces/{namespace-name}/metrics-aggregated/{aggregations}/{metric-name:*}"). To(metrics.InstrumentRouteFunc("namespaceMetrics", a.namespaceAggregations)). Doc("Export some namespace-level metric aggregations"). Operation("namespaceAggregations"). Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")). Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricAggregationResult{})) // The /namespaces/{namespace-name}/pods/{pod-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes // some aggregations for a Pod entity of the historical API. ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/metrics-aggregated/{aggregations}/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podMetrics", a.podAggregations)). Doc("Export some pod-level metric aggregations"). Operation("podAggregations"). Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")). Param(ws.PathParameter("pod-name", "The name of the pod to lookup").DataType("string")). Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricAggregationResult{})) // The /namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes // some aggregations for a Container entity of the historical API. ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podContainerMetrics", a.podContainerAggregations)). Doc("Export some aggregations for a Pod Container"). Operation("podContainerAggregations"). Param(ws.PathParameter("namespace-name", "The name of the namespace to use").DataType("string")). Param(ws.PathParameter("pod-name", "The name of the pod to use").DataType("string")). Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string")). Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricAggregationResult{})) // The /pod-id/{pod-id}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes // some aggregations for a Pod entity of the historical API. ws.Route(ws.GET("/pod-id/{pod-id}/metrics-aggregated/{aggregations}/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podMetrics", a.podAggregations)). Doc("Export some pod-level metric aggregations"). Operation("podAggregations"). Param(ws.PathParameter("pod-id", "The UID of the pod to lookup").DataType("string")). Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricAggregationResult{})) // The /pod-id/{pod-id}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes // some aggregations for a Container entity of the historical API. ws.Route(ws.GET("/pod-id/{pod-id}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podContainerMetrics", a.podContainerAggregations)). Doc("Export some aggregations for a Pod Container"). Operation("podContainerAggregations"). Param(ws.PathParameter("pod-id", "The name of the pod to use").DataType("string")). Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string")). Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricAggregationResult{})) } // The /nodes/{node-name}/freecontainers/{container-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes // some aggregations for a free Container entity of the historical API. ws.Route(ws.GET("/nodes/{node-name}/freecontainers/{container-name}/metrics-aggregated/{aggregations}/{metric-name:*}"). To(metrics.InstrumentRouteFunc("freeContainerMetrics", a.freeContainerAggregations)). Doc("Export a contsome iner-level metric aggregations for a free container"). Operation("freeContainerAggregations"). Param(ws.PathParameter("node-name", "The name of the node to use").DataType("string")). Param(ws.PathParameter("container-name", "The name of the container to use").DataType("string")). Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricAggregationResult{})) if a.isRunningInKubernetes() { // The /namespaces/{namespace-name}/pod-list/{pod-list}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes // metrics for a list of pods of the historical API. ws.Route(ws.GET("/namespaces/{namespace-name}/pod-list/{pod-list}/metrics-aggregated/{aggregations}/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podListAggregations", a.podListAggregations)). Doc("Export some aggregations for all pods from the given list"). Operation("podListAggregations"). Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")). Param(ws.PathParameter("pod-list", "Comma separated list of pod names to lookup").DataType("string")). Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricAggregationResultList{})) // The /pod-id-list/{pod-id-list}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes // metrics for a list of pod ids of the historical API. ws.Route(ws.GET("/pod-id-list/{pod-id-list}/metrics-aggregated/{aggregations}/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podListAggregations", a.podListAggregations)). Doc("Export an aggregation for all pods from the given list"). Operation("podListAggregations"). Param(ws.PathParameter("pod-id-list", "Comma separated list of pod UIDs to lookup").DataType("string")). Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")). Writes(types.MetricAggregationResultList{})) } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L204-L256
go
train
// RegisterHistorical registers the Historical API endpoints. It will register the same endpoints // as those in the model API, plus endpoints for aggregation retrieval, and endpoints to retrieve pod // metrics by using the pod id.
func (normalApi *Api) RegisterHistorical(container *restful.Container)
// RegisterHistorical registers the Historical API endpoints. It will register the same endpoints // as those in the model API, plus endpoints for aggregation retrieval, and endpoints to retrieve pod // metrics by using the pod id. func (normalApi *Api) RegisterHistorical(container *restful.Container)
{ ws := new(restful.WebService) ws.Path("/api/v1/historical"). Doc("Root endpoint of the historical access API"). Consumes("*/*"). Produces(restful.MIME_JSON) a := &HistoricalApi{normalApi} addClusterMetricsRoutes(a, ws) addAggregationRoutes(a, ws) // register the endpoint for fetching raw metrics based on pod id if a.isRunningInKubernetes() { // The /pod-id/{pod-id}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes // some aggregations for a Pod entity of the historical API. ws.Route(ws.GET("/pod-id/{pod-id}/metrics/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podMetrics", a.podMetrics)). Doc("Export some pod-level metric aggregations"). Operation("podAggregations"). Param(ws.PathParameter("pod-id", "The UID of the pod to lookup").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Writes(types.MetricResult{})) // The /pod-id/{pod-id}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes // some aggregations for a Container entity of the historical API. ws.Route(ws.GET("/pod-id/{pod-id}/containers/{container-name}/metrics/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podContainerMetrics", a.podContainerMetrics)). Doc("Export some aggregations for a Pod Container"). Operation("podContainerAggregations"). Param(ws.PathParameter("pod-id", "The uid of the pod to use").DataType("string")). Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Writes(types.MetricResult{})) // The /pod-id-list/{pod-id-list}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes // metrics for a list of pod ids of the historical API. ws.Route(ws.GET("/pod-id-list/{pod-id-list}/metrics/{metric-name:*}"). To(metrics.InstrumentRouteFunc("podListAggregations", a.podListMetrics)). Doc("Export an aggregation for all pods from the given list"). Operation("podListAggregations"). Param(ws.PathParameter("pod-id-list", "Comma separated list of pod UIDs to lookup").DataType("string")). Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")). Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")). Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")). Writes(types.MetricResultList{})) } container.Add(ws) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L259-L262
go
train
// availableClusterMetrics returns a list of available cluster metric names.
func (a *HistoricalApi) availableClusterMetrics(request *restful.Request, response *restful.Response)
// availableClusterMetrics returns a list of available cluster metric names. func (a *HistoricalApi) availableClusterMetrics(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ObjectType: core.MetricSetTypeCluster} a.processMetricNamesRequest(key, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L265-L271
go
train
// availableNodeMetrics returns a list of available node metric names.
func (a *HistoricalApi) availableNodeMetrics(request *restful.Request, response *restful.Response)
// availableNodeMetrics returns a list of available node metric names. func (a *HistoricalApi) availableNodeMetrics(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ ObjectType: core.MetricSetTypeNode, NodeName: request.PathParameter("node-name"), } a.processMetricNamesRequest(key, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L274-L280
go
train
// availableNamespaceMetrics returns a list of available namespace metric names.
func (a *HistoricalApi) availableNamespaceMetrics(request *restful.Request, response *restful.Response)
// availableNamespaceMetrics returns a list of available namespace metric names. func (a *HistoricalApi) availableNamespaceMetrics(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ ObjectType: core.MetricSetTypeNamespace, NamespaceName: request.PathParameter("namespace-name"), } a.processMetricNamesRequest(key, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L283-L290
go
train
// availablePodMetrics returns a list of available pod metric names.
func (a *HistoricalApi) availablePodMetrics(request *restful.Request, response *restful.Response)
// availablePodMetrics returns a list of available pod metric names. func (a *HistoricalApi) availablePodMetrics(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ ObjectType: core.MetricSetTypePod, NamespaceName: request.PathParameter("namespace-name"), PodName: request.PathParameter("pod-name"), } a.processMetricNamesRequest(key, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L293-L301
go
train
// availablePodContainerMetrics returns a list of available pod container metric names.
func (a *HistoricalApi) availablePodContainerMetrics(request *restful.Request, response *restful.Response)
// availablePodContainerMetrics returns a list of available pod container metric names. func (a *HistoricalApi) availablePodContainerMetrics(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ ObjectType: core.MetricSetTypePodContainer, NamespaceName: request.PathParameter("namespace-name"), PodName: request.PathParameter("pod-name"), ContainerName: request.PathParameter("container-name"), } a.processMetricNamesRequest(key, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L304-L311
go
train
// availableFreeContainerMetrics returns a list of available pod metric names.
func (a *HistoricalApi) availableFreeContainerMetrics(request *restful.Request, response *restful.Response)
// availableFreeContainerMetrics returns a list of available pod metric names. func (a *HistoricalApi) availableFreeContainerMetrics(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ ObjectType: core.MetricSetTypeSystemContainer, NodeName: request.PathParameter("node-name"), ContainerName: request.PathParameter("container-name"), } a.processMetricNamesRequest(key, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L314-L320
go
train
// nodeList lists all nodes for which we have metrics
func (a *HistoricalApi) nodeList(request *restful.Request, response *restful.Response)
// nodeList lists all nodes for which we have metrics func (a *HistoricalApi) nodeList(request *restful.Request, response *restful.Response)
{ if resp, err := a.historicalSource.GetNodes(); err != nil { response.WriteError(http.StatusInternalServerError, err) } else { response.WriteEntity(resp) } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L323-L329
go
train
// namespaceList lists all namespaces for which we have metrics
func (a *HistoricalApi) namespaceList(request *restful.Request, response *restful.Response)
// namespaceList lists all namespaces for which we have metrics func (a *HistoricalApi) namespaceList(request *restful.Request, response *restful.Response)
{ if resp, err := a.historicalSource.GetNamespaces(); err != nil { response.WriteError(http.StatusInternalServerError, err) } else { response.WriteEntity(resp) } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L332-L338
go
train
// namespacePodList lists all pods for which we have metrics in a particular namespace
func (a *HistoricalApi) namespacePodList(request *restful.Request, response *restful.Response)
// namespacePodList lists all pods for which we have metrics in a particular namespace func (a *HistoricalApi) namespacePodList(request *restful.Request, response *restful.Response)
{ if resp, err := a.historicalSource.GetPodsFromNamespace(request.PathParameter("namespace-name")); err != nil { response.WriteError(http.StatusInternalServerError, err) } else { response.WriteEntity(resp) } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L350-L353
go
train
// clusterMetrics returns a metric timeseries for a metric of the Cluster entity.
func (a *HistoricalApi) clusterMetrics(request *restful.Request, response *restful.Response)
// clusterMetrics returns a metric timeseries for a metric of the Cluster entity. func (a *HistoricalApi) clusterMetrics(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ObjectType: core.MetricSetTypeCluster} a.processMetricRequest(key, request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L356-L362
go
train
// nodeMetrics returns a metric timeseries for a metric of the Node entity.
func (a *HistoricalApi) nodeMetrics(request *restful.Request, response *restful.Response)
// nodeMetrics returns a metric timeseries for a metric of the Node entity. func (a *HistoricalApi) nodeMetrics(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ ObjectType: core.MetricSetTypeNode, NodeName: request.PathParameter("node-name"), } a.processMetricRequest(key, request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L365-L371
go
train
// namespaceMetrics returns a metric timeseries for a metric of the Namespace entity.
func (a *HistoricalApi) namespaceMetrics(request *restful.Request, response *restful.Response)
// namespaceMetrics returns a metric timeseries for a metric of the Namespace entity. func (a *HistoricalApi) namespaceMetrics(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ ObjectType: core.MetricSetTypeNamespace, NamespaceName: request.PathParameter("namespace-name"), } a.processMetricRequest(key, request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L374-L389
go
train
// podMetrics returns a metric timeseries for a metric of the Pod entity.
func (a *HistoricalApi) podMetrics(request *restful.Request, response *restful.Response)
// podMetrics returns a metric timeseries for a metric of the Pod entity. func (a *HistoricalApi) podMetrics(request *restful.Request, response *restful.Response)
{ var key core.HistoricalKey if request.PathParameter("pod-id") != "" { key = core.HistoricalKey{ ObjectType: core.MetricSetTypePod, PodId: request.PathParameter("pod-id"), } } else { key = core.HistoricalKey{ ObjectType: core.MetricSetTypePod, NamespaceName: request.PathParameter("namespace-name"), PodName: request.PathParameter("pod-name"), } } a.processMetricRequest(key, request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L393-L400
go
train
// freeContainerMetrics returns a metric timeseries for a metric of the Container entity. // freeContainerMetrics addresses only free containers.
func (a *HistoricalApi) freeContainerMetrics(request *restful.Request, response *restful.Response)
// freeContainerMetrics returns a metric timeseries for a metric of the Container entity. // freeContainerMetrics addresses only free containers. func (a *HistoricalApi) freeContainerMetrics(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ ObjectType: core.MetricSetTypeSystemContainer, NodeName: request.PathParameter("node-name"), ContainerName: request.PathParameter("container-name"), } a.processMetricRequest(key, request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L403-L459
go
train
// podListMetrics returns a list of metric timeseries for each for the listed nodes
func (a *HistoricalApi) podListMetrics(request *restful.Request, response *restful.Response)
// podListMetrics returns a list of metric timeseries for each for the listed nodes func (a *HistoricalApi) podListMetrics(request *restful.Request, response *restful.Response)
{ start, end, err := getStartEndTimeHistorical(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } keys := []core.HistoricalKey{} if request.PathParameter("pod-id-list") != "" { for _, podId := range strings.Split(request.PathParameter("pod-id-list"), ",") { key := core.HistoricalKey{ ObjectType: core.MetricSetTypePod, PodId: podId, } keys = append(keys, key) } } else { for _, podName := range strings.Split(request.PathParameter("pod-list"), ",") { key := core.HistoricalKey{ ObjectType: core.MetricSetTypePod, NamespaceName: request.PathParameter("namespace-name"), PodName: podName, } keys = append(keys, key) } } labels, err := getLabels(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } metricName := request.PathParameter("metric-name") convertedMetricName := convertMetricName(metricName) var metrics map[core.HistoricalKey][]core.TimestampedMetricValue if labels != nil { metrics, err = a.historicalSource.GetLabeledMetric(convertedMetricName, labels, keys, start, end) } else { metrics, err = a.historicalSource.GetMetric(convertedMetricName, keys, start, end) } if err != nil { response.WriteError(http.StatusInternalServerError, err) return } result := types.MetricResultList{ Items: make([]types.MetricResult, 0, len(keys)), } for _, key := range keys { result.Items = append(result.Items, exportTimestampedMetricValue(metrics[key])) } response.PrettyPrint(false) response.WriteEntity(result) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L482-L485
go
train
// clusterAggregations returns a metric timeseries for a metric of the Cluster entity.
func (a *HistoricalApi) clusterAggregations(request *restful.Request, response *restful.Response)
// clusterAggregations returns a metric timeseries for a metric of the Cluster entity. func (a *HistoricalApi) clusterAggregations(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ObjectType: core.MetricSetTypeCluster} a.processAggregationRequest(key, request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L488-L494
go
train
// nodeAggregations returns a metric timeseries for a metric of the Node entity.
func (a *HistoricalApi) nodeAggregations(request *restful.Request, response *restful.Response)
// nodeAggregations returns a metric timeseries for a metric of the Node entity. func (a *HistoricalApi) nodeAggregations(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ ObjectType: core.MetricSetTypeNode, NodeName: request.PathParameter("node-name"), } a.processAggregationRequest(key, request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L497-L503
go
train
// namespaceAggregations returns a metric timeseries for a metric of the Namespace entity.
func (a *HistoricalApi) namespaceAggregations(request *restful.Request, response *restful.Response)
// namespaceAggregations returns a metric timeseries for a metric of the Namespace entity. func (a *HistoricalApi) namespaceAggregations(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ ObjectType: core.MetricSetTypeNamespace, NamespaceName: request.PathParameter("namespace-name"), } a.processAggregationRequest(key, request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L524-L541
go
train
// podContainerAggregations returns a metric timeseries for a metric of a Pod Container entity.
func (a *HistoricalApi) podContainerAggregations(request *restful.Request, response *restful.Response)
// podContainerAggregations returns a metric timeseries for a metric of a Pod Container entity. func (a *HistoricalApi) podContainerAggregations(request *restful.Request, response *restful.Response)
{ var key core.HistoricalKey if request.PathParameter("pod-id") != "" { key = core.HistoricalKey{ ObjectType: core.MetricSetTypePodContainer, PodId: request.PathParameter("pod-id"), ContainerName: request.PathParameter("container-name"), } } else { key = core.HistoricalKey{ ObjectType: core.MetricSetTypePodContainer, NamespaceName: request.PathParameter("namespace-name"), PodName: request.PathParameter("pod-name"), ContainerName: request.PathParameter("container-name"), } } a.processAggregationRequest(key, request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L545-L552
go
train
// freeContainerAggregations returns a metric timeseries for a metric of the Container entity. // freeContainerAggregations addresses only free containers.
func (a *HistoricalApi) freeContainerAggregations(request *restful.Request, response *restful.Response)
// freeContainerAggregations returns a metric timeseries for a metric of the Container entity. // freeContainerAggregations addresses only free containers. func (a *HistoricalApi) freeContainerAggregations(request *restful.Request, response *restful.Response)
{ key := core.HistoricalKey{ ObjectType: core.MetricSetTypeSystemContainer, NodeName: request.PathParameter("node-name"), ContainerName: request.PathParameter("container-name"), } a.processAggregationRequest(key, request, response) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L555-L616
go
train
// podListAggregations returns a list of metric timeseries for the specified pods.
func (a *HistoricalApi) podListAggregations(request *restful.Request, response *restful.Response)
// podListAggregations returns a list of metric timeseries for the specified pods. func (a *HistoricalApi) podListAggregations(request *restful.Request, response *restful.Response)
{ start, end, err := getStartEndTimeHistorical(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } bucketSize, err := getBucketSize(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } aggregations, err := getAggregations(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } labels, err := getLabels(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } keys := []core.HistoricalKey{} if request.PathParameter("pod-id-list") != "" { for _, podId := range strings.Split(request.PathParameter("pod-id-list"), ",") { key := core.HistoricalKey{ ObjectType: core.MetricSetTypePod, PodId: podId, } keys = append(keys, key) } } else { for _, podName := range strings.Split(request.PathParameter("pod-list"), ",") { key := core.HistoricalKey{ ObjectType: core.MetricSetTypePod, NamespaceName: request.PathParameter("namespace-name"), PodName: podName, } keys = append(keys, key) } } metricName := request.PathParameter("metric-name") convertedMetricName := convertMetricName(metricName) var metrics map[core.HistoricalKey][]core.TimestampedAggregationValue if labels != nil { metrics, err = a.historicalSource.GetLabeledAggregation(convertedMetricName, labels, aggregations, keys, start, end, bucketSize) } else { metrics, err = a.historicalSource.GetAggregation(convertedMetricName, aggregations, keys, start, end, bucketSize) } if err != nil { response.WriteError(http.StatusInternalServerError, err) return } result := types.MetricAggregationResultList{ Items: make([]types.MetricAggregationResult, 0, len(keys)), } for _, key := range keys { result.Items = append(result.Items, exportTimestampedAggregationValue(metrics[key])) } response.PrettyPrint(false) response.WriteEntity(result) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L619-L646
go
train
// processMetricRequest retrieves a metric for the object at the requested key.
func (a *HistoricalApi) processMetricRequest(key core.HistoricalKey, request *restful.Request, response *restful.Response)
// processMetricRequest retrieves a metric for the object at the requested key. func (a *HistoricalApi) processMetricRequest(key core.HistoricalKey, request *restful.Request, response *restful.Response)
{ start, end, err := getStartEndTimeHistorical(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } labels, err := getLabels(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } metricName := request.PathParameter("metric-name") convertedMetricName := convertMetricName(metricName) var metrics map[core.HistoricalKey][]core.TimestampedMetricValue if labels != nil { metrics, err = a.historicalSource.GetLabeledMetric(convertedMetricName, labels, []core.HistoricalKey{key}, start, end) } else { metrics, err = a.historicalSource.GetMetric(convertedMetricName, []core.HistoricalKey{key}, start, end) } if err != nil { response.WriteError(http.StatusInternalServerError, err) return } converted := exportTimestampedMetricValue(metrics[key]) response.WriteEntity(converted) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L649-L655
go
train
// processMetricNamesRequest retrieves the available metrics for the object at the specified key.
func (a *HistoricalApi) processMetricNamesRequest(key core.HistoricalKey, response *restful.Response)
// processMetricNamesRequest retrieves the available metrics for the object at the specified key. func (a *HistoricalApi) processMetricNamesRequest(key core.HistoricalKey, response *restful.Response)
{ if resp, err := a.historicalSource.GetMetricNames(key); err != nil { response.WriteError(http.StatusInternalServerError, err) } else { response.WriteEntity(resp) } }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L658-L695
go
train
// processAggregationRequest retrieves one or more aggregations (across time) of a metric for the object specified at the given key.
func (a *HistoricalApi) processAggregationRequest(key core.HistoricalKey, request *restful.Request, response *restful.Response)
// processAggregationRequest retrieves one or more aggregations (across time) of a metric for the object specified at the given key. func (a *HistoricalApi) processAggregationRequest(key core.HistoricalKey, request *restful.Request, response *restful.Response)
{ start, end, err := getStartEndTimeHistorical(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } bucketSize, err := getBucketSize(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } aggregations, err := getAggregations(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } labels, err := getLabels(request) if err != nil { response.WriteError(http.StatusBadRequest, err) return } metricName := request.PathParameter("metric-name") convertedMetricName := convertMetricName(metricName) var metrics map[core.HistoricalKey][]core.TimestampedAggregationValue if labels != nil { metrics, err = a.historicalSource.GetLabeledAggregation(convertedMetricName, labels, aggregations, []core.HistoricalKey{key}, start, end, bucketSize) } else { metrics, err = a.historicalSource.GetAggregation(convertedMetricName, aggregations, []core.HistoricalKey{key}, start, end, bucketSize) } if err != nil { response.WriteError(http.StatusInternalServerError, err) return } converted := exportTimestampedAggregationValue(metrics[key]) response.WriteEntity(converted) }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L698-L739
go
train
// getBucketSize parses the bucket size specifier into a
func getBucketSize(request *restful.Request) (time.Duration, error)
// getBucketSize parses the bucket size specifier into a func getBucketSize(request *restful.Request) (time.Duration, error)
{ rawSize := request.QueryParameter("bucket") if rawSize == "" { return 0, nil } if len(rawSize) < 2 { return 0, fmt.Errorf("unable to parse bucket size: %q is too short to be a duration", rawSize) } var multiplier time.Duration var num string switch rawSize[len(rawSize)-1] { case 's': // could be s or ms if len(rawSize) < 3 || rawSize[len(rawSize)-2] != 'm' { multiplier = time.Second num = rawSize[:len(rawSize)-1] } else { multiplier = time.Millisecond num = rawSize[:len(rawSize)-2] } case 'h': multiplier = time.Hour num = rawSize[:len(rawSize)-1] case 'd': multiplier = 24 * time.Hour num = rawSize[:len(rawSize)-1] case 'm': multiplier = time.Minute num = rawSize[:len(rawSize)-1] default: return 0, fmt.Errorf("unable to parse bucket size: %q has no known duration suffix", rawSize) } parsedNum, err := strconv.ParseUint(num, 10, 64) if err != nil { return 0, err } return time.Duration(parsedNum) * multiplier, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L742-L759
go
train
// getAggregations extracts and validates the list of requested aggregations
func getAggregations(request *restful.Request) ([]core.AggregationType, error)
// getAggregations extracts and validates the list of requested aggregations func getAggregations(request *restful.Request) ([]core.AggregationType, error)
{ aggregationsRaw := strings.Split(request.PathParameter("aggregations"), ",") if len(aggregationsRaw) == 0 { return nil, fmt.Errorf("No aggregations specified") } aggregations := make([]core.AggregationType, len(aggregationsRaw)) for ind, aggNameRaw := range aggregationsRaw { aggName := core.AggregationType(aggNameRaw) if _, ok := core.AllAggregations[aggName]; !ok { return nil, fmt.Errorf("Unknown aggregation %q", aggName) } aggregations[ind] = aggName } return aggregations, nil }
kubernetes-retired/heapster
e1e83412787b60d8a70088f09a2cb12339b305c3
metrics/api/v1/historical_handlers.go
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/api/v1/historical_handlers.go#L762-L777
go
train
// exportMetricValue converts a core.MetricValue into an API MetricValue
func exportMetricValue(value *core.MetricValue) *types.MetricValue
// exportMetricValue converts a core.MetricValue into an API MetricValue func exportMetricValue(value *core.MetricValue) *types.MetricValue
{ if value == nil { return nil } if value.ValueType == core.ValueInt64 { return &types.MetricValue{ IntValue: &value.IntValue, } } else { floatVal := float64(value.FloatValue) return &types.MetricValue{ FloatValue: &floatVal, } } }