Skip to content

Commit

Permalink
Merge pull request #41 from wanghaoran1988/add_group
Browse files Browse the repository at this point in the history
Add collector for group
  • Loading branch information
openshift-merge-robot committed Sep 18, 2019
2 parents 4e6b118 + daccd44 commit c01d2de
Show file tree
Hide file tree
Showing 27 changed files with 3,547 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/README.md
Expand Up @@ -29,6 +29,7 @@ Per group of metrics there is one file for each metrics. See each file for speci
- [DeploymentConfig Metrics](deploymentconfig-metrics.md)
- [ClusterResourceQuota Metrics](clusterresourcequota-metrics.md)
- [Route Metrics](route-metrics.md)
- [Group Metrics](group-metrics.md)

## CLI Arguments

Expand Down
6 changes: 6 additions & 0 deletions docs/group-metrics.md
@@ -0,0 +1,6 @@
# Group Metrics

| Metric name| Metric type | Labels/tags | Status |
| ---------- | ----------- | ----------- | ----------- |
| openshift_group_created | Gauge | `group`=<group-name>| STABLE |
| openshift_group_user_account | Gauge | `group`=<group-name> | STABLE |
9 changes: 8 additions & 1 deletion jsonnet/openshift-state-metrics.libsonnet
Expand Up @@ -102,6 +102,13 @@ local k = import 'ksonnet/ksonnet.beta.4/k.libsonnet';
]) +
rulesType.withVerbs(['list', 'watch']);

local groupRule = rulesType.new() +
rulesType.withApiGroups(['user.openshift.io']) +
rulesType.withResources([
'groups',
]) +
rulesType.withVerbs(['list', 'watch']);

local authenticationRole = rulesType.new() +
rulesType.withApiGroups(['authentication.k8s.io']) +
rulesType.withResources([
Expand All @@ -116,7 +123,7 @@ local k = import 'ksonnet/ksonnet.beta.4/k.libsonnet';
]) +
rulesType.withVerbs(['create']);

local rules = [appsRule, buildRule, quotaRule, routeRule, authenticationRole, authorizationRole];
local rules = [appsRule, buildRule, quotaRule, routeRule, groupRule, authenticationRole, authorizationRole];

clusterRole.new() +
clusterRole.mixin.metadata.withName('openshift-state-metrics') +
Expand Down
7 changes: 7 additions & 0 deletions manifests/openshift-state-metrics-cluster-role.yaml
Expand Up @@ -32,6 +32,13 @@ rules:
verbs:
- list
- watch
- apiGroups:
- user.openshift.io
resources:
- groups
verbs:
- list
- watch
- apiGroups:
- authentication.k8s.io
resources:
Expand Down
18 changes: 18 additions & 0 deletions pkg/collectors/builder.go
Expand Up @@ -16,6 +16,7 @@ import (
buildv1 "github.com/openshift/api/build/v1"
quotav1 "github.com/openshift/api/quota/v1"
routev1 "github.com/openshift/api/route/v1"
userv1 "github.com/openshift/api/user/v1"
"golang.org/x/net/context"
)

Expand Down Expand Up @@ -112,6 +113,7 @@ var availableCollectors = map[string]func(f *Builder) *collector.Collector{
"builds": func(b *Builder) *collector.Collector { return b.buildBuildCollector() },
"clusterresourcequotas": func(b *Builder) *collector.Collector { return b.buildQuotaCollector() },
"routes": func(b *Builder) *collector.Collector { return b.buildRouteCollector() },
"groups": func(b *Builder) *collector.Collector { return b.buildGroupCollector() },
}

