-
Notifications
You must be signed in to change notification settings - Fork 105
/
smiCanaryHelper.ts
383 lines (345 loc) · 12.7 KB
/
smiCanaryHelper.ts
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
import {Kubectl} from '../../types/kubectl'
import * as core from '@actions/core'
import * as fs from 'fs'
import * as yaml from 'js-yaml'
import * as fileHelper from '../../utilities/fileUtils'
import * as kubectlUtils from '../../utilities/trafficSplitUtils'
import * as canaryDeploymentHelper from './canaryHelper'
import * as podCanaryHelper from './podCanaryHelper'
import {isDeploymentEntity, isServiceEntity} from '../../types/kubernetesTypes'
import {checkForErrors} from '../../utilities/kubectlUtils'
import {inputAnnotations} from '../../inputUtils'
import {DeployResult} from '../../types/deployResult'
import {K8sObject} from '../../types/k8sObject'
const TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX = '-workflow-rollout'
const TRAFFIC_SPLIT_OBJECT = 'TrafficSplit'
export async function deploySMICanary(
filePaths: string[],
kubectl: Kubectl,
onlyDeployStable: boolean = false
): Promise<DeployResult> {
const canaryReplicasInput = core.getInput('baseline-and-canary-replicas')
let canaryReplicaCount
let calculateReplicas = true
if (canaryReplicasInput !== '') {
canaryReplicaCount = parseInt(canaryReplicasInput)
calculateReplicas = false
core.debug(
`read replica count ${canaryReplicaCount} from input: ${canaryReplicasInput}`
)
}
if (canaryReplicaCount < 0 && canaryReplicaCount > 100)
throw Error('Baseline-and-canary-replicas must be between 0 and 100')
const newObjectsList = []
for await (const filePath of filePaths) {
try {
const fileContents = fs.readFileSync(filePath).toString()
const inputObjects: K8sObject[] = yaml.loadAll(
fileContents
) as K8sObject[]
for (const inputObject of inputObjects) {
const name = inputObject.metadata.name
const kind = inputObject.kind
if (!onlyDeployStable && isDeploymentEntity(kind)) {
if (calculateReplicas) {
// calculate for each object
const percentage = parseInt(
core.getInput('percentage', {required: true})
)
canaryReplicaCount =
podCanaryHelper.calculateReplicaCountForCanary(
inputObject,
percentage
)
core.debug(`calculated replica count ${canaryReplicaCount}`)
}
core.debug('Creating canary object')
const newCanaryObject =
canaryDeploymentHelper.getNewCanaryResource(
inputObject,
canaryReplicaCount
)
newObjectsList.push(newCanaryObject)
const stableObject = await canaryDeploymentHelper.fetchResource(
kubectl,
kind,
canaryDeploymentHelper.getStableResourceName(name)
)
if (stableObject) {
core.debug(
`Stable object found for ${kind} ${name}. Creating baseline objects`
)
const newBaselineObject =
canaryDeploymentHelper.getBaselineDeploymentFromStableDeployment(
stableObject,
canaryReplicaCount
)
newObjectsList.push(newBaselineObject)
}
} else if (isDeploymentEntity(kind)) {
core.debug(
`creating stable deployment with ${inputObject.spec.replicas} replicas`
)
const stableDeployment =
canaryDeploymentHelper.getStableResource(inputObject)
newObjectsList.push(stableDeployment)
} else {
// Update non deployment entity or stable deployment as it is
newObjectsList.push(inputObject)
}
}
} catch (error) {
core.error(`Failed to process file at ${filePath}: ${error.message}`)
throw error
}
}
core.debug(
`deploying canary objects with SMI: \n ${JSON.stringify(newObjectsList)}`
)
const newFilePaths = fileHelper.writeObjectsToFile(newObjectsList)
const forceDeployment = core.getInput('force').toLowerCase() === 'true'
const result = await kubectl.apply(newFilePaths, forceDeployment)
const svcDeploymentFiles = await createCanaryService(kubectl, filePaths)
newFilePaths.push(...svcDeploymentFiles)
return {execResult: result, manifestFiles: newFilePaths}
}
async function createCanaryService(
kubectl: Kubectl,
filePaths: string[]
): Promise<string[]> {
const newObjectsList = []
const trafficObjectsList: string[] = []
for (const filePath of filePaths) {
try {
const fileContents = fs.readFileSync(filePath).toString()
const parsedYaml: K8sObject[] = yaml.loadAll(
fileContents
) as K8sObject[]
for (const inputObject of parsedYaml) {
const name = inputObject.metadata.name
const kind = inputObject.kind
if (isServiceEntity(kind)) {
core.debug(`Creating services for ${kind} ${name}`)
const newCanaryServiceObject =
canaryDeploymentHelper.getNewCanaryResource(inputObject)
newObjectsList.push(newCanaryServiceObject)
const newBaselineServiceObject =
canaryDeploymentHelper.getNewBaselineResource(inputObject)
newObjectsList.push(newBaselineServiceObject)
const stableObject = await canaryDeploymentHelper.fetchResource(
kubectl,
kind,
canaryDeploymentHelper.getStableResourceName(name)
)
if (!stableObject) {
const newStableServiceObject =
canaryDeploymentHelper.getStableResource(inputObject)
newObjectsList.push(newStableServiceObject)
core.debug('Creating the traffic object for service: ' + name)
const trafficObject = await createTrafficSplitManifestFile(
kubectl,
name,
0,
0,
1000
)
trafficObjectsList.push(trafficObject)
} else {
let updateTrafficObject = true
const trafficObject =
await canaryDeploymentHelper.fetchResource(
kubectl,
TRAFFIC_SPLIT_OBJECT,
getTrafficSplitResourceName(name)
)
if (trafficObject) {
const trafficJObject = JSON.parse(
JSON.stringify(trafficObject)
)
if (trafficJObject?.spec?.backends) {
trafficJObject.spec.backends.forEach((s) => {
if (
s.service ===
canaryDeploymentHelper.getCanaryResourceName(
name
) &&
s.weight === '1000m'
) {
core.debug('Update traffic objcet not required')
updateTrafficObject = false
}
})
}
}
if (updateTrafficObject) {
core.debug(
'Stable service object present so updating the traffic object for service: ' +
name
)
trafficObjectsList.push(
await updateTrafficSplitObject(kubectl, name)
)
}
}
}
}
} catch (error) {
core.error(`Failed to process file at ${filePath}: ${error.message}`)
throw error
}
}
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList)
manifestFiles.push(...trafficObjectsList)
const forceDeployment = core.getInput('force').toLowerCase() === 'true'
const result = await kubectl.apply(manifestFiles, forceDeployment)
checkForErrors([result])
return manifestFiles
}
export async function redirectTrafficToCanaryDeployment(
kubectl: Kubectl,
manifestFilePaths: string[]
) {
await adjustTraffic(kubectl, manifestFilePaths, 0, 1000)
}
export async function redirectTrafficToStableDeployment(
kubectl: Kubectl,
manifestFilePaths: string[]
): Promise<string[]> {
return await adjustTraffic(kubectl, manifestFilePaths, 1000, 0)
}
async function adjustTraffic(
kubectl: Kubectl,
manifestFilePaths: string[],
stableWeight: number,
canaryWeight: number
) {
if (!manifestFilePaths || manifestFilePaths?.length == 0) {
return
}
const trafficSplitManifests = []
for (const filePath of manifestFilePaths) {
try {
const fileContents = fs.readFileSync(filePath).toString()
const parsedYaml: K8sObject[] = yaml.loadAll(
fileContents
) as K8sObject[]
for (const inputObject of parsedYaml) {
const name = inputObject.metadata.name
const kind = inputObject.kind
if (isServiceEntity(kind)) {
trafficSplitManifests.push(
await createTrafficSplitManifestFile(
kubectl,
name,
stableWeight,
0,
canaryWeight
)
)
}
}
} catch (error) {
core.error(`Failed to process file at ${filePath}: ${error.message}`)
throw error
}
}
if (trafficSplitManifests.length <= 0) {
return
}
const forceDeployment = core.getInput('force').toLowerCase() === 'true'
const result = await kubectl.apply(trafficSplitManifests, forceDeployment)
checkForErrors([result])
return trafficSplitManifests
}
async function updateTrafficSplitObject(
kubectl: Kubectl,
serviceName: string
): Promise<string> {
const percentage = parseInt(core.getInput('percentage', {required: true}))
if (percentage < 0 || percentage > 100)
throw Error('Percentage must be between 0 and 100')
const percentageWithMuliplier = percentage * 10
const baselineAndCanaryWeight = percentageWithMuliplier / 2
const stableDeploymentWeight = 1000 - percentageWithMuliplier
core.debug(
'Creating the traffic object with canary weight: ' +
baselineAndCanaryWeight +
', baseline weight: ' +
baselineAndCanaryWeight +
', stable weight: ' +
stableDeploymentWeight
)
return await createTrafficSplitManifestFile(
kubectl,
serviceName,
stableDeploymentWeight,
baselineAndCanaryWeight,
baselineAndCanaryWeight
)
}
async function createTrafficSplitManifestFile(
kubectl: Kubectl,
serviceName: string,
stableWeight: number,
baselineWeight: number,
canaryWeight: number
): Promise<string> {
const smiObjectString = await getTrafficSplitObject(
kubectl,
serviceName,
stableWeight,
baselineWeight,
canaryWeight
)
const manifestFile = fileHelper.writeManifestToFile(
smiObjectString,
TRAFFIC_SPLIT_OBJECT,
serviceName
)
if (!manifestFile) {
throw new Error('Unable to create traffic split manifest file')
}
return manifestFile
}
let trafficSplitAPIVersion = ''
async function getTrafficSplitObject(
kubectl: Kubectl,
name: string,
stableWeight: number,
baselineWeight: number,
canaryWeight: number
): Promise<string> {
// cached version
if (!trafficSplitAPIVersion) {
trafficSplitAPIVersion =
await kubectlUtils.getTrafficSplitAPIVersion(kubectl)
}
return JSON.stringify({
apiVersion: trafficSplitAPIVersion,
kind: 'TrafficSplit',
metadata: {
name: getTrafficSplitResourceName(name),
annotations: inputAnnotations
},
spec: {
backends: [
{
service: canaryDeploymentHelper.getStableResourceName(name),
weight: stableWeight
},
{
service: canaryDeploymentHelper.getBaselineResourceName(name),
weight: baselineWeight
},
{
service: canaryDeploymentHelper.getCanaryResourceName(name),
weight: canaryWeight
}
],
service: name
}
})
}
function getTrafficSplitResourceName(name: string) {
return name + TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX
}