forked from kubernetes-sigs/dashboard-metrics-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
180 lines (149 loc) · 5.12 KB
/
server.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
package main
import (
"context"
"database/sql"
"net/http"
"os"
"time"
log "github.com/sirupsen/logrus"
flag "github.com/spf13/pflag"
_ "github.com/mattn/go-sqlite3"
sideapi "github.com/kubernetes-sigs/dashboard-metrics-scraper/pkg/api"
sidedb "github.com/kubernetes-sigs/dashboard-metrics-scraper/pkg/database"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/metrics/pkg/apis/metrics/v1beta1"
metricsclient "k8s.io/metrics/pkg/client/clientset/versioned"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
func main() {
var kubeconfig *string
var dbFile *string
var metricResolution *time.Duration
var metricDuration *time.Duration
var logLevel *string
var logToStdErr *bool
var metricNamespace *[]string
log.SetFormatter(&log.JSONFormatter{})
// Output to stdout instead of the default stderr
// Can be any io.Writer, see below for File example
log.SetOutput(os.Stdout)
// Only log the warning severity or above.
log.SetLevel(log.InfoLevel)
kubeconfig = flag.String("kubeconfig", "", "The path to the kubeconfig used to connect to the Kubernetes API server and the Kubelets (defaults to in-cluster config)")
dbFile = flag.String("db-file", "/tmp/metrics.db", "What file to use as a SQLite3 database.")
metricResolution = flag.Duration("metric-resolution", 1*time.Minute, "The resolution at which dashboard-metrics-scraper will poll metrics.")
metricDuration = flag.Duration("metric-duration", 15*time.Minute, "The duration after which metrics are purged from the database.")
logLevel = flag.String("log-level", "info", "The log level")
logToStdErr = flag.Bool("logtostderr", true, "Log to stderr")
// When running in a scoped namespace, disable Node lookup and only capture metrics for the given namespace(s)
metricNamespace = flag.StringSliceP("namespace", "n", []string{getEnv("POD_NAMESPACE", "")}, "The namespace to use for all metric calls. When provided, skip node metrics. (defaults to cluster level metrics)")
flag.Parse()
if *logToStdErr {
log.SetOutput(os.Stderr)
}
level, err := log.ParseLevel(*logLevel)
if err != nil {
log.Fatal(err)
} else {
log.SetLevel(level)
}
// This should only be run in-cluster so...
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
log.Fatalf("Unable to generate a client config: %s", err)
}
log.Infof("Kubernetes host: %s", config.Host)
log.Infof("Namespace(s): %s", *metricNamespace)
// Generate the metrics client
clientset, err := metricsclient.NewForConfig(config)
if err != nil {
log.Fatalf("Unable to generate a clientset: %s", err)
}
// Create the db "connection"
db, err := sql.Open("sqlite3", *dbFile)
if err != nil {
log.Fatalf("Unable to open Sqlite database: %s", err)
}
defer db.Close()
// Populate tables
err = sidedb.CreateDatabase(db)
if err != nil {
log.Fatalf("Unable to initialize database tables: %s", err)
}
go func() {
r := mux.NewRouter()
sideapi.Manager(r, db)
// Bind to a port and pass our router in
log.Fatal(http.ListenAndServe(":8000", handlers.CombinedLoggingHandler(os.Stdout, r)))
}()
// Start the machine. Scrape every metricResolution
ticker := time.NewTicker(*metricResolution)
quit := make(chan struct{})
for {
select {
case <-quit:
ticker.Stop()
return
case <-ticker.C:
err = update(clientset, db, metricDuration, metricNamespace)
if err != nil {
break
}
}
}
}
/**
* Update the Node and Pod metrics in the provided DB
*/
func update(client *metricsclient.Clientset, db *sql.DB, metricDuration *time.Duration, metricNamespace *[]string) error {
nodeMetrics := &v1beta1.NodeMetricsList{}
podMetrics := &v1beta1.PodMetricsList{}
ctx := context.TODO()
var err error
// If no namespace is provided, make a call to the Node
if len(*metricNamespace) == 1 && (*metricNamespace)[0] == "" {
// List node metrics across the cluster
nodeMetrics, err = client.MetricsV1beta1().NodeMetricses().List(ctx, v1.ListOptions{})
if err != nil {
log.Errorf("Error scraping node metrics: %s", err)
return err
}
}
// List pod metrics across the cluster, or for a given namespace
for _, namespace := range *metricNamespace {
pod, err := client.MetricsV1beta1().PodMetricses(namespace).List(ctx, v1.ListOptions{})
if err != nil {
log.Errorf("Error scraping '%s' for pod metrics: %s", namespace, err)
return err
}
podMetrics.TypeMeta = pod.TypeMeta
podMetrics.ListMeta = pod.ListMeta
podMetrics.Items = append(podMetrics.Items, pod.Items...)
}
// Insert scrapes into DB
err = sidedb.UpdateDatabase(db, nodeMetrics, podMetrics)
if err != nil {
log.Errorf("Error updating database: %s", err)
return err
}
// Delete rows outside of the metricDuration time
err = sidedb.CullDatabase(db, metricDuration)
if err != nil {
log.Errorf("Error culling database: %s", err)
return err
}
log.Infof("Database updated: %d nodes, %d pods", len(nodeMetrics.Items), len(podMetrics.Items))
return nil
}
/**
* Lookup the environment variable provided and set to default value if variable isn't found
*/
func getEnv(key, fallback string) string {
value := os.Getenv(key)
if value == "" {
value = fallback
}
return value
}