This repository has been archived by the owner on May 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
227 lines (190 loc) · 6.53 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
/*
* Copyright 2022 The flomesh.io 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"
"flag"
"fmt"
"github.com/flomesh-io/ErieCanal/pkg/commons"
"github.com/flomesh-io/ErieCanal/pkg/config"
"github.com/flomesh-io/ErieCanal/pkg/event"
"github.com/flomesh-io/ErieCanal/pkg/kube"
"github.com/flomesh-io/ErieCanal/pkg/repo"
"github.com/flomesh-io/ErieCanal/pkg/util"
"github.com/flomesh-io/ErieCanal/pkg/util/tls"
"github.com/flomesh-io/ErieCanal/pkg/version"
"github.com/spf13/pflag"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
"k8s.io/klog/v2/klogr"
"math/rand"
"os"
"sigs.k8s.io/controller-runtime/pkg/manager"
"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.
_ "k8s.io/client-go/plugin/pkg/client/auth"
flomeshscheme "github.com/flomesh-io/ErieCanal/pkg/generated/clientset/versioned/scheme"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
gwschema "sigs.k8s.io/gateway-api/pkg/client/clientset/versioned/scheme"
//+kubebuilder:scaffold:imports
)
var (
scheme = runtime.NewScheme()
//setupLog = ctrl.Log.WithName("setup")
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(flomeshscheme.AddToScheme(scheme))
utilruntime.Must(gwschema.AddToScheme(scheme))
//+kubebuilder:scaffold:scheme
}
type startArgs struct {
managerConfigFile string
namespace string
}
func main() {
// process CLI arguments and parse them to flags
args := processFlags()
options := loadManagerOptions(args.managerConfigFile)
klog.Infof(commons.AppVersionTemplate, version.Version, version.ImageVersion, version.GitVersion, version.GitCommit, version.BuildDate)
kubeconfig := ctrl.GetConfigOrDie()
k8sApi := newK8sAPI(kubeconfig, args)
if !version.IsSupportedK8sVersion(k8sApi) {
klog.Error(fmt.Errorf("kubernetes server version %s is not supported, requires at least %s",
version.ServerVersion.String(), version.MinK8sVersion.String()))
os.Exit(1)
}
// ErieCanal configurations
controlPlaneConfigStore := config.NewStore(k8sApi)
mcClient := controlPlaneConfigStore.MeshConfig
mc := mcClient.GetConfig()
mc.Cluster.UID = getClusterUID(k8sApi)
mc, err := mcClient.UpdateConfig(mc)
if err != nil {
os.Exit(1)
}
// generate certificate and store it in k8s secret flomesh-ca-bundle
certMgr, err := tls.GetCertificateManager(k8sApi, mc)
if err != nil {
os.Exit(1)
}
// upload init scripts to pipy repo
repoClient := repo.NewRepoClient(mc.RepoRootURL())
initRepo(repoClient)
// setup HTTP
setupHTTP(repoClient, mc)
// setup TLS config
setupTLS(certMgr, repoClient, mc)
// create a new manager for controllers
mgr := newManager(kubeconfig, options)
stopCh := util.RegisterOSExitHandlers()
broker := event.NewBroker(stopCh)
// create mutating and validating webhook configurations
createWebhookConfigurations(k8sApi, controlPlaneConfigStore, certMgr)
// register Reconcilers
registerReconcilers(mgr, k8sApi, controlPlaneConfigStore, certMgr, broker)
// register webhooks
registerToWebhookServer(mgr, k8sApi, controlPlaneConfigStore)
registerEventHandler(mgr, k8sApi, controlPlaneConfigStore, certMgr)
// add endpoints for Liveness and Readiness check
addLivenessAndReadinessCheck(mgr)
//+kubebuilder:scaffold:builder
// start the controller manager
startManager(mgr, mc)
}
func processFlags() *startArgs {
var configFile string
flag.StringVar(&configFile, "config", "manager_config.yaml",
"The controller will load its initial configuration from this file. "+
"Omit this flag to use the default configuration values. "+
"Command-line flags override configuration from this file.")
klog.InitFlags(nil)
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.Parse()
rand.Seed(time.Now().UnixNano())
ctrl.SetLogger(klogr.New())
return &startArgs{
managerConfigFile: configFile,
namespace: config.GetErieCanalNamespace(),
}
}
func loadManagerOptions(configFile string) ctrl.Options {
var err error
options := ctrl.Options{Scheme: scheme}
if configFile != "" {
options, err = options.AndFrom(ctrl.ConfigFile().AtPath(configFile))
if err != nil {
klog.Error(err, "unable to load the config file")
os.Exit(1)
}
}
return options
}
func newManager(kubeconfig *rest.Config, options ctrl.Options) manager.Manager {
mgr, err := ctrl.NewManager(kubeconfig, options)
if err != nil {
klog.Error(err, "unable to create manager")
os.Exit(1)
}
return mgr
}
func newK8sAPI(kubeconfig *rest.Config, args *startArgs) *kube.K8sAPI {
api, err := kube.NewAPIForConfig(kubeconfig, 30*time.Second)
if err != nil {
klog.Error(err, "unable to create k8s client")
os.Exit(1)
}
return api
}
func getClusterUID(api *kube.K8sAPI) string {
ns, err := api.Client.CoreV1().Namespaces().Get(context.TODO(), config.GetErieCanalNamespace(), metav1.GetOptions{})
if err != nil {
klog.Errorf("Failed to get ErieCanal namespace: %s", err)
os.Exit(1)
}
return string(ns.UID)
}
func addLivenessAndReadinessCheck(mgr manager.Manager) {
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
klog.Error(err, "unable to set up health check")
os.Exit(1)
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
klog.Error(err, "unable to set up ready check")
os.Exit(1)
}
}
func startManager(mgr manager.Manager, mc *config.MeshConfig) {
//err := mgr.Add(manager.RunnableFunc(func(context.Context) error {
// aggregatorAddr := fmt.Sprintf(":%s", mc.AggregatorPort())
// return aggregator.NewAggregator(aggregatorAddr, mc.RepoAddr()).Run()
//}))
//if err != nil {
// klog.Error(err, "unable add aggregator server to the manager")
// os.Exit(1)
//}
klog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
klog.Fatalf("problem running manager, %s", err.Error())
os.Exit(1)
}
}