forked from nearmap/kcd
-
Notifications
You must be signed in to change notification settings - Fork 3
/
sync.go
400 lines (329 loc) · 12.6 KB
/
sync.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
package main
import (
"context"
"flag"
"fmt"
"os"
"time"
"github.com/golang/glog"
"github.com/pkg/errors"
"github.com/spf13/cobra"
conf "github.com/wish/kcd/config"
"github.com/wish/kcd/events"
clientset "github.com/wish/kcd/gok8s/client/clientset/versioned"
"github.com/wish/kcd/gok8s/workload"
"github.com/wish/kcd/history"
"github.com/wish/kcd/registry"
dh "github.com/wish/kcd/registry/dockerhub"
"github.com/wish/kcd/registry/ecr"
"github.com/wish/kcd/resource"
svc "github.com/wish/kcd/service"
"github.com/wish/kcd/signals"
"github.com/wish/kcd/state"
"github.com/wish/kcd/stats"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
type regRoot struct {
*cobra.Command
stats stats.Stats
stopChan chan os.Signal
params *crParams
}
type crParams struct {
tag string
registry string
providerUnused string
stats statsParams
}
func newCRCommands() *cobra.Command {
regRoot := newCRRootCommand()
regRoot.AddCommand(newKCDSyncCommand(regRoot))
regRoot.AddCommand(newTagsCommand(regRoot))
return regRoot.Command
}
func newCRRootCommand() *regRoot {
var params crParams
root := ®Root{
params: ¶ms,
Command: &cobra.Command{
Use: "registry",
Short: "Command to perform container registry operations",
Long: "Command to perform container registry operations such as registry sync, tag images etc",
},
}
root.PersistentFlags().StringVar(¶ms.tag, "tag", "", "Tag name to monitor on")
root.PersistentFlags().StringVar(¶ms.registry, "repo", "", "Container repository ARN of Docker or registry ex. nearmap/kcd")
root.PersistentFlags().StringVar(¶ms.providerUnused, "provider", "ecr", "unused")
(¶ms.stats).addFlags(root.Command)
root.PersistentPreRunE = func(cmd *cobra.Command, args []string) (err error) {
// prevent glog complaining about flags not being parsed
flag.CommandLine.Parse([]string{})
root.stats, err = root.params.stats.stats("kcd")
if err != nil {
return errors.Wrap(err, "failed to initialize stats")
}
root.stopChan = signals.SetupTwoWaySignalHandler()
return nil
}
return root
}
type crSyncParams struct {
k8sConfig string
namespace string
kcdName string
version string
}
func newKCDSyncCommand(root *regRoot) *cobra.Command {
cmd := &cobra.Command{
Use: "sync",
Short: "Polls container registry to check for deployoments",
Long: "Continuously polls container registry to check if the a service deployment needs updates and if so, performs the update via k8s APIs",
}
var params crSyncParams
cmd.Flags().StringVar(¶ms.k8sConfig, "k8s-config", "", "Path to the kube config file. Only required for running outside k8s cluster. In cluster, pods credentials are used")
cmd.Flags().StringVar(¶ms.namespace, "namespace", "", "namespace of container version resource that the syncer is based on.")
cmd.Flags().StringVar(¶ms.kcdName, "kcd", "", "name of container version resource that the syncer is based on")
cmd.Flags().StringVar(¶ms.version, "version", "", "Indicates version of kcd resources to use in CR Syncer")
cmd.PreRunE = func(cmd *cobra.Command, args []string) (err error) {
if params.kcdName == "" || params.namespace == "" {
return errors.New("kcd and namespace to watch on must be provided")
}
return nil
}
cmd.PostRun = func(cmd *cobra.Command, args []string) {
state.CleanupHealthStatus()
}
cmd.RunE = func(cmd *cobra.Command, args []string) error {
glog.V(1).Info("Starting registry Sync")
stats, err := root.params.stats.stats("kcd", params.namespace)
if err != nil {
return errors.Wrap(err, "failed to initialize stats")
}
scStatus := 0
defer stats.ServiceCheck("kcdsync.exec", "", scStatus, time.Now())
var cfg *rest.Config
if params.k8sConfig != "" {
cfg, err = clientcmd.BuildConfigFromFlags("", params.k8sConfig)
} else {
cfg, err = rest.InClusterConfig()
}
if err != nil {
scStatus = 2
glog.Errorf("Failed to get k8s config: %v", err)
return errors.Wrap(err, "error building k8s config: either run in cluster or provide config file")
}
k8sClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
scStatus = 2
glog.Errorf("Error building k8s clientset: %v", err)
return errors.Wrap(err, "Error building k8s clientset")
}
customCS, err := clientset.NewForConfig(cfg)
if err != nil {
scStatus = 2
glog.Errorf("Error building k8s container version clientset: %v", err)
return errors.Wrap(err, "Error building k8s container version clientset")
}
recorder := events.PodEventRecorder(k8sClient, params.namespace)
workloadProvider := workload.NewProvider(k8sClient, customCS, params.namespace,
conf.WithRecorder(recorder), conf.WithStats(stats))
resourceProvider := resource.NewK8sProvider(params.namespace, customCS, workloadProvider)
kcd, err := customCS.CustomV1().KCDs(params.namespace).Get(context.TODO(), params.kcdName, metav1.GetOptions{})
if err != nil {
scStatus = 2
glog.Errorf("Failed to find CV resource in namespace=%s, name=%s, error=%v", params.namespace, params.kcdName, err)
return errors.Wrap(err, "Failed to find CV resource")
}
// CRD does not allow us to specify default type on OpenAPISpec
// TODO: this needs a better strategy but hacking it for now
//
if kcd.Spec.VersionSyntax == "" {
kcd.Spec.VersionSyntax = ecr.VersionRegex
}
var registryProvider registry.Provider
switch registry.ProviderByRepo(kcd.Spec.ImageRepo) {
case "ecr":
registryProvider, err = ecr.NewECR(kcd.Spec.ImageRepo, kcd.Spec.VersionSyntax, stats)
case "dockerhub":
registryProvider, err = dh.NewDHV2(kcd.Spec.ImageRepo, kcd.Spec.VersionSyntax, dh.WithStats(stats))
}
if err != nil {
glog.Errorf("Failed to create registry provider in namespace=%s for kcd name=%s, error=%v",
params.namespace, params.kcdName, err)
return errors.Wrap(err, "Failed to create registry provider")
}
historyProvider := history.NewProvider(k8sClient, stats)
crSyncer, err := resource.NewSyncer(resourceProvider, workloadProvider, registryProvider, historyProvider, kcd,
conf.WithRecorder(recorder), conf.WithStats(stats))
if err != nil {
glog.Errorf("Failed to create syncer in namespace=%s for kcd name=%s, error=%v",
params.namespace, params.kcdName, err)
return errors.Wrap(err, "Failed to create syncer")
}
glog.V(1).Infof("Starting registry syncer with namespace=%s for kcd name=%s, error=%v",
params.namespace, params.kcdName, err)
stats.ServiceCheck("kcdsync.exec", "", scStatus, time.Now())
go func() {
crSyncer.Start()
}()
<-root.stopChan
if err = crSyncer.Stop(); err != nil {
glog.Errorf("error received while stopping state machine: %v", err)
}
glog.V(1).Info("kcdsync Server gracefully stopped")
return nil
}
status := &cobra.Command{
Use: "status",
Short: "Checks whether sync was run recently",
Long: "Checks whether sync was run recently",
}
var by time.Duration
status.Flags().DurationVar(&by, "by", time.Duration(int64(time.Minute*5)), "Duration to check sync for ")
status.RunE = func(cmd *cobra.Command, args []string) error {
glog.V(4).Info("Performing health status check")
if err := state.CheckHealth(by); err != nil {
glog.Errorf("health status returned error: %v", err)
return err
}
glog.V(4).Info("health status check was successful")
return nil
}
cmd.AddCommand(status)
return cmd
}
type regTagParams struct {
tags []string
version string
username string
pwd string
verPat string
}
// newTagsCommand is CLI interface to managing tags on registry images
func newTagsCommand(root *regRoot) *cobra.Command {
cmd := &cobra.Command{
Use: "tags",
Short: "Manages tags of registry repository",
Long: "Manages adds/removes tags on registry repositories",
}
var crProvider registry.Tagger
var params regTagParams
cmd.PersistentFlags().StringSliceVar(¶ms.tags, "tags", nil, "list of tags that needs to be added or removed")
cmd.PersistentFlags().StringVar(¶ms.verPat, "version-pattern", ecr.VersionRegex, "Regex pattern for container version")
cmd.PersistentFlags().StringVar(¶ms.version, "version", "", "sha/version tag of registry image that is being tagged")
cmd.PersistentFlags().StringVar(¶ms.username, "username", "", "username of dockerhub registry")
cmd.PersistentFlags().StringVar(¶ms.pwd, "passsword", "", "password of user of dockerhub registry")
cmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) (err error) {
root.stats, err = root.params.stats.stats("kcdtagger")
if err != nil {
return errors.Wrap(err, "failed to initialize stats")
}
switch registry.ProviderByRepo(root.params.registry) {
case "ecr":
crProvider, err = ecr.NewECR(root.params.registry, params.verPat, root.stats)
case "dockerhub":
crProvider, err = dh.NewDHV2(root.params.registry, params.verPat, dh.WithStats(root.stats))
}
if err != nil {
return err
}
return nil
}
addTagCmd := &cobra.Command{
Use: "add",
Short: "Add tag to image in given registry repository",
Long: "Add tag to image in given registry repository",
}
addTagCmd.PreRunE = func(cmd *cobra.Command, args []string) (err error) {
if root.params.registry == "" || params.tags == nil || len(params.tags) == 0 || params.version == "" {
return errors.New("registry repository name/URI and registry image version is required")
}
return nil
}
addTagCmd.RunE = func(cmd *cobra.Command, args []string) error {
return crProvider.Add(params.version, params.tags...)
}
rmTagCmd := &cobra.Command{
Use: "remove",
Short: "Remove tag to image in given registry repository",
Long: "Remove tag to image in given registry repository",
}
rmTagCmd.PreRunE = func(cmd *cobra.Command, args []string) (err error) {
if root.params.registry == "" || params.tags == nil || len(params.tags) == 0 {
return errors.New("registry repository name/URI and tags are required")
}
return nil
}
rmTagCmd.RunE = func(cmd *cobra.Command, args []string) error {
return crProvider.Remove(params.tags...)
}
getTagCmd := &cobra.Command{
Use: "get",
Short: "get tags of image by its version tagin given registry repository",
Long: "Remove tag to image in given registry repository",
}
getTagCmd.PreRunE = func(cmd *cobra.Command, args []string) (err error) {
if root.params.registry == "" || params.version == "" {
return errors.New("registry repository name/URI and version is required")
}
return nil
}
getTagCmd.RunE = func(cmd *cobra.Command, args []string) error {
ts, err := crProvider.Get(params.version)
if err != nil {
return err
}
fmt.Printf("Found tags %s on requested registry repository of image %s \n", ts, params.version)
return nil
}
cmd.AddCommand(addTagCmd)
cmd.AddCommand(rmTagCmd)
cmd.AddCommand(getTagCmd)
return cmd
}
// newCVListCommand is CLI interface to list the current status of KCD resource definitions
func newCVCommand() *cobra.Command {
var k8sConfig string
cmd := &cobra.Command{
Use: "rd",
Short: "Manages current status (version and status) of deployments managed by KCD resources",
Long: "Manages current status (version and status) of deployments managed by KCD resources",
}
cmd.PersistentFlags().StringVar(&k8sConfig, "k8s-config", "", "Path to the kube config file. Only required for running outside k8s cluster. In cluster, pods credentials are used")
listCmd := &cobra.Command{
Use: "get",
Short: "Get current status (version and status) of deployments managed by KCD resources",
Long: "Get current status (version and status) of deployments managed by KCD resources",
}
listCmd.RunE = func(cmd *cobra.Command, args []string) error {
var cfg *rest.Config
var err error
if k8sConfig != "" {
cfg, err = clientcmd.BuildConfigFromFlags("", k8sConfig)
} else {
cfg, err = rest.InClusterConfig()
}
if err != nil {
glog.Errorf("Failed to get k8s config: %v", err)
return errors.Wrap(err, "Error building k8s configs either run in cluster or provide config file via k8s-config arg")
}
k8sClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
glog.Errorf("Error building k8s clientset: %v", err)
return errors.Wrap(err, "Error building k8s clientset")
}
customClient, err := clientset.NewForConfig(cfg)
if err != nil {
glog.Errorf("Error building k8s container version clientset: %v", err)
return errors.Wrap(err, "Error building k8s container version clientset")
}
workloadProvider := workload.NewProvider(k8sClient, customClient, "")
resourceProvider := resource.NewK8sProvider("", customClient, workloadProvider)
return svc.AllKCDs(os.Stdout, "json", "", resourceProvider, false)
}
cmd.AddCommand(listCmd)
return cmd
}