-
Notifications
You must be signed in to change notification settings - Fork 248
/
main.go
272 lines (241 loc) · 9.15 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
package main
import (
"errors"
"flag"
"fmt"
"os"
"time"
"cloud.google.com/go/storage"
"github.com/bombsimon/logrusr/v3"
prometheusclient "github.com/prometheus/client_golang/api"
prometheusapi "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/sirupsen/logrus"
"google.golang.org/api/option"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/transport"
prowConfig "k8s.io/test-infra/prow/config"
prowflagutil "k8s.io/test-infra/prow/flagutil"
"k8s.io/test-infra/prow/interrupts"
"k8s.io/test-infra/prow/logrusutil"
"k8s.io/test-infra/prow/metrics"
pprofutil "k8s.io/test-infra/prow/pjutil/pprof"
"k8s.io/test-infra/prow/version"
controllerruntime "sigs.k8s.io/controller-runtime"
buildclientset "github.com/openshift/client-go/build/clientset/versioned/typed/build/v1"
routeclientset "github.com/openshift/client-go/route/clientset/versioned/typed/route/v1"
"github.com/openshift/ci-tools/pkg/results"
"github.com/openshift/ci-tools/pkg/util"
)
type options struct {
mode string
producerOptions
consumerOptions
instrumentationOptions prowflagutil.InstrumentationOptions
loglevel string
logStyle string
cacheDir string
cacheBucket string
gcsCredentialsFile string
resultsOptions results.Options
}
type producerOptions struct {
kubernetesOptions prowflagutil.KubernetesOptions
once bool
ignoreLatest time.Duration
}
type consumerOptions struct {
port int
uiPort int
dataDir string
certDir string
mutateResourceLimits bool
cpuCap int64
memoryCap string
cpuPriorityScheduling int64
}
func bindOptions(fs *flag.FlagSet) *options {
o := options{producerOptions: producerOptions{kubernetesOptions: prowflagutil.KubernetesOptions{NOInClusterConfigDefault: true}}}
o.instrumentationOptions.AddFlags(fs)
fs.StringVar(&o.mode, "mode", "", "Which mode to run in.")
o.producerOptions.kubernetesOptions.AddFlags(fs)
fs.DurationVar(&o.ignoreLatest, "ignore-latest", 0, "Duration of latest time series to ignore when querying Prometheus. For instance, 1h will ignore the latest hour of data.")
fs.BoolVar(&o.once, "produce-once", false, "Query Prometheus and refresh cached data only once before exiting.")
fs.IntVar(&o.port, "port", 0, "Port to serve admission webhooks on.")
fs.IntVar(&o.uiPort, "ui-port", 0, "Port to serve frontend on.")
fs.StringVar(&o.certDir, "serving-cert-dir", "", "Path to directory with serving certificate and key for the admission webhook server.")
fs.BoolVar(&o.mutateResourceLimits, "mutate-resource-limits", false, "Enable resource limit mutation in the admission webhook.")
fs.StringVar(&o.loglevel, "loglevel", "debug", "Logging level.")
fs.StringVar(&o.logStyle, "log-style", "json", "Logging style: json or text.")
fs.StringVar(&o.cacheDir, "cache-dir", "", "Local directory holding cache data (for development mode).")
fs.StringVar(&o.dataDir, "data-dir", "", "Local directory to cache UI data into.")
fs.StringVar(&o.cacheBucket, "cache-bucket", "", "GCS bucket name holding cached Prometheus data.")
fs.StringVar(&o.gcsCredentialsFile, "gcs-credentials-file", "", "File where GCS credentials are stored.")
fs.Int64Var(&o.cpuCap, "cpu-cap", 10, "The maximum CPU request value, ex: 10")
fs.StringVar(&o.memoryCap, "memory-cap", "20Gi", "The maximum memory request value, ex: '20Gi'")
fs.Int64Var(&o.cpuPriorityScheduling, "cpu-priority-scheduling", 8, "Pods with CPU requests at, or above, this value will be admitted with priority scheduling")
o.resultsOptions.Bind(fs)
return &o
}
const (
logStyleJson = "json"
logStyleText = "text"
)
func (o *options) validate() error {
switch o.mode {
case "producer":
return o.kubernetesOptions.Validate(false)
case "consumer.ui":
if o.uiPort == 0 {
return errors.New("--ui-port is required")
}
if o.dataDir == "" {
return errors.New("--data-dir is required")
}
case "consumer.admission":
if o.port == 0 {
return errors.New("--port is required")
}
if o.certDir == "" {
return errors.New("--serving-cert-dir is required")
}
if cpuCap := resource.NewQuantity(o.cpuCap, resource.DecimalSI); cpuCap.Sign() <= 0 {
return errors.New("--cpu-cap must be greater than 0")
}
if memoryCap := resource.MustParse(o.memoryCap); memoryCap.Sign() <= 0 {
return errors.New("--memory-cap must be greater than 0")
}
if err := o.resultsOptions.Validate(); err != nil {
return err
}
default:
return errors.New("--mode must be either \"producer\", \"consumer.ui\", or \"consumer.admission\"")
}
if o.cacheDir == "" {
if o.cacheBucket == "" {
return errors.New("--cache-bucket is required")
}
if o.gcsCredentialsFile == "" {
return errors.New("--gcs-credentials-file is required")
}
}
if level, err := logrus.ParseLevel(o.loglevel); err != nil {
return fmt.Errorf("--loglevel invalid: %w", err)
} else {
logrus.SetLevel(level)
}
if o.logStyle != logStyleJson && o.logStyle != logStyleText {
return fmt.Errorf("--log-style must be one of %s or %s, not %s", logStyleText, logStyleJson, o.logStyle)
}
return o.instrumentationOptions.Validate(false)
}
func main() {
flagSet := flag.NewFlagSet("", flag.ExitOnError)
opts := bindOptions(flagSet)
if err := flagSet.Parse(os.Args[1:]); err != nil {
logrus.WithError(err).Fatal("failed to parse flags")
}
if err := opts.validate(); err != nil {
logrus.WithError(err).Fatal("Failed to validate flags")
}
switch opts.logStyle {
case logStyleJson:
logrusutil.ComponentInit()
case logStyleText:
logrus.SetFormatter(&logrus.TextFormatter{
ForceColors: true,
DisableQuote: true,
FullTimestamp: true,
TimestampFormat: time.RFC3339,
})
}
logrus.Infof("%s version %s", version.Name, version.Version)
pprofutil.Instrument(opts.instrumentationOptions)
metrics.ExposeMetrics("pod-scaler", prowConfig.PushGateway{}, opts.instrumentationOptions.MetricsPort)
var cache cache
if opts.cacheDir != "" {
cache = &localCache{dir: opts.cacheDir}
} else {
gcsClient, err := storage.NewClient(interrupts.Context(), option.WithCredentialsFile(opts.gcsCredentialsFile))
if err != nil {
logrus.WithError(err).Fatal("Could not initialize GCS client.")
}
bucket := gcsClient.Bucket(opts.cacheBucket)
cache = &bucketCache{bucket: bucket}
}
switch opts.mode {
case "producer":
mainProduce(opts, cache)
case "consumer.ui":
mainUI(opts, cache)
case "consumer.admission":
mainAdmission(opts, cache)
}
if !opts.once {
interrupts.WaitForGracefulShutdown()
}
}
func mainProduce(opts *options, cache cache) {
kubeconfigChangedCallBack := func() {
logrus.Fatal("Kubeconfig changed, exiting to get restarted by Kubelet and pick up the changes")
}
kubeconfigs, err := opts.kubernetesOptions.LoadClusterConfigs(kubeconfigChangedCallBack)
if err != nil {
logrus.WithError(err).Fatal("Failed to load kubeconfigs")
}
clients := map[string]prometheusapi.API{}
for cluster, config := range kubeconfigs {
logger := logrus.WithField("cluster", cluster)
client, err := routeclientset.NewForConfig(&config)
if err != nil {
logger.WithError(err).Fatal("Failed to construct client.")
}
route, err := client.Routes("openshift-monitoring").Get(interrupts.Context(), "prometheus-k8s", metav1.GetOptions{})
if err != nil {
logger.WithError(err).Fatal("Failed to get Prometheus route.")
}
var addr string
if route.Spec.TLS != nil {
addr = "https://" + route.Spec.Host
} else {
addr = "http://" + route.Spec.Host
}
promClient, err := prometheusclient.NewClient(prometheusclient.Config{
Address: addr,
RoundTripper: transport.NewBearerAuthRoundTripper(config.BearerToken, prometheusclient.DefaultRoundTripper),
})
if err != nil {
logger.WithError(err).Fatal("Failed to get Prometheus client.")
}
clients[cluster] = prometheusapi.NewAPI(promClient)
logger.Debugf("Loaded Prometheus client.")
}
produce(clients, cache, opts.ignoreLatest, opts.once)
}
func mainUI(opts *options, cache cache) {
go serveUI(opts.uiPort, opts.instrumentationOptions.HealthPort, opts.dataDir, loaders(cache))
}
func mainAdmission(opts *options, cache cache) {
controllerruntime.SetLogger(logrusr.New(logrus.StandardLogger()))
restConfig, err := util.LoadClusterConfig()
if err != nil {
logrus.WithError(err).Fatal("Failed to load cluster config.")
}
client, err := buildclientset.NewForConfig(restConfig)
if err != nil {
logrus.WithError(err).Fatal("Failed to construct client.")
}
reporter, err := opts.resultsOptions.PodScalerReporter()
if err != nil {
logrus.WithError(err).Fatal("Failed to create pod-scaler reporter.")
}
go admit(opts.port, opts.instrumentationOptions.HealthPort, opts.certDir, client, loaders(cache), opts.mutateResourceLimits, opts.cpuCap, opts.memoryCap, opts.cpuPriorityScheduling, reporter)
}
func loaders(cache cache) map[string][]*cacheReloader {
l := map[string][]*cacheReloader{}
for _, prefix := range []string{prowjobsCachePrefix, podsCachePrefix, stepsCachePrefix} {
l[MetricNameCPUUsage] = append(l[MetricNameCPUUsage], newReloader(prefix+"/"+MetricNameCPUUsage, cache))
l[MetricNameMemoryWorkingSet] = append(l[MetricNameMemoryWorkingSet], newReloader(prefix+"/"+MetricNameMemoryWorkingSet, cache))
}
return l
}