forked from pyrra-dev/pyrra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kubernetes.go
225 lines (198 loc) · 6.27 KB
/
kubernetes.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
/*
Copyright 2021 Pyrra Authors.
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"
"net/http"
"os"
"syscall"
"time"
"github.com/bufbuild/connect-go"
"github.com/go-kit/log"
"github.com/oklog/run"
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql/parser"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"k8s.io/apimachinery/pkg/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"
pyrrav1alpha1 "github.com/pyrra-dev/pyrra/kubernetes/api/v1alpha1"
"github.com/pyrra-dev/pyrra/kubernetes/controllers"
objectivesv1alpha1 "github.com/pyrra-dev/pyrra/proto/objectives/v1alpha1"
"github.com/pyrra-dev/pyrra/proto/objectives/v1alpha1/objectivesv1alpha1connect"
// +kubebuilder:scaffold:imports
)
var scheme = runtime.NewScheme()
func init() {
_ = clientgoscheme.AddToScheme(scheme)
_ = pyrrav1alpha1.AddToScheme(scheme)
_ = monitoringv1.AddToScheme(scheme)
// +kubebuilder:scaffold:scheme
}
func cmdKubernetes(
logger log.Logger,
metricsAddr string,
_, genericRules, disableWebhooks bool,
certFile, privateKeyFile string,
) int {
setupLog := ctrl.Log.WithName("setup")
ctrl.SetLogger(zap.New(zap.UseDevMode(true)))
webhookServer := webhook.NewServer(webhook.Options{Port: 9443})
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
Metrics: metricsserver.Options{
BindAddress: metricsAddr,
},
WebhookServer: webhookServer,
LeaderElection: false,
LeaderElectionID: "9d76195a.pyrra.dev",
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
reconciler := &controllers.ServiceLevelObjectiveReconciler{
Client: mgr.GetClient(),
Logger: log.With(logger, "controllers", "ServiceLevelObjective"),
GenericRules: genericRules,
}
if err = reconciler.SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "ServiceLevelObjective")
os.Exit(1)
}
if !disableWebhooks {
if err = reconciler.SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "ServiceLevelObjective")
os.Exit(1)
}
}
// +kubebuilder:scaffold:builder
var (
gr run.Group
ctx, cancel = context.WithCancel(context.Background())
)
gr.Add(run.SignalHandler(ctx, os.Interrupt, syscall.SIGTERM))
{
gr.Add(func() error {
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
return fmt.Errorf("unable to set up health check: %w", err)
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
return fmt.Errorf("unable to set up ready check: %w", err)
}
setupLog.Info("starting manager")
return mgr.Start(ctx)
}, func(_ error) {
cancel()
})
}
{
router := http.NewServeMux()
router.Handle(objectivesv1alpha1connect.NewObjectiveBackendServiceHandler(&KubernetesObjectiveServer{
client: mgr.GetClient(),
}))
server := http.Server{
Addr: ":9444",
Handler: h2c.NewHandler(router, &http2.Server{}),
}
gr.Add(func() error {
if certFile != "" && privateKeyFile != "" {
setupLog.Info("serving with TLS", "cert", certFile, "key", privateKeyFile)
return server.ListenAndServeTLS(certFile, privateKeyFile)
}
return server.ListenAndServe()
}, func(_ error) {
shutdownCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
_ = server.Shutdown(shutdownCtx)
})
}
if err := gr.Run(); err != nil {
if _, ok := err.(run.SignalError); ok {
setupLog.Info("terminated", "reason", err)
return 0
}
setupLog.Error(err, "failed to run groups")
return 2
}
return 0
}
type KubernetesClient interface {
List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error
}
type KubernetesObjectiveServer struct {
client KubernetesClient
}
func (s *KubernetesObjectiveServer) List(ctx context.Context, req *connect.Request[objectivesv1alpha1.ListRequest]) (*connect.Response[objectivesv1alpha1.ListResponse], error) {
var (
matchers []*labels.Matcher
nameMatcher *labels.Matcher
namespaceMatcher *labels.Matcher
)
if req.Msg.Expr != "" {
var err error
matchers, err = parser.ParseMetricSelector(req.Msg.Expr)
if err != nil {
return nil, connect.NewError(connect.CodeFailedPrecondition, fmt.Errorf("failed to parse expr: %w", err))
}
for _, m := range matchers {
if m.Name == labels.MetricName {
nameMatcher = m
}
if m.Name == "namespace" {
namespaceMatcher = m
}
}
}
listOpts := client.ListOptions{}
for _, m := range matchers {
if m.Name == "namespace" && m.Type == labels.MatchEqual {
listOpts.Namespace = m.Value
break
}
}
var list pyrrav1alpha1.ServiceLevelObjectiveList
if err := s.client.List(ctx, &list, &listOpts); err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
objectives := make([]*objectivesv1alpha1.Objective, 0, len(list.Items))
for _, s := range list.Items {
if nameMatcher != nil {
if !nameMatcher.Matches(s.GetName()) {
continue
}
}
if namespaceMatcher != nil {
if !namespaceMatcher.Matches(s.GetNamespace()) {
continue
}
}
internal, err := s.Internal()
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
objectives = append(objectives, objectivesv1alpha1.FromInternal(internal))
}
return connect.NewResponse(&objectivesv1alpha1.ListResponse{
Objectives: objectives,
}), nil
}