func (b *Builder) buildRouteCollector() *collector.Collector {
Expand Down Expand Up @@ -194,6 +196,22 @@ func (b *Builder) buildQuotaCollector() *collector.Collector {
return collector.NewCollector(store)
}

func (b *Builder) buildGroupCollector() *collector.Collector {
filteredMetricFamilies := metric.FilterMetricFamilies(b.whiteBlackList, groupMetricFamilies)
composedMetricGenFuncs := metric.ComposeMetricGenFuncs(filteredMetricFamilies)

familyHeaders := metric.ExtractMetricFamilyHeaders(filteredMetricFamilies)

store := metricsstore.NewMetricsStore(
familyHeaders,
composedMetricGenFuncs,
)
reflectorPerNamespace(b.ctx, &userv1.Group{}, store,
b.apiserver, b.kubeconfig, b.namespaces, createGroupListWatch)

return collector.NewCollector(store)
}

// reflectorPerNamespace creates a Kubernetes client-go reflector with the given
// listWatchFunc for each given namespace and registers it with the given store.
func reflectorPerNamespace(
Expand Down
105 changes: 105 additions & 0 deletions pkg/collectors/group.go
@@ -0,0 +1,105 @@
package collectors

import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/kube-state-metrics/pkg/metric"
"k8s.io/kube-state-metrics/pkg/version"

"github.com/golang/glog"

"github.com/openshift/api/user/v1"
groupclient "github.com/openshift/client-go/user/clientset/versioned"
)

var (
descGroupLabelsName = "openshift_group_labels"
descGroupLabelsHelp = "Kubernetes labels converted to Prometheus labels."
descGroupLabelsDefaultLabels = []string{"group"}

groupMetricFamilies = []metric.FamilyGenerator{
metric.FamilyGenerator{
Name: "openshift_group_created",
Type: metric.MetricTypeGauge,
Help: "Unix creation timestamp",
GenerateFunc: wrapGroupFunc(func(d *v1.Group) metric.Family {
f := metric.Family{}

if !d.CreationTimestamp.IsZero() {
f.Metrics = append(f.Metrics, &metric.Metric{
Value: float64(d.CreationTimestamp.Unix()),
})
}

return f
}),
},
metric.FamilyGenerator{
Name: "openshift_group_user_account",
Type: metric.MetricTypeGauge,
Help: "User account in a group.",
GenerateFunc: wrapGroupFunc(func(d *v1.Group) metric.Family {
f := metric.Family{}
if len(d.Users) > 0 {
for _, user := range d.Users {
f.Metrics = append(f.Metrics, &metric.Metric{
LabelKeys: []string{"user"},
LabelValues: []string{user},
Value: 1,
})
}

}
return f
}),
},
}
)

func wrapGroupFunc(f func(group *v1.Group) metric.Family) func(interface{}) metric.Family {
return func(obj interface{}) metric.Family {
group := obj.(*v1.Group)

metricFamily := f(group)

for _, m := range metricFamily.Metrics {
m.LabelKeys = append(descGroupLabelsDefaultLabels, m.LabelKeys...)
m.LabelValues = append([]string{group.Name}, m.LabelValues...)
}

return metricFamily
}
}

func createGroupListWatch(apiserver string, kubeconfig string, ns string) cache.ListWatch {
groupclient, err := createGroupClient(apiserver, kubeconfig)
if err != nil {
glog.Fatalf("cannot create Group client: %v", err)
}
return cache.ListWatch{
ListFunc: func(opts metav1.ListOptions) (runtime.Object, error) {
return groupclient.UserV1().Groups().List(opts)
},
WatchFunc: func(opts metav1.ListOptions) (watch.Interface, error) {
return groupclient.UserV1().Groups().Watch(opts)
},
}
}

func createGroupClient(apiserver string, kubeconfig string) (*groupclient.Clientset, error) {
config, err := clientcmd.BuildConfigFromFlags(apiserver, kubeconfig)
if err != nil {
return nil, err
}

config.UserAgent = version.GetVersion().String()
config.AcceptContentTypes = "application/vnd.kubernetes.protobuf,application/json"
config.ContentType = "application/vnd.kubernetes.protobuf"

client, err := groupclient.NewForConfig(config)
return client, err

}
44 changes: 44 additions & 0 deletions pkg/collectors/group_test.go
@@ -0,0 +1,44 @@
package collectors

import (
"testing"
"time"

"github.com/openshift/api/user/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kube-state-metrics/pkg/metric"
)

func TestGroupCollector(t *testing.T) {
// Fixed metadata on type and help text. We prepend this to every expected
// output so we only have to modify a single place when doing adjustments.
const metadata = `
# HELP openshift_group_created Unix creation timestamp
# TYPE openshift_group_created gauge
# HELP openshift_group_user_account User account in a group.
# TYPE openshift_group_user_account gauge
`
cases := []generateMetricsTestCase{
{
Obj: &v1.Group{
ObjectMeta: metav1.ObjectMeta{
Name: "group",
CreationTimestamp: metav1.Time{Time: time.Unix(1500000000, 0)},
},
Users: []string{"user1"},
},
Want: `
openshift_group_created{group="group"} 1.5e+09
openshift_group_user_account{group="group",user="user1"} 1
`,
MetricNames: []string{"openshift_group_created", "openshift_group_user_account"},
},
}

for i, c := range cases {
c.Func = metric.ComposeMetricGenFuncs(groupMetricFamilies)
if err := c.run(); err != nil {
t.Errorf("unexpected collecting result in %vth run:\n%s", i, err)
}
}
}
2 changes: 2 additions & 0 deletions pkg/options/collector.go
Expand Up @@ -13,6 +13,7 @@ func init() {
koptions.DefaultCollectors["builds"] = struct{}{}
koptions.DefaultCollectors["clusterresourcequotas"] = struct{}{}
koptions.DefaultCollectors["routes"] = struct{}{}
koptions.DefaultCollectors["groups"] = struct{}{}
}

var (
Expand All @@ -23,5 +24,6 @@ var (
"builds": struct{}{},
"clusterresourcequotas": struct{}{},
"routes": struct{}{},
"groups": struct{}{},
}
)
8 changes: 8 additions & 0 deletions vendor/github.com/openshift/api/user/v1/doc.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit c01d2de

Please sign in to comment.