/
main.go
153 lines (129 loc) · 3.71 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
/*
Copyright 2020 Red Hat, Inc. jcope@redhat.com
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 (
"context"
"fmt"
"github.com/Masterminds/squirrel"
routev1 "github.com/openshift/api/route/v1"
routeClient "github.com/openshift/client-go/route/clientset/versioned/typed/route/v1"
promapi "github.com/prometheus/client_golang/api"
promv1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/spf13/pflag"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/klog/v2"
"github.com/redhat-et/caliper/prom-top/pkg/dbhandler"
"github.com/redhat-et/caliper/prom-top/pkg/top"
)
func hasBearerToken(cfg *rest.Config) bool {
if len(cfg.BearerToken) == 0 && len(cfg.BearerTokenFile) == 0 {
return false
}
return true
}
func prometheusHost(r *routev1.Route) string {
return fmt.Sprintf("https://%s", r.Spec.Host)
}
func handleError(e error) {
if e != nil {
klog.ExitDepth(1, e)
}
}
const (
promNamespace = `openshift-monitoring`
promRoute = `prometheus-k8s`
)
func main() {
pflag.Parse()
defer klog.Flush()
klog.Infof("initializing openshift client from KUBECONFIG=%s", kubeconfig)
cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
handleError(err)
if !hasBearerToken(cfg) {
klog.Exit("error: bearer token not found, required access to prometheus oauth access. login to cluster with 'oc'")
}
rc := routeClient.NewForConfigOrDie(cfg)
klog.Infof("fetching prometheus route")
route, err := rc.Routes(promNamespace).Get(context.Background(), promRoute, metav1.GetOptions{})
handleError(err)
transport, err := rest.TransportFor(cfg)
handleError(err)
host := prometheusHost(route)
klog.Infof("initializing connection for host: %s", host)
conn, err := promapi.NewClient(promapi.Config{
Address: host,
RoundTripper: transport,
})
klog.Info("creating prometheus api client")
pc := promv1.NewAPI(conn)
handleError(err)
result, err := top.Top(top.Config{
Range: queryRange,
Context: context.Background(),
PrometheusClient: pc,
})
handleError(err)
if toDb {
if err = streamToDatabase(result); err != nil {
handleError(err)
}
} else {
printToStdout(result)
}
handleError(err)
}
//Postgres compatible time format, required for converting query timestamps
func streamToDatabase(metrics top.PodMetricTable) error {
klog.Infoln("init postgres db client")
db, err := dbhandler.NewPostgresClient()
if err != nil {
return fmt.Errorf("failed to send to db: %v", err)
}
sqIns := squirrel.
Insert(dbhandler.Table).
Columns(dbhandler.ColumnsHeaders()...).
PlaceholderFormat(squirrel.Dollar).
RunWith(db)
for _, m := range metrics {
sqIns = sqIns.Values(
version,
m.Metric,
m.Node,
m.Pod,
m.Namespace,
m.OwnerName,
m.AvgValue,
m.Q95Value,
m.MaxValue,
m.MinValue,
m.InstValue,
m.QueryTime,
m.Range,
)
}
resp, err := sqIns.Exec()
if err != nil {
return fmt.Errorf("unable to generate sql insert script: %v", err)
}
nrows, _ := resp.RowsAffected()
klog.Infof("insert success, updated %d rows", nrows)
return nil
}
func printToStdout(podMetrics []*top.PodMetric) {
klog.Infof("got %d results", len(podMetrics))
for _, pm := range podMetrics {
klog.Info(pm)
}
}