This repository has been archived by the owner on May 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
393 lines (321 loc) · 11.8 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
//"compress/gzip"
//"context"
//"io"
"net"
"strconv"
"fmt"
"log"
"net/http"
"net/http/pprof"
"os"
"strings"
"github.com/golang/glog"
"github.com/openshift/origin/pkg/util/proc"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/tools/clientcmd"
/*kcollectors "k8s.io/kube-state-metrics/pkg/collectors"*/
/*"k8s.io/kube-state-metrics/pkg/options"
"k8s.io/kube-state-metrics/pkg/version"
"k8s.io/kube-state-metrics/pkg/whiteblacklist"
*/
"sort"
"k8s.io/client-go/rest"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kubeclientset "k8s.io/client-go/kubernetes"
/*clientset "github.com/openshift/client-go/quota/clientset/versioned"*/
/*oapiclientset "github.com/openshift/client-go"*/
)
const (
metricsPath = "/metrics"
healthzPath = "/healthz"
)
var (
defaultCollectors = collectorSet{
}
availableCollectors = map[string]func(registry prometheus.Registerer, kubeClient kubeclientset.Interface, namespace string){
}
defaultCollectorsOApi = collectorSet{
"appliedclusterresourcequotas": struct{}{},
"clusterresourcequotas": struct{}{},
"deploymentconfigs": struct{}{},
}
availableCollectorsOApi = map[string]func(registry prometheus.Registerer, kubeConfig *rest.Config, namespace string){
"appliedclusterresourcequotas": RegisterAppliedClusterResourceQuotaCollectorOApi,
"clusterresourcequotas": RegisterClusterResourceQuotaCollectorOApi,
"deploymentconfigs": RegisterDeploymentConfigCollectorOApi,
}
ScrapeErrorTotalMetric = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "oapi_scrape_error_total",
Help: "Total scrape errors encountered when scraping a resource",
},
[]string{"resource"},
)
ResourcesPerScrapeMetric = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "oapi_resources_per_scrape",
Help: "Number of resources returned per scrape",
},
[]string{"resource"},
)
ScrapeDurationHistogram = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "oapi_durations_per_scrape",
Help: "During distribution of per metric collector",
Buckets: []float64{1, 2, 5, 10, 20, 60},
},
[]string{"resource"},
)
)
type collectorSet map[string]struct{}
func (c *collectorSet) String() string {
s := *c
ss := s.asSlice()
sort.Strings(ss)
return strings.Join(ss, ",")
}
func (c *collectorSet) Set(value string) error {
s := *c
cols := strings.Split(value, ",")
for _, col := range cols {
_, ok1 := availableCollectors[col]
_, ok2 := availableCollectorsOApi[col]
if !(ok1 || ok2) {
glog.Fatalf("Collector \"%s\" does not exist", col)
}
s[col] = struct{}{}
}
return nil
}
func (c collectorSet) asSlice() []string {
cols := []string{}
for col, _ := range c {
cols = append(cols, col)
}
return cols
}
func (c collectorSet) isEmpty() bool {
return len(c.asSlice()) == 0
}
func (c *collectorSet) Type() string {
return "string"
}
func main() {
opts := NewOptions()
opts.AddFlags()
err := opts.Parse()
if err != nil {
glog.Fatalf("Error: %s", err)
}
if opts.Version {
fmt.Printf("%#v\n", GetVersion())
os.Exit(0)
}
if opts.Help {
opts.Usage()
os.Exit(0)
}
var collectors collectorSet
if len(opts.Collectors) == 0 {
glog.Info("Using default collectors")
collectors = defaultCollectorsOApi
} else {
collectors = opts.Collectors
}
if opts.Namespace == metav1.NamespaceAll {
glog.Info("Using all namespace")
} else {
glog.Infof("Using %s namespace", opts.Namespace)
}
/*if isNotExists(opts.Kubeconfig) {
glog.Fatalf("kubeconfig invalid and --in-cluster is false; kubeconfig must be set to a valid file(kubeconfig default file name: $HOME/.kube/config)")
}
if opts.Apiserver != "" {
glog.Infof("apiserver set to: %v", opts.Apiserver)
}
*/
proc.StartReaper()
/* kubeClientConfig, err := createOApiClient(opts.inCluster, opts.apiserver, opts.kubeconfig) */
kubeClient, err := createKubeClient(opts.Apiserver, opts.Kubeconfig)
if err != nil {
glog.Fatalf("Failed to create client: %v", err)
}
kubeClientConfig, err := createKubeConfig(opts.Apiserver, opts.Kubeconfig)
if err != nil {
glog.Fatalf("Failed to create Kube Config: %v", err)
}
/* TODO: update Scrape metrics! */
telemetryMetricsRegistry := prometheus.NewRegistry()
telemetryMetricsRegistry.Register(ResourcesPerScrapeMetric)
telemetryMetricsRegistry.Register(ScrapeErrorTotalMetric)
telemetryMetricsRegistry.Register(ScrapeDurationHistogram)
telemetryMetricsRegistry.Register(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
telemetryMetricsRegistry.Register(prometheus.NewGoCollector())
go telemetryServer(telemetryMetricsRegistry, opts.TelemetryHost, opts.TelemetryPort)
registry := prometheus.NewRegistry()
registerCollectorsOApi(registry, kubeClientConfig, collectors, opts.Namespace)
registerCollectors(registry, kubeClient, collectors, opts.Namespace)
metricsServer(registry, opts.Port)
}
func isNotExists(file string) bool {
if file == "" {
file = clientcmd.NewDefaultClientConfigLoadingRules().GetDefaultFilename()
}
_, err := os.Stat(file)
return os.IsNotExist(err)
}
/* createKubeConfig: create rest.Config as base for creation clientsets
Note: OAPI only provides very specifiy clientsets,
the specify clients are created in the object collectors Register... method */
func createKubeConfig(apiserver string, kubeconfig string) (config *rest.Config, err error) {
config, err = clientcmd.BuildConfigFromFlags(apiserver, kubeconfig)
if err != nil {
return nil, err
}
config.UserAgent = GetVersion().String()
config.AcceptContentTypes = "application/vnd.kubernetes.protobuf,application/json"
config.ContentType = "application/vnd.kubernetes.protobuf"
kubeClient, err := kubeclientset.NewForConfig(config)
if err != nil {
return nil, err
}
// Informers don't seem to do a good job logging error messages when it
// can't reach the server, making debugging hard. This makes it easier to
// figure out if apiserver is configured incorrectly.
glog.Infof("Testing communication with server")
v, err := kubeClient.Discovery().ServerVersion()
if err != nil {
return nil, fmt.Errorf("ERROR communicating with apiserver: %v", err)
}
glog.Infof("Running with Kubernetes cluster version: v%s.%s. git version: %s. git tree state: %s. commit: %s. platform: %s",
v.Major, v.Minor, v.GitVersion, v.GitTreeState, v.GitCommit, v.Platform)
glog.Infof("Communication with server successful")
return config, nil
}
/* createKubeClient: create generic client for Kubernetes API*/
func createKubeClient(apiserver string, kubeconfig string) (kubeclientset.Interface, error) {
config, err := clientcmd.BuildConfigFromFlags(apiserver, kubeconfig)
if err != nil {
return nil, err
}
config.UserAgent = GetVersion().String()
config.AcceptContentTypes = "application/vnd.kubernetes.protobuf,application/json"
config.ContentType = "application/vnd.kubernetes.protobuf"
kubeClient, err := kubeclientset.NewForConfig(config)
if err != nil {
return nil, err
}
// Informers don't seem to do a good job logging error messages when it
// can't reach the server, making debugging hard. This makes it easier to
// figure out if apiserver is configured incorrectly.
glog.Infof("Testing communication with server")
v, err := kubeClient.Discovery().ServerVersion()
if err != nil {
return nil, fmt.Errorf("ERROR communicating with apiserver: %v", err)
}
glog.Infof("Running with Kubernetes cluster version: v%s.%s. git version: %s. git tree state: %s. commit: %s. platform: %s",
v.Major, v.Minor, v.GitVersion, v.GitTreeState, v.GitCommit, v.Platform)
glog.Infof("Communication with server successful")
return kubeClient, nil
}
func metricsServer(registry prometheus.Gatherer, port int) {
// Address to listen on for web interface and telemetry
listenAddress := fmt.Sprintf(":%d", port)
glog.Infof("Starting metrics server: %s", listenAddress)
mux := http.NewServeMux()
mux.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
mux.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
// Add metricsPath
mux.Handle(metricsPath, promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
// Add healthzPath
mux.HandleFunc(healthzPath, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("ok"))
})
// Add index
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Kube Metrics Server</title></head>
<body>
<h1>Kube Metrics</h1>
<ul>
<li><a href='` + metricsPath + `'>metrics</a></li>
<li><a href='` + healthzPath + `'>healthz</a></li>
</ul>
</body>
</html>`))
})
log.Fatal(http.ListenAndServe(listenAddress, mux))
}
func telemetryServer(registry prometheus.Gatherer, host string, port int) {
// Address to listen on for web interface and telemetry
listenAddress := net.JoinHostPort(host, strconv.Itoa(port))
glog.Infof("Starting kube-state-metrics self metrics server: %s", listenAddress)
mux := http.NewServeMux()
// Add metricsPath
mux.Handle(metricsPath, promhttp.HandlerFor(registry, promhttp.HandlerOpts{ErrorLog: promLogger{}}))
// Add index
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Kube-State-Metrics Metrics Server</title></head>
<body>
<h1>Kube-State-Metrics Metrics</h1>
<ul>
<li><a href='` + metricsPath + `'>metrics</a></li>
</ul>
</body>
</html>`))
})
log.Fatal(http.ListenAndServe(listenAddress, mux))
}
// promLogger implements promhttp.Logger
type promLogger struct{}
func (pl promLogger) Println(v ...interface{}) {
glog.Error(v...)
}
// registerCollectorsOApi creates specific OAPI Clients sets and starts informers if watch is supported
// otherwise the data is collected on demand in the Collect method of the object collector
// and initializes and registers metrics for collection.
func registerCollectorsOApi(registry prometheus.Registerer, kubeConfig *rest.Config, enabledCollectors collectorSet, namespace string) {
activeCollectors := []string{}
for c, _ := range enabledCollectors {
f, ok := availableCollectorsOApi[c]
if ok {
f(registry, kubeConfig, namespace)
activeCollectors = append(activeCollectors, c)
}
}
glog.Infof("Active collectors: %s", strings.Join(activeCollectors, ","))
}
// registerCollectors creates and starts informers and initializes and
// registers metrics for collection via Kubernetes API.
func registerCollectors(registry prometheus.Registerer, kubeClient kubeclientset.Interface, enabledCollectors collectorSet, namespace string) {
activeCollectors := []string{}
for c, _ := range enabledCollectors {
f, ok := availableCollectors[c]
if ok {
f(registry, kubeClient, namespace)
activeCollectors = append(activeCollectors, c)
}
}
glog.Infof("Active collectors: %s", strings.Join(activeCollectors, ","))
}