/
agent.go
442 lines (390 loc) · 15.1 KB
/
agent.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package options
import (
"flag"
"fmt"
"github.com/choerodon/choerodon-cluster-agent/pkg/agent"
"github.com/choerodon/choerodon-cluster-agent/pkg/agent/channel"
"github.com/choerodon/choerodon-cluster-agent/pkg/agent/model"
agentnamespace "github.com/choerodon/choerodon-cluster-agent/pkg/agent/namespace"
agentsync "github.com/choerodon/choerodon-cluster-agent/pkg/agent/sync"
"github.com/choerodon/choerodon-cluster-agent/pkg/git"
"github.com/choerodon/choerodon-cluster-agent/pkg/helm"
"github.com/choerodon/choerodon-cluster-agent/pkg/kube"
"github.com/choerodon/choerodon-cluster-agent/pkg/kubectl"
"github.com/choerodon/choerodon-cluster-agent/pkg/kubernetes"
"github.com/choerodon/choerodon-cluster-agent/pkg/polaris/config"
"github.com/choerodon/choerodon-cluster-agent/pkg/util"
"github.com/choerodon/choerodon-cluster-agent/pkg/util/cron"
operatorutil "github.com/choerodon/choerodon-cluster-agent/pkg/util/operator"
"github.com/choerodon/choerodon-cluster-agent/pkg/version"
"github.com/choerodon/choerodon-cluster-agent/pkg/websocket"
"github.com/golang/glog"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"k8s.io/client-go/util/homedir"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"net/http"
"net/http/pprof"
_ "net/http/pprof"
"os"
"os/exec"
"os/signal"
"path"
"runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
const (
defaultGitSyncTag = "agent-sync"
defaultGitDevOpsSyncTag = "devops-sync"
defaultGitNotesRef = "choerodon"
)
var (
helmCacheDir = path.Join(homedir.HomeDir(), ".cache/helm/repository")
)
type AgentOptions struct {
Listen string
HealthyPort string
UpstreamURL string
Token string
PrintVersion bool
// kubernetes controller
PlatformCode string
ConcurrentEndpointSyncs int32
ConcurrentServiceSyncs int32
ConcurrentRSSyncs int32
ConcurrentJobSyncs int32
ConcurrentDeploymentSyncs int32
ConcurrentIngressSyncs int32
ConcurrentSecretSyncs int32
ConcurrentConfigMapSyncs int32
ConcurrentPodSyncs int32
ConcurrentC7NHelmReleaseSyncs int32
ClusterId string
// git repo
gitURL string
gitBranch string
gitPath string
gitUser string
gitEmail string
gitPollInterval time.Duration
gitTimeOut time.Duration
gitSyncTag string
gitDevOpsSyncTag string
gitNotesRef string
syncInterval time.Duration
kubernetesKubectl string
statusSyncInterval time.Duration
syncAll bool
polarisFile string
clearHelmHistory bool
clearHelmCacheCron string
pprof bool
restrictedMod bool
}
func printVersion() {
glog.Info(fmt.Sprintf("Go Version: %s", runtime.Version()))
glog.Info(fmt.Sprintf("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH))
}
func NewAgentCommand(f cmdutil.Factory) *cobra.Command {
options := NewAgentOptions()
cmd := &cobra.Command{
Use: "choerodon-cluster-agent",
Long: `Environment Agent`,
Run: func(cmd *cobra.Command, args []string) {
Run(options, f)
},
}
// 给cmd绑定参数
options.BindFlags(cmd.Flags())
cmd.PersistentFlags().AddGoFlagSet(flag.CommandLine)
return cmd
}
func NewAgentOptions() *AgentOptions {
a := &AgentOptions{
Listen: "0.0.0.0:8088",
HealthyPort: "8000",
ConcurrentEndpointSyncs: 5,
ConcurrentServiceSyncs: 1,
ConcurrentRSSyncs: 1,
ConcurrentJobSyncs: 3,
ConcurrentDeploymentSyncs: 1,
ConcurrentIngressSyncs: 1,
ConcurrentSecretSyncs: 1,
ConcurrentConfigMapSyncs: 1,
ConcurrentPodSyncs: 1,
ConcurrentC7NHelmReleaseSyncs: 1,
}
return a
}
func Run(o *AgentOptions, f cmdutil.Factory) {
opts := zap.Options{
Development: false,
}
opts.BindFlags(flag.CommandLine)
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
printVersion()
model.AgentNamespace = os.Getenv("POD_NAMESPACE")
model.RestrictedModel = o.restrictedMod
model.ClusterId = o.ClusterId
if o.PrintVersion {
fmt.Println(version.GetVersion())
os.Exit(0)
}
// init a channel to receive commands
crChan := channel.NewCRChannel(100, 1000)
errChan := make(chan error, 1)
shutdown := make(chan struct{})
shutdownWg := &sync.WaitGroup{}
// graceful shutdown
defer func() {
glog.Errorf("%s", <-errChan)
close(shutdown)
shutdownWg.Wait()
glog.Info("exit in 5 seconds")
time.Sleep(5 * time.Second)
}()
// receive system int or term signal, send to err channel
go func() {
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
errChan <- fmt.Errorf("%s", <-c)
}()
// pprof
go func() {
var mux *http.ServeMux
if o.pprof {
mux = http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/heap", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
}
errChan <- http.ListenAndServe(o.Listen, mux)
}()
// 健康检查
go func() {
glog.Info("start health check server")
mux := http.ServeMux{}
mux.HandleFunc("/healthy", healthy)
mux.HandleFunc("/env_status", envStatus)
HealthyProbServer := &http.Server{Addr: fmt.Sprintf("0.0.0.0:%s", o.HealthyPort), Handler: &mux}
errChan <- HealthyProbServer.ListenAndServe()
}()
// for controller-manager
mgrs := &operatorutil.MgrList{}
cfg, _ := f.ToRESTConfig()
// 获得集群版本
discoveryClient, err := f.ToDiscoveryClient()
if err != nil {
errChan <- err
return
}
k8sVersion, err := discoveryClient.ServerVersion()
if err == nil {
model.KubernetesVersion = k8sVersion
split := strings.Split(k8sVersion.GitVersion, ".")
minorVersion, err := strconv.Atoi(split[1])
if err != nil {
errChan <- err
return
}
if minorVersion < 22 {
model.OldKubernetesVersion = true
} else {
model.OldKubernetesVersion = false
}
}
// new kubernetes clientf
kubeClient, err := kube.NewClient(f)
if err != nil {
errChan <- err
return
}
glog.Info("get kube client success")
helmClient := helm.NewClient(kubeClient, cfg)
glog.Info("init helm client success")
// 因为要缩小权限,所以这里不再校验权限
//checkKube(kubeClient.GetKubeClient())
glog.Infof("KubeClient init success.")
// 需要listen de namespaces
namespaces := agentnamespace.NewNamespaces()
glog.Info("Starting the Cmd.")
// --------------- operator sdk end ----------------- //
appClient, err := websocket.NewClient(websocket.Token(o.Token), o.UpstreamURL, crChan, o.ClusterId)
if err != nil {
errChan <- err
return
}
shutdownWg.Add(1)
go appClient.Loop(shutdown, shutdownWg)
//gitRemote := git.Remote{URL: o.gitURL}
gitConfig := git.Config{
Branch: o.gitBranch,
Path: o.gitPath,
UserName: o.gitUser,
GitUrl: o.gitURL,
UserEmail: o.gitEmail,
SyncTag: o.gitSyncTag,
DevOpsTag: o.gitDevOpsSyncTag,
NotesRef: o.gitNotesRef,
GitPollInterval: o.gitPollInterval,
}
agentctx := &agentsync.Context{
Namespaces: namespaces,
KubeClient: kubeClient,
HelmClient: helmClient,
CrChan: crChan,
StopCh: shutdown,
}
//ctx.StartControllers()
var k8s *kubernetes.Cluster
{
kubectlPath := o.kubernetesKubectl
if kubectlPath == "" {
kubectlPath, err = exec.LookPath("kubectl")
} else {
_, err = os.Stat(kubectlPath)
}
if err != nil {
errChan <- err
return
}
glog.Infof("kubectl %s", kubectlPath)
cfg, _ := f.ToRESTConfig()
kubectlApplier := kubectl.NewKubectl(kubectlPath, cfg)
kubectlDescriber := kubectl.NewKubectl(kubectlPath, cfg)
kubectlScaler := kubectl.NewKubectl(kubectlPath, cfg)
if !model.RestrictedModel {
if model.OldKubernetesVersion {
// k8s 22以下的版本使用此crd
glog.Infof("k8s version:%s use v1beta1 crd", model.KubernetesVersion)
if err := kubectlApplier.ApplySingleObj("kube-system", model.CRD_YAMLS[model.V1_BETA1]); err != nil {
glog.V(1).Info(err)
}
} else {
// k8s 22及以上的版本使用此crd
glog.Infof("k8s version:%s use v1 crd", model.KubernetesVersion)
if err := kubectlApplier.ApplySingleObj("kube-system", model.CRD_YAMLS[model.V1]); err != nil {
glog.V(1).Info(err)
}
}
helmClient.ApplyCertManagerCrd()
}
k8s = kubernetes.NewCluster(kubeClient.GetKubeClient(), kubeClient.GetV1CrdClient(), mgrs, kubectlApplier, kubectlDescriber, kubectlScaler)
}
var polarisConfig *config.Configuration
if !o.restrictedMod {
polarisConfig, err = config.ParseFile(o.polarisFile)
if err != nil {
errChan <- err
return
}
}
workerManager := agent.NewWorkerManager(
mgrs,
crChan,
kubeClient,
helmClient,
appClient,
k8s,
&model.AgentInitOptions{},
o.syncInterval,
o.statusSyncInterval,
o.gitTimeOut,
gitConfig,
agentctx,
shutdownWg,
shutdown,
o.Token,
o.PlatformCode,
o.syncAll,
polarisConfig,
o.clearHelmHistory,
)
go workerManager.Start()
glog.Infof("cron: %s", o.clearHelmCacheCron)
cron.AddCronJob(o.clearHelmCacheCron, func() {
glog.Info("start to delete helm cache")
err := os.RemoveAll(helmCacheDir)
if err != nil {
glog.Errorf("Failed to delete helm cache: %s", err.Error())
return
}
glog.Info("success to delete helm cache")
})
cron.StartCron(errChan)
}
func (o *AgentOptions) BindFlags(fs *pflag.FlagSet) {
fs.BoolVar(&o.pprof, "enable-pprof", false, "enable pprof")
fs.BoolVar(&o.restrictedMod, "restricted-mode", false, "whether cluster runs in restricted mode")
fs.StringVar(&o.clearHelmCacheCron, "clear-helm-cache-cron", "0 0 * * *", "cron jon for clear cache of helm")
fs.BoolVar(&o.PrintVersion, "version", false, "print the version number")
fs.StringVar(&o.Listen, "listen", o.Listen, "address:port to listen on")
fs.StringVar(&o.HealthyPort, "healthy-listen", o.HealthyPort, "address:port for healthy check")
fs.StringVar(&model.AgentVersion, "agent-version", "", "agent version")
fs.IntVar(&model.MaxWebsocketMessageLength, "max-websocket-message-length", 131072, "the max length of websocket message")
fs.IntVar(&model.MaxJobLogLength, "max-job-log-length", 102400, "the max length of job log")
// upstream
fs.StringVar(&o.UpstreamURL, "connect", "", "Connect to an upstream service")
fs.StringVar(&o.Token, "token", "", "Authentication token for upstream service")
fs.StringVar(&o.ClusterId, "clusterId", "0", "the env cluster id in devops")
// kubernetes controller
fs.StringVar(&o.PlatformCode, "choerodon-id", "", "choerodon platform id label")
fs.Int32Var(&o.ConcurrentEndpointSyncs, "concurrent-endpoint-syncs", o.ConcurrentEndpointSyncs, "The number of endpoint syncing operations that will be done concurrently. Larger number = faster endpoint updating, but more CPU (and network) load")
fs.Int32Var(&o.ConcurrentServiceSyncs, "concurrent-service-syncs", o.ConcurrentServiceSyncs, "The number of services that are allowed to sync concurrently. Larger number = more responsive service management, but more CPU (and network) load")
fs.Int32Var(&o.ConcurrentRSSyncs, "concurrent-replicaset-syncs", o.ConcurrentRSSyncs, "The number of replica sets that are allowed to sync concurrently. Larger number = more responsive replica management, but more CPU (and network) load")
fs.Int32Var(&o.ConcurrentJobSyncs, "concurrent-job-syncs", o.ConcurrentJobSyncs, "The number of job that are allowed to sync concurrently. Larger number = more responsive replica management, but more CPU (and network) load")
fs.Int32Var(&o.ConcurrentDeploymentSyncs, "concurrent-deployment-syncs", o.ConcurrentDeploymentSyncs, "The number of deployment objects that are allowed to sync concurrently. Larger number = more responsive deployments, but more CPU (and network) load")
fs.Int32Var(&o.ConcurrentIngressSyncs, "concurrent-ingress-syncs", o.ConcurrentIngressSyncs, "The number of ingress objects that are allowed to sync concurrently. Larger number = more responsive deployments, but more CPU (and network) load")
fs.Int32Var(&o.ConcurrentSecretSyncs, "concurrent-secret-syncs", o.ConcurrentSecretSyncs, "The number of secret objects that are allowed to sync concurrently. Larger number = more responsive deployments, but more CPU (and network) load")
fs.Int32Var(&o.ConcurrentConfigMapSyncs, "concurrent-configmap-syncs", o.ConcurrentConfigMapSyncs, "The number of config map objects that are allowed to sync concurrently. Larger number = more responsive deployments, but more CPU (and network) load")
fs.Int32Var(&o.ConcurrentPodSyncs, "concurrent-pod-syncs", o.ConcurrentPodSyncs, "The number of pod objects that are allowed to sync concurrently. Larger number = more responsive deployments, but more CPU (and network) load")
fs.Int32Var(&o.ConcurrentC7NHelmReleaseSyncs, "concurrent-c7nhelmrelease-syncs", o.ConcurrentC7NHelmReleaseSyncs, "The number of c7nhelmrelease objects that are allowed to sync concurrently. Larger number = more responsive deployments, but more CPU (and network) load")
// git repo
fs.StringVar(&o.gitURL, "git-url", "", "URL of git repo manifests")
fs.StringVar(&o.gitBranch, "git-branch", "master", "branch of git repo to use for manifests")
fs.StringVar(&o.gitPath, "git-path", ".", "path within git repo to locate manifests (relative path)")
fs.StringVar(&o.gitUser, "git-user", "Choerodon", "username to use as git committer")
fs.StringVar(&o.gitEmail, "git-email", "support@choerodon.io", "email to use as git committer")
fs.DurationVar(&o.gitPollInterval, "git-poll-interval", 5*time.Minute, "period at which to poll git repo for new commits")
fs.StringVar(&o.gitSyncTag, "git-sync-tag", defaultGitSyncTag, "tag to use to mark sync progress for this cluster")
fs.StringVar(&o.gitDevOpsSyncTag, "git-devops-sync-tag", defaultGitDevOpsSyncTag, "tag to use to mark sync progress for this cluster")
fs.StringVar(&o.gitNotesRef, "git-notes-ref", defaultGitNotesRef, "ref to use for keeping commit annotations in git notes")
fs.DurationVar(&o.syncInterval, "sync-interval", 5*time.Minute, "apply config in git to cluster at least this often, even if there are no new commits")
fs.DurationVar(&o.statusSyncInterval, "status-sync-interval", 3*time.Minute, "status sync interval")
fs.DurationVar(&o.gitTimeOut, "git-timeout", 1*time.Minute, "git time out")
fs.StringVar(&o.kubernetesKubectl, "kubernetes-kubectl", "", "Optional, explicit path to kubectl tool")
fs.BoolVar(&o.syncAll, "sync-all", false, "sync all or change")
fs.StringVar(&o.polarisFile, "polaris-file", "", "the polaris config file")
fs.BoolVar(&o.clearHelmHistory, "clear-helm-history", false, "clear helm2 release deploy history")
}
func healthy(resp http.ResponseWriter, req *http.Request) {
if model.Initialized {
resp.WriteHeader(http.StatusOK)
_, err := resp.Write([]byte("healthy"))
if err != nil {
glog.Error(err)
}
} else {
resp.WriteHeader(http.StatusServiceUnavailable)
_, err := resp.Write([]byte("unhealthy"))
if err != nil {
glog.Error(err)
}
}
}
func envStatus(resp http.ResponseWriter, req *http.Request) {
resp.WriteHeader(http.StatusOK)
_, err := resp.Write([]byte(util.GetEnvStatus()))
if err != nil {
glog.Error(err)
}
}