github.com/timstclair/heapster@v0.20.0-alpha1/metrics/processors/namespace_based_enricher.go (about) 1 // Copyright 2015 Google Inc. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package processors 16 17 import ( 18 "net/url" 19 "time" 20 21 "github.com/golang/glog" 22 23 kube_config "k8s.io/heapster/common/kubernetes" 24 "k8s.io/heapster/metrics/core" 25 kube_api "k8s.io/kubernetes/pkg/api" 26 "k8s.io/kubernetes/pkg/client/cache" 27 kube_client "k8s.io/kubernetes/pkg/client/unversioned" 28 "k8s.io/kubernetes/pkg/fields" 29 ) 30 31 type NamespaceBasedEnricher struct { 32 store cache.Store 33 reflector *cache.Reflector 34 } 35 36 func (this *NamespaceBasedEnricher) Name() string { 37 return "namespace_based_enricher" 38 } 39 40 func (this *NamespaceBasedEnricher) Process(batch *core.DataBatch) (*core.DataBatch, error) { 41 for _, ms := range batch.MetricSets { 42 this.addNamespaceInfo(ms) 43 } 44 return batch, nil 45 } 46 47 // Adds UID to all namespaced elements. 48 func (this *NamespaceBasedEnricher) addNamespaceInfo(metricSet *core.MetricSet) { 49 if metricSetType, found := metricSet.Labels[core.LabelMetricSetType.Key]; found && 50 (metricSetType == core.MetricSetTypePodContainer || 51 metricSetType == core.MetricSetTypePod || 52 metricSetType == core.MetricSetTypeNamespace) { 53 54 if namespaceName, found := metricSet.Labels[core.LabelNamespaceName.Key]; found { 55 nsObj, exists, err := this.store.GetByKey(namespaceName) 56 if exists && err == nil { 57 namespace, ok := nsObj.(*kube_api.Namespace) 58 if ok { 59 metricSet.Labels[core.LabelPodNamespaceUID.Key] = string(namespace.UID) 60 } else { 61 glog.Errorf("Wrong namespace store content") 62 } 63 } else { 64 glog.Warningf("Failed to get namespace: exist: %s error: %v", exists, err) 65 } 66 } 67 } 68 } 69 70 func NewNamespaceBasedEnricher(url *url.URL) (*NamespaceBasedEnricher, error) { 71 kubeConfig, err := kube_config.GetKubeClientConfig(url) 72 if err != nil { 73 return nil, err 74 } 75 kubeClient := kube_client.NewOrDie(kubeConfig) 76 77 // watch nodes 78 lw := cache.NewListWatchFromClient(kubeClient, "namespaces", kube_api.NamespaceAll, fields.Everything()) 79 store := cache.NewStore(cache.MetaNamespaceKeyFunc) 80 reflector := cache.NewReflector(lw, &kube_api.Namespace{}, store, time.Hour) 81 reflector.Run() 82 83 return &NamespaceBasedEnricher{ 84 store: store, 85 reflector: reflector, 86 }, nil 87 }