-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
281 lines (233 loc) · 7.43 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
/*
Copyright 2022.
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"
"flag"
"net/http"
"os"
"os/signal"
"syscall"
"time"
// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
// to ensure that exec-entrypoint and run can make use of them.
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/runtime"
utilRuntime "k8s.io/apimachinery/pkg/util/runtime"
clientGoScheme "k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"github.com/gin-gonic/gin"
"github.com/go-logr/zapr"
"github.com/uptrace/opentelemetry-go-extra/otelzap"
v1alpha1 "github.com/cedi/urlshortener/api/v1alpha1"
"github.com/cedi/urlshortener/controllers"
shortlinkClient "github.com/cedi/urlshortener/pkg/client"
apiController "github.com/cedi/urlshortener/pkg/controller"
"github.com/cedi/urlshortener/pkg/observability"
"github.com/cedi/urlshortener/pkg/router"
"github.com/pkg/errors"
//+kubebuilder:scaffold:imports
)
var (
scheme = runtime.NewScheme()
serviceName = "urlshortener"
serviceVersion = "1.0.0"
)
func init() {
utilRuntime.Must(clientGoScheme.AddToScheme(scheme))
utilRuntime.Must(v1alpha1.AddToScheme(scheme))
//+kubebuilder:scaffold:scheme
}
// @title URL Shortener
// @version 1.0
// @description A url shortener, written in Go running on Kubernetes
// @contact.name Cedric Kienzler
// @contact.url cedi.dev
// @contact.email [email protected]
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @BasePath /
func main() {
var metricsAddr string
var probeAddr string
var bindAddr string
var namespaced bool
var debug bool
flag.StringVar(&metricsAddr, "metrics-bind-address", ":9110", "The address the metric endpoint binds to.")
flag.StringVar(&probeAddr, "health-probe-bind-address", ":9081", "The address the probe endpoint binds to.")
flag.StringVar(&bindAddr, "bind-address", ":8443", "The address the service binds to.")
flag.BoolVar(&namespaced, "namespaced", true, "Restrict the urlshortener to only list resources in the current namespace")
flag.BoolVar(&debug, "debug", false, "Turn on debug logging")
flag.Parse()
// Initialize Logging
otelLogger, undo := observability.InitLogging(debug)
defer otelLogger.Sync()
defer undo()
ctrl.SetLogger(zapr.NewLogger(otelzap.L().Logger))
// Initialize Tracing (OpenTelemetry)
traceProvider, tracer, err := observability.InitTracer(serviceName, serviceVersion)
if err != nil {
otelzap.L().Sugar().Errorw("failed initializing tracing",
zap.Error(err),
)
os.Exit(1)
}
defer func() {
if err := traceProvider.Shutdown(context.Background()); err != nil {
otelzap.L().Sugar().Errorw("Error shutting down tracer provider",
zap.Error(err),
)
}
}()
// Start namespaced
namespace := ""
if namespaced {
_, span := tracer.Start(context.Background(), "main.loadNamespace")
// try to read the namespace from /var/run
namespaceByte, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
if err != nil {
span.RecordError(err)
otelzap.L().Sugar().Errorw("Error shutting down tracer provider",
zap.Error(err),
)
os.Exit(1)
}
span.End()
namespace = string(namespaceByte)
}
_, span := tracer.Start(context.Background(), "main.startManager")
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 9443,
HealthProbeBindAddress: probeAddr,
LeaderElection: false,
LeaderElectionID: "a9a252fc.cedi.dev",
LeaderElectionReleaseOnCancel: false,
Namespace: string(namespace),
})
if err != nil {
span.RecordError(err)
otelzap.L().Sugar().Errorw("unable to start urlshortener",
zap.Error(err),
)
os.Exit(1)
}
sClient := shortlinkClient.NewShortlinkClient(
mgr.GetClient(),
tracer,
)
rClient := shortlinkClient.NewRedirectClient(
mgr.GetClient(),
tracer,
)
shortlinkReconciler := controllers.NewShortLinkReconciler(
sClient,
mgr.GetScheme(),
tracer,
)
if err = shortlinkReconciler.SetupWithManager(mgr); err != nil {
span.RecordError(err)
otelzap.L().Sugar().Errorw("unable to create controller",
zap.Error(err),
zap.String("controller", "ShortLink"),
)
os.Exit(1)
}
redirectReconciler := controllers.NewRedirectReconciler(
mgr.GetClient(),
rClient,
mgr.GetScheme(),
tracer,
)
if err = redirectReconciler.SetupWithManager(mgr); err != nil {
span.RecordError(err)
otelzap.L().Sugar().Errorw("unable to create controller",
zap.Error(err),
zap.String("controller", "Redirect"),
)
os.Exit(1)
}
//+kubebuilder:scaffold:builder
span.End()
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
otelzap.L().Sugar().Errorw("unable to set up health check",
zap.Error(err),
)
os.Exit(1)
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
otelzap.L().Sugar().Errorw("unable to set up ready check",
zap.Error(err),
)
os.Exit(1)
}
// run our urlshortener mgr in a separate go routine
go func() {
otelzap.L().Info("starting urlshortener")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
otelzap.L().Sugar().Errorw("unable starting urlshortener",
zap.Error(err),
)
os.Exit(1)
}
}()
shortlinkController := apiController.NewShortlinkController(
tracer,
sClient,
)
// Init Gin Framework
gin.SetMode(gin.ReleaseMode)
r, srv := router.NewGinGonicHTTPServer(bindAddr, serviceName)
otelzap.L().Info("Load API routes")
router.Load(r, shortlinkController)
// run our gin server mgr in a separate go routine
go func() {
if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
otelzap.L().Sugar().Errorw("failed to listen and serve",
zap.Error(err),
)
}
}()
handleShutdown(srv)
otelzap.L().Info("Server exiting")
}
// handleShutdown waits for interrupt signal and then tries to gracefully
// shutdown the server with a timeout of 5 seconds.
func handleShutdown(srv *http.Server) {
quit := make(chan os.Signal, 1)
signal.Notify(
quit,
syscall.SIGINT, // kill -2 is syscall.SIGINT
syscall.SIGTERM, // kill (no param) default send syscall.SIGTERM
// kill -9 is syscall.SIGKILL but can't be caught
)
// wait (and block) until shutdown signal is received
<-quit
otelzap.L().Info("Shutting down server...")
// The context is used to inform the server it has 5 seconds to finish
// the request it is currently handling
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// try to shut down the http server gracefully. If ctx deadline exceeds
// then srv.Shutdown(ctx) will return an error, causing us to force
// the shutdown
if err := srv.Shutdown(ctx); err != nil {
otelzap.L().Sugar().Errorw("Server forced to shutdown",
zap.Error(err),
)
os.Exit(1)
}
}