/
main.go
257 lines (224 loc) · 9.28 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
/*
MIT License
Copyright (c) 2023 mercari
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package main
import (
"context"
"flag"
"os"
"time"
"github.com/go-logr/zapr"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
v2 "k8s.io/api/autoscaling/v2"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
controllerfetcher "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/target/controller_fetcher"
"k8s.io/client-go/informers"
kube_client "k8s.io/client-go/kubernetes"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
autoscalingv2 "github.com/mercari/tortoise/api/autoscaling/v2"
v1 "github.com/mercari/tortoise/api/core/v1"
autoscalingv1beta3 "github.com/mercari/tortoise/api/v1beta3"
"github.com/mercari/tortoise/controllers"
"github.com/mercari/tortoise/pkg/config"
"github.com/mercari/tortoise/pkg/deployment"
"github.com/mercari/tortoise/pkg/hpa"
"github.com/mercari/tortoise/pkg/pod"
"github.com/mercari/tortoise/pkg/recommender"
"github.com/mercari/tortoise/pkg/tortoise"
"github.com/mercari/tortoise/pkg/vpa"
// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
// to ensure that exec-entrypoint and run can make use of them.
_ "k8s.io/client-go/plugin/pkg/client/auth"
)
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(autoscalingv1beta3.AddToScheme(scheme))
//+kubebuilder:scaffold:scheme
}
func main() {
var metricsAddr string
var enableLeaderElection bool
var probeAddr string
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
// Tortoise specific flags
var configPath string
var logLevel string
flag.StringVar(&configPath, "config", "", "The path to the config file.")
flag.StringVar(&logLevel, "log-level", "DEBUG", "The log level: DEBUG, INFO, or ERROR")
flag.Parse()
level, err := zapcore.ParseLevel(logLevel)
if err != nil {
setupLog.Error(err, "failed to parse log level, valid values are DEBUG, INFO, or ERROR")
os.Exit(1)
}
zapconfig := zap.NewProductionConfig()
zapconfig.Level = zap.NewAtomicLevelAt(level)
zapconfig.DisableStacktrace = true
zapconfig.Sampling = nil
zapconfig.OutputPaths = []string{"stdout"}
zapconfig.ErrorOutputPaths = []string{"stderr"}
l, err := zapconfig.Build()
if err != nil {
setupLog.Error(err, "failed to create logger")
os.Exit(1)
}
ctrl.SetLogger(zapr.NewLogger(l))
config, err := config.ParseConfig(configPath)
if err != nil {
setupLog.Error(err, "failed to load config")
os.Exit(1)
}
setupLog.Info("config", "config", *config)
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 9443,
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "76c4d78a.mercari.com",
// LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily
// when the Manager ends. This requires the binary to immediately end when the
// Manager is stopped, otherwise, this setting is unsafe. Setting this significantly
// speeds up voluntary leader transitions as the new leader don't have to wait
// LeaseDuration time first.
//
// In the default scaffold provided, the program ends immediately after
// the manager stops, so would be fine to enable this option. However,
// if you are doing or is intended to do any operation such as perform cleanups
// after the manager stops then its usage might be unsafe.
LeaderElectionReleaseOnCancel: true,
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
eventRecorder := mgr.GetEventRecorderFor("tortoise-controller")
tortoiseService, err := tortoise.New(mgr.GetClient(), eventRecorder, config.RangeOfMinMaxReplicasRecommendationHours, config.TimeZone, config.TortoiseUpdateInterval, config.GatheringDataPeriodType)
if err != nil {
setupLog.Error(err, "unable to start tortoise service")
os.Exit(1)
}
vpaClient, err := vpa.New(mgr.GetConfig(), eventRecorder)
if err != nil {
setupLog.Error(err, "unable to start vpa client")
os.Exit(1)
}
hpaService, err := hpa.New(mgr.GetClient(), eventRecorder, config.ReplicaReductionFactor, config.MaximumTargetResourceUtilization, config.HPATargetUtilizationMaxIncrease, config.HPATargetUtilizationUpdateInterval, config.MaximumMinReplicas, config.MaximumMaxReplicas, int32(config.MinimumMinReplicas), config.HPAExternalMetricExclusionRegex)
if err != nil {
setupLog.Error(err, "unable to start hpa service")
os.Exit(1)
}
if err = (&controllers.TortoiseReconciler{
Scheme: mgr.GetScheme(),
HpaService: hpaService,
VpaService: vpaClient,
DeploymentService: deployment.New(mgr.GetClient(), config.IstioSidecarProxyDefaultCPU, config.IstioSidecarProxyDefaultMemory, eventRecorder),
RecommenderService: recommender.New(
config.MaxReplicasRecommendationMultiplier,
config.MinReplicasRecommendationMultiplier,
config.MaximumTargetResourceUtilization,
config.MinimumTargetResourceUtilization,
config.MinimumMinReplicas,
config.PreferredMaxReplicas,
config.MinimumCPURequest,
config.MinimumMemoryRequest,
config.MinimumCPURequestPerContainer,
config.MinimumMemoryRequestPerContainer,
config.MaximumCPURequest,
config.MaximumMemoryRequest,
config.MaximumMaxReplicas,
config.MaxAllowedScalingDownRatio,
config.BufferRatioOnVerticalResource,
config.FeatureFlags,
eventRecorder,
),
TortoiseService: tortoiseService,
Interval: config.TortoiseUpdateInterval,
EventRecorder: eventRecorder,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Tortoise")
os.Exit(1)
}
if err = (&autoscalingv1beta3.Tortoise{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "Tortoise")
os.Exit(1)
}
//+kubebuilder:scaffold:builder
hpaWebhook := autoscalingv2.New(tortoiseService, hpaService)
const (
defaultResyncPeriod = 10 * time.Minute
statusUpdateInterval = 10 * time.Second
scaleCacheEntryLifetime time.Duration = time.Hour
scaleCacheEntryFreshnessTime time.Duration = 10 * time.Minute
scaleCacheEntryJitterFactor float64 = 1.
)
kubeClient := kube_client.NewForConfigOrDie(mgr.GetConfig())
factory := informers.NewSharedInformerFactory(kubeClient, defaultResyncPeriod)
controllerFetcher := controllerfetcher.NewControllerFetcher(mgr.GetConfig(), kubeClient, factory, scaleCacheEntryFreshnessTime, scaleCacheEntryLifetime, scaleCacheEntryJitterFactor)
ctx, cancel := context.WithCancel(context.Background())
controllerFetcher.Start(ctx, 1*time.Second)
defer cancel()
podService, err := pod.New(config.ResourceLimitMultiplier, config.MinimumCPULimit, controllerFetcher, config.FeatureFlags)
if err != nil {
setupLog.Error(err, "unable to create pod service")
os.Exit(1)
}
podWebhook := v1.New(tortoiseService, podService)
if err = ctrl.NewWebhookManagedBy(mgr).
WithDefaulter(hpaWebhook).
WithValidator(hpaWebhook).
For(&v2.HorizontalPodAutoscaler{}).
Complete(); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "HorizontalPodAutoscaler")
os.Exit(1)
}
if err = ctrl.NewWebhookManagedBy(mgr).
WithDefaulter(podWebhook).
For(&corev1.Pod{}).
Complete(); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "Pod")
os.Exit(1)
}
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up health check")
os.Exit(1)
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up ready check")
os.Exit(1)
}
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}