-
Notifications
You must be signed in to change notification settings - Fork 37
/
main.go
211 lines (183 loc) · 7.18 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
/*
* Tencent is pleased to support the open source community by making TKEStack available.
*
* Copyright (C) 2012-2019 Tencent. All Rights Reserved.
*
* 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
*
* https://opensource.org/licenses/Apache-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 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"
"os"
"time"
"tkestack.io/tapp/pkg/admission"
clientset "tkestack.io/tapp/pkg/client/clientset/versioned"
informers "tkestack.io/tapp/pkg/client/informers/externalversions"
"tkestack.io/tapp/pkg/tapp"
"tkestack.io/tapp/pkg/version/verflag"
"github.com/spf13/pflag"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
kubeinformers "k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
componentbaseconfig "k8s.io/component-base/config"
"k8s.io/component-base/logs"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/client/leaderelectionconfig"
)
var (
masterURL string
kubeconfig string
createCRD bool
// If true, delete instance pod after app finishes, otherwise delete pod once pod finishes.
deletePodAfterAppFinish bool
// kubeAPIQPS is the QPS to use while talking with kubernetes apiserver.
kubeAPIQPS float32
// kubeAPIBurst is the burst to use while talking with kubernetes apiserver.
kubeAPIBurst int
// TApp sync worker number
worker int
// Admission related config
registerAdmission bool
tlsCAfile string
tlsCertFile string
tlsKeyFile string
listenAddress string
// namespace to deploy tapp controller
namespace string
// leaderElection defines the configuration of leader election client.
// The default value refers k8s.io/component-base/config/v1alpha1/defaults.go
leaderElection = componentbaseconfig.LeaderElectionConfiguration{
LeaderElect: false,
LeaseDuration: metav1.Duration{Duration: 15 * time.Second},
RenewDeadline: metav1.Duration{Duration: 10 * time.Second},
RetryPeriod: metav1.Duration{Duration: 2 * time.Second},
ResourceLock: "endpoints",
}
)
const (
defaultWorkerNumber = 5
defaultKubeAPIQPS = 2000
defaultKubeAPIBurst = 2500
)
func main() {
cfg, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)
if err != nil {
klog.Fatalf("Error building kubeconfig: %s", err.Error())
}
cfg.QPS = kubeAPIQPS
cfg.Burst = kubeAPIBurst
kubeClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
klog.Fatalf("Error building kubernetes clientset: %s", err.Error())
}
tappClient, err := clientset.NewForConfig(cfg)
if err != nil {
klog.Fatalf("Error building example clientset: %s", err.Error())
}
extensionsClient, err := apiextensionsclient.NewForConfig(cfg)
if err != nil {
klog.Fatalf("Error instantiating apiextensions client: %s", err.Error())
}
kubeInformerFactory := kubeinformers.NewSharedInformerFactory(kubeClient, time.Second*30)
tappInformerFactory := informers.NewSharedInformerFactory(tappClient, time.Second*30)
controller := tapp.NewController(kubeClient, tappClient, kubeInformerFactory, tappInformerFactory)
run := func(ctx context.Context) {
stop := ctx.Done()
if createCRD {
wait.PollImmediateUntil(time.Second*5, func() (bool, error) { return tapp.EnsureCRDCreated(extensionsClient) }, stop)
}
if registerAdmission {
wait.PollImmediateUntil(time.Second*5, func() (bool, error) {
return admission.Register(kubeClient, namespace, tlsCAfile)
}, stop)
server, err := admission.NewServer(listenAddress, tlsCertFile, tlsKeyFile)
if err != nil {
klog.Fatalf("Error new admission server: %v", err)
}
go server.Run(stop)
}
go kubeInformerFactory.Start(stop)
go tappInformerFactory.Start(stop)
tapp.SetDeletePodAfterAppFinish(deletePodAfterAppFinish)
if err = controller.Run(worker, stop); err != nil {
klog.Fatalf("Error running controller: %s", err.Error())
}
}
if !leaderElection.LeaderElect {
run(context.TODO())
panic("unreachable")
}
id, err := os.Hostname()
if err != nil {
klog.Fatalf("Failed to get hostname: %s", err.Error())
}
leaderElectionClient := kubernetes.NewForConfigOrDie(restclient.AddUserAgent(cfg, "leader-election"))
rl, err := resourcelock.New(leaderElection.ResourceLock,
"kube-system",
"tapp-controller",
leaderElectionClient.CoreV1(),
leaderElectionClient.CoordinationV1(),
resourcelock.ResourceLockConfig{
Identity: id,
EventRecorder: controller.GetEventRecorder(),
})
if err != nil {
klog.Fatalf("error creating lock: %v", err)
}
leaderelection.RunOrDie(context.TODO(), leaderelection.LeaderElectionConfig{
Lock: rl,
LeaseDuration: leaderElection.LeaseDuration.Duration,
RenewDeadline: leaderElection.RenewDeadline.Duration,
RetryPeriod: leaderElection.RetryPeriod.Duration,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: run,
OnStoppedLeading: func() {
klog.Fatalf("leaderelection lost")
},
},
})
panic("unreachable")
}
func init() {
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
addFlags(pflag.CommandLine)
pflag.Parse()
logs.InitLogs()
defer logs.FlushLogs()
verflag.PrintAndExitIfRequested()
}
func addFlags(fs *pflag.FlagSet) {
fs.StringVar(&kubeconfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.")
fs.StringVar(&masterURL, "master", "",
"The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.")
fs.BoolVar(&createCRD, "create-crd", true, "Create TApp CRD if it does not exist")
fs.BoolVar(&deletePodAfterAppFinish, "delete-pod-after-app-finish", true,
"If true, delete instance pod after app finishes, otherwise delete pod once pod finishes")
fs.Float32Var(&kubeAPIQPS, "kube-api-qps", defaultKubeAPIQPS, "QPS to use while talking with kubernetes apiserver")
fs.IntVar(&kubeAPIBurst, "kube-api-burst", defaultKubeAPIBurst, "Burst to use while talking with kubernetes apiserver")
fs.IntVar(&worker, "worker", defaultWorkerNumber, "TApp sync worker number, default: 5")
// Admission related
fs.BoolVar(®isterAdmission, "register-admission", false, "Register admission for tapp controller")
fs.StringVar(&tlsCAfile, "tlsCAFile", "/etc/certs/ca.crt", "File containing the x509 CA for HTTPS")
fs.StringVar(&listenAddress, "listen-address", ":8443", "The address to listen on for HTTP requests.")
fs.StringVar(&tlsCertFile, "tlsCertFile", "/etc/certs/tls.crt", "File containing the x509 Certificate for HTTPS.")
fs.StringVar(&tlsKeyFile, "tlsKeyFile", "/etc/certs/tls.key", "File containing the x509 private key to for HTTPS.")
fs.StringVar(&namespace, "namespace", "kube-system", "Namespace to deploy tapp controller")
leaderelectionconfig.BindFlags(&leaderElection, fs)
}