-
Notifications
You must be signed in to change notification settings - Fork 135
/
canary.go
221 lines (191 loc) · 7.46 KB
/
canary.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
// Copyright 2020 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"
"fmt"
"strings"
provider "github.com/pipe-cd/pipe/pkg/app/piped/cloudprovider/kubernetes"
"github.com/pipe-cd/pipe/pkg/config"
"github.com/pipe-cd/pipe/pkg/model"
)
const (
canaryVariant = "canary"
addedCanaryResourcesMetadataKey = "canary-resources"
)
func (e *Executor) ensureCanaryRollout(ctx context.Context) model.StageStatus {
var (
commitHash = e.Deployment.Trigger.Commit.Hash
options = e.StageConfig.K8sCanaryRolloutStageOptions
)
if options == nil {
e.LogPersister.AppendErrorf("Malformed configuration for stage %s", e.Stage.Name)
return model.StageStatus_STAGE_FAILURE
}
// Load the manifests at the triggered commit.
e.LogPersister.AppendInfof("Loading manifests at commit %s for handling", commitHash)
manifests, err := e.loadManifests(ctx)
if err != nil {
e.LogPersister.AppendErrorf("Failed while loading manifests (%v)", err)
return model.StageStatus_STAGE_FAILURE
}
e.LogPersister.AppendSuccessf("Successfully loaded %d manifests", len(manifests))
if len(manifests) == 0 {
e.LogPersister.AppendError("This application has no Kubernetes manifests to handle")
return model.StageStatus_STAGE_FAILURE
}
// Find and generate workload & service manifests for CANARY variant.
canaryManifests, err := e.generateCanaryManifests(manifests, *options)
if err != nil {
e.LogPersister.AppendErrorf("Unable to generate manifests for CANARY variant (%v)", err)
return model.StageStatus_STAGE_FAILURE
}
// Add builtin annotations for tracking application live state.
e.addBuiltinAnnontations(canaryManifests, canaryVariant, commitHash)
// Store added resource keys into metadata for cleaning later.
addedResources := make([]string, 0, len(canaryManifests))
for _, m := range canaryManifests {
addedResources = append(addedResources, m.Key.String())
}
metadata := strings.Join(addedResources, ",")
err = e.MetadataStore.Set(ctx, addedCanaryResourcesMetadataKey, metadata)
if err != nil {
e.LogPersister.AppendErrorf("Unable to save deployment metadata (%v)", err)
return model.StageStatus_STAGE_FAILURE
}
// Start rolling out the resources for CANARY variant.
e.LogPersister.AppendInfo("Start rolling out CANARY variant...")
if err := e.applyManifests(ctx, canaryManifests); err != nil {
return model.StageStatus_STAGE_FAILURE
}
e.LogPersister.AppendSuccess("Successfully rolled out CANARY variant")
return model.StageStatus_STAGE_SUCCESS
}
func (e *Executor) ensureCanaryClean(ctx context.Context) model.StageStatus {
value, ok := e.MetadataStore.Get(addedCanaryResourcesMetadataKey)
if !ok {
e.LogPersister.AppendError("Unable to determine the applied CANARY resources")
return model.StageStatus_STAGE_FAILURE
}
resources := strings.Split(value, ",")
if err := e.removeCanaryResources(ctx, resources); err != nil {
return model.StageStatus_STAGE_FAILURE
}
return model.StageStatus_STAGE_SUCCESS
}
func (e *Executor) removeCanaryResources(ctx context.Context, resources []string) error {
if len(resources) == 0 {
return nil
}
var (
workloadKeys = make([]provider.ResourceKey, 0)
serviceKeys = make([]provider.ResourceKey, 0)
)
for _, r := range resources {
key, err := provider.DecodeResourceKey(r)
if err != nil {
e.LogPersister.AppendErrorf("Had an error while decoding CANARY resource key: %s, %v", r, err)
continue
}
if key.IsWorkload() {
workloadKeys = append(workloadKeys, key)
} else {
serviceKeys = append(serviceKeys, key)
}
}
// We delete the service first to close all incoming connections.
e.LogPersister.AppendInfo("Starting finding and deleting service resources of CANARY variant")
if err := e.deleteResources(ctx, serviceKeys); err != nil {
return err
}
// Next, delete all workloads.
e.LogPersister.AppendInfo("Starting finding and deleting workload resources of CANARY variant")
if err := e.deleteResources(ctx, workloadKeys); err != nil {
return err
}
return nil
}
func (e *Executor) generateCanaryManifests(manifests []provider.Manifest, opts config.K8sCanaryRolloutStageOptions) ([]provider.Manifest, error) {
var (
workloadKind, workloadName string
serviceName string
generateService bool
canaryManifests []provider.Manifest
suffix = canaryVariant
)
// Apply the specified configuration if they are present.
if sc := e.config.CanaryVariant; sc != nil {
var ok bool
if sc.Suffix != "" {
suffix = sc.Suffix
}
generateService = sc.Service.Create
workloadKind, workloadName, ok = config.ParseVariantResourceReference(sc.Workload.Reference)
if !ok {
return nil, fmt.Errorf("malformed workload reference: %s", sc.Workload.Reference)
}
_, serviceName, ok = config.ParseVariantResourceReference(sc.Service.Reference)
if !ok {
return nil, fmt.Errorf("malformed service reference: %s", sc.Service.Reference)
}
}
if workloadKind == "" {
workloadKind = provider.KindDeployment
}
workloads := findManifests(workloadKind, workloadName, manifests)
if len(workloads) == 0 {
return nil, fmt.Errorf("unable to find any workload manifests for CANARY variant")
}
// Find service manifests and duplicate them for CANARY variant.
if generateService {
services := findManifests(provider.KindService, serviceName, manifests)
if len(services) == 0 {
return nil, fmt.Errorf("unable to find any service for name=%q", serviceName)
}
// Because the loaded maninests are read-only
// so we duplicate them to avoid updating the shared manifests data in cache.
services = duplicateManifests(services, "")
generatedServices, err := generateVariantServiceManifests(services, canaryVariant, suffix)
if err != nil {
return nil, err
}
canaryManifests = append(canaryManifests, generatedServices...)
}
// Find config map manifests and duplicate them for CANARY variant.
configMaps := findConfigMapManifests(manifests)
configMaps = duplicateManifests(configMaps, suffix)
canaryManifests = append(canaryManifests, configMaps...)
// Find secret manifests and duplicate them for CANARY variant.
secrets := findSecretManifests(manifests)
secrets = duplicateManifests(secrets, suffix)
canaryManifests = append(canaryManifests, secrets...)
// Generate new workload manifests for CANARY variant.
// The generated ones will mount to the new ConfigMaps and Secrets.
replicasCalculator := func(cur *int32) int32 {
if cur == nil {
return 1
}
num := opts.Replicas.Calculate(int(*cur), 1)
return int32(num)
}
// We don't need to duplicate the workload manifests
// because generateVariantWorkloadManifests function is already making a duplicate while decoding.
// workloads = duplicateManifests(workloads, suffix)
generatedWorkloads, err := generateVariantWorkloadManifests(workloads, configMaps, secrets, canaryVariant, suffix, replicasCalculator)
if err != nil {
return nil, err
}
canaryManifests = append(canaryManifests, generatedWorkloads...)
return canaryManifests, nil
}