-
Notifications
You must be signed in to change notification settings - Fork 155
/
kubernetes.go
538 lines (477 loc) · 16.5 KB
/
kubernetes.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
// Copyright 2024 The PipeCD 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 kubernetes
import (
"context"
"encoding/json"
"fmt"
"io"
"sort"
"strings"
"time"
"go.uber.org/zap"
"github.com/pipe-cd/pipecd/pkg/app/piped/deploysource"
"github.com/pipe-cd/pipecd/pkg/app/piped/planner"
provider "github.com/pipe-cd/pipecd/pkg/app/piped/platformprovider/kubernetes"
"github.com/pipe-cd/pipecd/pkg/app/piped/platformprovider/kubernetes/resource"
"github.com/pipe-cd/pipecd/pkg/config"
"github.com/pipe-cd/pipecd/pkg/diff"
"github.com/pipe-cd/pipecd/pkg/model"
)
const (
versionUnknown = "unknown"
)
// Planner plans the deployment pipeline for kubernetes application.
type Planner struct {
}
type registerer interface {
Register(k model.ApplicationKind, p planner.Planner) error
}
// Register registers this planner into the given registerer.
func Register(r registerer) {
r.Register(model.ApplicationKind_KUBERNETES, &Planner{})
}
// Plan decides which pipeline should be used for the given input.
func (p *Planner) Plan(ctx context.Context, in planner.Input) (out planner.Output, err error) {
ds, err := in.TargetDSP.Get(ctx, io.Discard)
if err != nil {
err = fmt.Errorf("error while preparing deploy source data (%v)", err)
return
}
cfg := ds.ApplicationConfig.KubernetesApplicationSpec
if cfg == nil {
err = fmt.Errorf("missing KubernetesApplicationSpec in application configuration")
return
}
if cfg.Input.HelmChart != nil {
chartRepoName := cfg.Input.HelmChart.Repository
if chartRepoName != "" {
cfg.Input.HelmChart.Insecure = in.PipedConfig.IsInsecureChartRepository(chartRepoName)
}
}
manifestCache := provider.AppManifestsCache{
AppID: in.ApplicationID,
Cache: in.AppManifestsCache,
Logger: in.Logger,
}
// Load previous deployed manifests and new manifests to compare.
newManifests, ok := manifestCache.Get(in.Trigger.Commit.Hash)
if !ok {
// When the manifests were not in the cache we have to load them.
loader := provider.NewLoader(in.ApplicationName, ds.AppDir, ds.RepoDir, in.GitPath.ConfigFilename, cfg.Input, in.GitClient, in.Logger)
newManifests, err = loader.LoadManifests(ctx)
if err != nil {
return
}
manifestCache.Put(in.Trigger.Commit.Hash, newManifests)
}
// Determine application version from the manifests.
if version, e := determineVersion(newManifests); e != nil {
in.Logger.Warn("unable to determine version", zap.Error(e))
out.Version = versionUnknown
} else {
out.Version = version
}
if versions, e := determineVersions(newManifests); e != nil || len(versions) == 0 {
in.Logger.Warn("unable to determine versions", zap.Error(e))
out.Versions = []*model.ArtifactVersion{
{
Kind: model.ArtifactVersion_UNKNOWN,
Version: versionUnknown,
},
}
} else {
out.Versions = versions
}
autoRollback := *cfg.Input.AutoRollback
// In case the strategy has been decided by trigger.
// For example: user triggered the deployment via web console.
switch in.Trigger.SyncStrategy {
case model.SyncStrategy_QUICK_SYNC:
out.SyncStrategy = model.SyncStrategy_QUICK_SYNC
out.Stages = buildQuickSyncPipeline(autoRollback, time.Now())
out.Summary = in.Trigger.StrategySummary
return
case model.SyncStrategy_PIPELINE:
if cfg.Pipeline == nil {
err = fmt.Errorf("unable to force sync with pipeline because no pipeline was specified")
return
}
out.SyncStrategy = model.SyncStrategy_PIPELINE
out.Stages = buildProgressivePipeline(cfg.Pipeline, autoRollback, time.Now())
out.Summary = in.Trigger.StrategySummary
return
}
// If the progressive pipeline was not configured
// we have only one choise to do is applying all manifestt.
if cfg.Pipeline == nil || len(cfg.Pipeline.Stages) == 0 {
out.SyncStrategy = model.SyncStrategy_QUICK_SYNC
out.Stages = buildQuickSyncPipeline(autoRollback, time.Now())
out.Summary = "Quick sync by applying all manifests (no pipeline was configured)"
return
}
// Force to use pipeline when the alwaysUsePipeline field was configured.
if cfg.Planner.AlwaysUsePipeline {
out.SyncStrategy = model.SyncStrategy_PIPELINE
out.Stages = buildProgressivePipeline(cfg.Pipeline, autoRollback, time.Now())
out.Summary = "Sync with the specified pipeline (alwaysUsePipeline was set)"
return
}
// This deployment is triggered by a commit with the intent to perform pipeline.
// Commit Matcher will be ignored when triggered by a command.
if p := cfg.CommitMatcher.Pipeline; p != "" && in.Trigger.Commander == "" {
pipelineRegex, err := in.RegexPool.Get(p)
if err != nil {
err = fmt.Errorf("failed to compile commitMatcher.pipeline(%s): %w", p, err)
return out, err
}
if pipelineRegex.MatchString(in.Trigger.Commit.Message) {
out.SyncStrategy = model.SyncStrategy_PIPELINE
out.Stages = buildProgressivePipeline(cfg.Pipeline, autoRollback, time.Now())
out.Summary = fmt.Sprintf("Sync progressively because the commit message was matching %q", p)
return out, err
}
}
// This deployment is triggered by a commit with the intent to synchronize.
// Commit Matcher will be ignored when triggered by a command.
if s := cfg.CommitMatcher.QuickSync; s != "" && in.Trigger.Commander == "" {
syncRegex, err := in.RegexPool.Get(s)
if err != nil {
err = fmt.Errorf("failed to compile commitMatcher.sync(%s): %w", s, err)
return out, err
}
if syncRegex.MatchString(in.Trigger.Commit.Message) {
out.SyncStrategy = model.SyncStrategy_QUICK_SYNC
out.Stages = buildQuickSyncPipeline(autoRollback, time.Now())
out.Summary = fmt.Sprintf("Quick sync by applying all manifests because the commit message was matching %q", s)
return out, err
}
}
// This is the first time to deploy this application
// or it was unable to retrieve that value.
// We just apply all manifests.
if in.MostRecentSuccessfulCommitHash == "" {
out.SyncStrategy = model.SyncStrategy_QUICK_SYNC
out.Stages = buildQuickSyncPipeline(autoRollback, time.Now())
out.Summary = "Quick sync by applying all manifests because it seems this is the first deployment"
return
}
// Load manifests of the previously applied commit.
oldManifests, ok := manifestCache.Get(in.MostRecentSuccessfulCommitHash)
if !ok {
// When the manifests were not in the cache we have to load them.
var runningDs *deploysource.DeploySource
runningDs, err = in.RunningDSP.Get(ctx, io.Discard)
if err != nil {
err = fmt.Errorf("failed to prepare the running deploy source data (%v)", err)
return
}
runningCfg := runningDs.ApplicationConfig.KubernetesApplicationSpec
if runningCfg == nil {
err = fmt.Errorf("unable to find the running configuration (%v)", err)
return
}
loader := provider.NewLoader(in.ApplicationName, runningDs.AppDir, runningDs.RepoDir, in.GitPath.ConfigFilename, runningCfg.Input, in.GitClient, in.Logger)
oldManifests, err = loader.LoadManifests(ctx)
if err != nil {
err = fmt.Errorf("failed to load previously deployed manifests: %w", err)
return
}
manifestCache.Put(in.MostRecentSuccessfulCommitHash, oldManifests)
}
progressive, desc := decideStrategy(oldManifests, newManifests, cfg.Workloads, in.Logger)
out.Summary = desc
if progressive {
out.SyncStrategy = model.SyncStrategy_PIPELINE
out.Stages = buildProgressivePipeline(cfg.Pipeline, autoRollback, time.Now())
return
}
out.SyncStrategy = model.SyncStrategy_QUICK_SYNC
out.Stages = buildQuickSyncPipeline(autoRollback, time.Now())
return
}
// First up, checks to see if the workload's `spec.template` has been changed,
// and then checks if the configmap/secret's data.
func decideStrategy(olds, news []provider.Manifest, workloadRefs []config.K8sResourceReference, logger *zap.Logger) (progressive bool, desc string) {
oldWorkloads := findWorkloadManifests(olds, workloadRefs)
if len(oldWorkloads) == 0 {
desc = "Quick sync by applying all manifests because it was unable to find the currently running workloads"
return
}
newWorkloads := findWorkloadManifests(news, workloadRefs)
if len(newWorkloads) == 0 {
desc = "Quick sync by applying all manifests because it was unable to find workloads in the new manifests"
return
}
workloads := findUpdatedWorkloads(oldWorkloads, newWorkloads)
diffs := make(map[provider.ResourceKey]diff.Nodes, len(workloads))
for _, w := range workloads {
// If the workload's pod template was touched
// do progressive deployment with the specified pipeline.
diffResult, err := provider.Diff(w.old, w.new, logger)
if err != nil {
progressive = true
desc = fmt.Sprintf("Sync progressively due to an error while calculating the diff (%v)", err)
return
}
diffNodes := diffResult.Nodes()
diffs[w.new.Key] = diffNodes
templateDiffs := diffNodes.FindByPrefix("spec.template")
if len(templateDiffs) > 0 {
progressive = true
if msg, changed := checkImageChange(templateDiffs); changed {
desc = msg
return
}
desc = fmt.Sprintf("Sync progressively because pod template of workload %s was changed", w.new.Key.Name)
return
}
}
// If the config/secret was touched, we also need to do progressive
// deployment to check run with the new config/secret content.
oldConfigs := findConfigs(olds)
newConfigs := findConfigs(news)
if len(oldConfigs) > len(newConfigs) {
progressive = true
desc = fmt.Sprintf("Sync progressively because %d configmap/secret deleted", len(oldConfigs)-len(newConfigs))
return
}
if len(oldConfigs) < len(newConfigs) {
progressive = true
desc = fmt.Sprintf("Sync progressively because new %d configmap/secret added", len(newConfigs)-len(oldConfigs))
return
}
for k, oc := range oldConfigs {
nc, ok := newConfigs[k]
if !ok {
progressive = true
desc = fmt.Sprintf("Sync progressively because %s %s was deleted", oc.Key.Kind, oc.Key.Name)
return
}
result, err := provider.Diff(oc, nc, logger)
if err != nil {
progressive = true
desc = fmt.Sprintf("Sync progressively due to an error while calculating the diff (%v)", err)
return
}
if result.HasDiff() {
progressive = true
desc = fmt.Sprintf("Sync progressively because %s %s was updated", oc.Key.Kind, oc.Key.Name)
return
}
}
// Check if this is a scaling commit.
scales := make([]string, 0, len(diffs))
for k, d := range diffs {
if before, after, changed := checkReplicasChange(d); changed {
scales = append(scales, fmt.Sprintf("%s/%s from %s to %s", k.Kind, k.Name, before, after))
}
}
sort.Strings(scales)
if len(scales) > 0 {
desc = fmt.Sprintf("Quick sync to scale %s", strings.Join(scales, ", "))
return
}
desc = "Quick sync by applying all manifests"
return
}
func findWorkloadManifests(manifests []provider.Manifest, refs []config.K8sResourceReference) []provider.Manifest {
if len(refs) == 0 {
return findManifests(provider.KindDeployment, "", manifests)
}
workloads := make([]provider.Manifest, 0)
for _, ref := range refs {
kind := provider.KindDeployment
if ref.Kind != "" {
kind = ref.Kind
}
ms := findManifests(kind, ref.Name, manifests)
workloads = append(workloads, ms...)
}
return workloads
}
func findManifests(kind, name string, manifests []provider.Manifest) []provider.Manifest {
out := make([]provider.Manifest, 0, len(manifests))
for _, m := range manifests {
if m.Key.Kind != kind {
continue
}
if name != "" && m.Key.Name != name {
continue
}
out = append(out, m)
}
return out
}
type workloadPair struct {
old provider.Manifest
new provider.Manifest
}
func findUpdatedWorkloads(olds, news []provider.Manifest) []workloadPair {
pairs := make([]workloadPair, 0)
oldMap := make(map[provider.ResourceKey]provider.Manifest, len(olds))
nomalizeKey := func(k provider.ResourceKey) provider.ResourceKey {
// Ignoring APIVersion because user can upgrade to the new APIVersion for the same workload.
k.APIVersion = ""
if k.Namespace == provider.DefaultNamespace {
k.Namespace = ""
}
return k
}
for _, m := range olds {
key := nomalizeKey(m.Key)
oldMap[key] = m
}
for _, n := range news {
key := nomalizeKey(n.Key)
if o, ok := oldMap[key]; ok {
pairs = append(pairs, workloadPair{
old: o,
new: n,
})
}
}
return pairs
}
func findConfigs(manifests []provider.Manifest) map[provider.ResourceKey]provider.Manifest {
configs := make(map[provider.ResourceKey]provider.Manifest)
for _, m := range manifests {
if m.Key.IsConfigMap() {
configs[m.Key] = m
}
if m.Key.IsSecret() {
configs[m.Key] = m
}
}
return configs
}
func checkImageChange(ns diff.Nodes) (string, bool) {
const containerImageQuery = `^spec\.template\.spec\.containers\.\d+.image$`
nodes, _ := ns.Find(containerImageQuery)
if len(nodes) == 0 {
return "", false
}
images := make([]string, 0, len(ns))
for _, n := range nodes {
beforeImg := parseContainerImage(n.StringX())
afterImg := parseContainerImage(n.StringY())
if beforeImg.name == afterImg.name {
images = append(images, fmt.Sprintf("image %s from %s to %s", beforeImg.name, beforeImg.tag, afterImg.tag))
} else {
images = append(images, fmt.Sprintf("image %s:%s to %s:%s", beforeImg.name, beforeImg.tag, afterImg.name, afterImg.tag))
}
}
desc := fmt.Sprintf("Sync progressively because of updating %s", strings.Join(images, ", "))
return desc, true
}
func checkReplicasChange(ns diff.Nodes) (before, after string, changed bool) {
const replicasQuery = `^spec\.replicas$`
node, err := ns.FindOne(replicasQuery)
if err != nil {
return
}
before = node.StringX()
after = node.StringY()
changed = true
return
}
type containerImage struct {
name string
tag string
}
func parseContainerImage(image string) (img containerImage) {
parts := strings.Split(image, ":")
if len(parts) == 2 {
img.tag = parts[1]
}
paths := strings.Split(parts[0], "/")
img.name = paths[len(paths)-1]
return
}
// determineVersion decides running version of an application based on its manifests.
// Currently, this shows the tag values of using container images.
// In case only one container is used, its tag value will be returned.
//
// TODO: Add ability to configure how to determine application version.
func determineVersion(manifests []provider.Manifest) (string, error) {
images := make([]containerImage, 0)
for _, m := range manifests {
if !m.Key.IsDeployment() {
continue
}
data, err := m.MarshalJSON()
if err != nil {
return "", err
}
var d resource.Deployment
if err := json.Unmarshal(data, &d); err != nil {
return "", err
}
containers := d.Spec.Template.Spec.Containers
for _, c := range containers {
images = append(images, parseContainerImage(c.Image))
}
}
if len(images) == 0 {
return versionUnknown, nil
}
// In case the workload is containing only one container
// return only the tag name.
if len(images) == 1 {
return images[0].tag, nil
}
// In case multiple containers are used
// return version in format: "tag-1 (name-1), tag-2 (name-2)"
var b strings.Builder
b.WriteString(fmt.Sprintf("%s (%s)", images[0].tag, images[0].name))
for _, img := range images[1:] {
b.WriteString(fmt.Sprintf(", %s (%s)", img.tag, img.name))
}
return b.String(), nil
}
// determineVersions decides artifact versions of an application.
// It finds all container images that are being specified in the workload manifests then returns their names, version numbers, and urls.
func determineVersions(manifests []provider.Manifest) ([]*model.ArtifactVersion, error) {
imageMap := map[string]struct{}{}
for _, m := range manifests {
// TODO: Determine container image version from other workload kinds such as StatefulSet, Pod, Daemon, CronJob...
if !m.Key.IsDeployment() {
continue
}
data, err := m.MarshalJSON()
if err != nil {
return nil, err
}
var d resource.Deployment
if err := json.Unmarshal(data, &d); err != nil {
return nil, err
}
containers := d.Spec.Template.Spec.Containers
// Remove duplicate images on multiple manifests.
for _, c := range containers {
imageMap[c.Image] = struct{}{}
}
}
versions := make([]*model.ArtifactVersion, 0, len(imageMap))
for i := range imageMap {
image := parseContainerImage(i)
versions = append(versions, &model.ArtifactVersion{
Kind: model.ArtifactVersion_CONTAINER_IMAGE,
Version: image.tag,
Name: image.name,
Url: i,
})
}
return versions, nil
}