-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
DeploymentHelper.ts
317 lines (281 loc) · 13.5 KB
/
DeploymentHelper.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
'use strict';
import * as fs from 'fs';
import * as path from 'path';
import * as tl from 'azure-pipelines-task-lib/task';
import * as yaml from 'js-yaml';
import * as canaryDeploymentHelper from '../utils/CanaryDeploymentHelper';
import * as KubernetesObjectUtility from '../utils/KubernetesObjectUtility';
import * as constants from '../models/constants';
import * as TaskInputParameters from '../models/TaskInputParameters';
import * as models from '../models/constants';
import * as fileHelper from '../utils/FileHelper';
import * as utils from '../utils/utilities';
import { IExecSyncResult } from 'azure-pipelines-task-lib/toolrunner';
import { Kubectl, Resource } from 'kubernetes-common-v2/kubectl-object-model';
import { isEqual, StringComparer } from './StringComparison';
import { getDeploymentMetadata, getPublishDeploymentRequestUrl, isDeploymentEntity, getManifestUrls } from 'kubernetes-common-v2/image-metadata-helper';
import { WebRequest, WebResponse, sendRequest } from 'utility-common-v2/restutilities';
const publishPipelineMetadata = tl.getVariable("PUBLISH_PIPELINE_METADATA");
export async function deploy(kubectl: Kubectl, manifestFilePaths: string[], deploymentStrategy: string) {
// get manifest files
let inputManifestFiles: string[] = getManifestFiles(manifestFilePaths);
// artifact substitution
inputManifestFiles = updateContainerImagesInManifestFiles(inputManifestFiles, TaskInputParameters.containers);
// imagePullSecrets addition
inputManifestFiles = updateImagePullSecretsInManifestFiles(inputManifestFiles, TaskInputParameters.imagePullSecrets);
// deployment
const deployedManifestFiles = deployManifests(inputManifestFiles, kubectl, isCanaryDeploymentStrategy(deploymentStrategy));
// check manifest stability
const resourceTypes: Resource[] = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([constants.DiscoveryAndLoadBalancerResource.service]));
await checkManifestStability(kubectl, resourceTypes);
// print ingress resources
const ingressResources: Resource[] = KubernetesObjectUtility.getResources(deployedManifestFiles, [constants.DiscoveryAndLoadBalancerResource.ingress]);
ingressResources.forEach(ingressResource => {
kubectl.getResource(constants.DiscoveryAndLoadBalancerResource.ingress, ingressResource.name);
});
// annotate resources
const allPods = JSON.parse((kubectl.getAllPods()).stdout);
annotateResources(deployedManifestFiles, kubectl, resourceTypes, allPods);
// Capture and push deployment metadata only if the variable 'PUBLISH_PIPELINE_METADATA' is set to true,
// and deployment strategy is not specified (because for Canary/SMI we do not replace actual deployment objects)
if (publishPipelineMetadata && publishPipelineMetadata.toLowerCase() == "true" && !isCanaryDeploymentStrategy(deploymentStrategy)) {
try {
const clusterInfo = kubectl.getClusterInfo().stdout;
captureAndPushDeploymentMetadata(inputManifestFiles, allPods, deploymentStrategy, clusterInfo, manifestFilePaths);
}
catch (e) {
tl.warning("Capturing deployment metadata failed with error: " + e);
}
}
}
function getManifestFiles(manifestFilePaths: string[]): string[] {
const files: string[] = utils.getManifestFiles(manifestFilePaths);
if (files == null || files.length === 0) {
throw (tl.loc('ManifestFileNotFound', manifestFilePaths));
}
return files;
}
function deployManifests(files: string[], kubectl: Kubectl, isCanaryDeploymentStrategy: boolean): string[] {
let result;
if (isCanaryDeploymentStrategy) {
const canaryDeploymentOutput = canaryDeploymentHelper.deployCanary(kubectl, files);
result = canaryDeploymentOutput.result;
files = canaryDeploymentOutput.newFilePaths;
} else {
result = kubectl.apply(files);
}
utils.checkForErrors([result]);
return files;
}
async function checkManifestStability(kubectl: Kubectl, resources: Resource[]): Promise<void> {
const rolloutStatusResults = [];
const numberOfResources = resources.length;
for (let i = 0; i < numberOfResources; i++) {
const resource = resources[i];
if (models.workloadTypesWithRolloutStatus.indexOf(resource.type.toLowerCase()) >= 0) {
rolloutStatusResults.push(kubectl.checkRolloutStatus(resource.type, resource.name));
}
if (isEqual(resource.type, constants.KubernetesWorkload.pod, StringComparer.OrdinalIgnoreCase)) {
try {
await checkPodStatus(kubectl, resource.name);
} catch (ex) {
tl.warning(tl.loc('CouldNotDeterminePodStatus', JSON.stringify(ex)));
}
}
if (isEqual(resource.type, constants.DiscoveryAndLoadBalancerResource.service, StringComparer.OrdinalIgnoreCase)) {
try {
const service = getService(kubectl, resource.name);
const spec = service.spec;
const status = service.status;
if (isEqual(spec.type, constants.ServiceTypes.loadBalancer, StringComparer.OrdinalIgnoreCase)) {
if(!isLoadBalancerIPAssigned(status)) {
await waitForServiceExternalIPAssignment(kubectl, resource.name);
}
console.log(tl.loc('ServiceExternalIP', resource.name, status.loadBalancer.ingress[0].ip));
}
} catch (ex) {
tl.warning(tl.loc('CouldNotDetermineServiceStatus', resource.name, JSON.stringify(ex)));
}
}
}
utils.checkForErrors(rolloutStatusResults);
}
function annotateResources(files: string[], kubectl: Kubectl, resourceTypes: Resource[], allPods: any) {
const annotateResults: IExecSyncResult[] = [];
annotateResults.push(kubectl.annotateFiles(files, constants.pipelineAnnotations, true));
resourceTypes.forEach(resource => {
if (resource.type.toUpperCase() !== models.KubernetesWorkload.pod.toUpperCase()) {
utils.annotateChildPods(kubectl, resource.type, resource.name, allPods)
.forEach(execResult => annotateResults.push(execResult));
}
});
utils.checkForErrors(annotateResults, true);
}
function updateContainerImagesInManifestFiles(filePaths: string[], containers: string[]): string[] {
if (!!containers && containers.length > 0) {
const newFilePaths = [];
const tempDirectory = fileHelper.getTempDirectory();
filePaths.forEach((filePath: string) => {
let contents = fs.readFileSync(filePath).toString();
containers.forEach((container: string) => {
let imageName = container.split(':')[0];
if (imageName.indexOf('@') > 0) {
imageName = imageName.split('@')[0];
}
if (contents.indexOf(imageName) > 0) {
contents = utils.substituteImageNameInSpecFile(contents, imageName, container);
}
});
const fileName = path.join(tempDirectory, path.basename(filePath));
fs.writeFileSync(
path.join(fileName),
contents
);
newFilePaths.push(fileName);
});
return newFilePaths;
}
return filePaths;
}
function updateImagePullSecretsInManifestFiles(filePaths: string[], imagePullSecrets: string[]): string[] {
if (!!imagePullSecrets && imagePullSecrets.length > 0) {
const newObjectsList = [];
filePaths.forEach((filePath: string) => {
const fileContents = fs.readFileSync(filePath).toString();
yaml.safeLoadAll(fileContents, function (inputObject: any) {
if (!!inputObject && !!inputObject.kind) {
const kind = inputObject.kind;
if (KubernetesObjectUtility.isWorkloadEntity(kind)) {
KubernetesObjectUtility.updateImagePullSecrets(inputObject, imagePullSecrets, false);
}
newObjectsList.push(inputObject);
}
});
});
tl.debug('New K8s objects after addin imagePullSecrets are :' + JSON.stringify(newObjectsList));
const newFilePaths = fileHelper.writeObjectsToFile(newObjectsList);
return newFilePaths;
}
return filePaths;
}
function captureAndPushDeploymentMetadata(filePaths: string[], allPods: any, deploymentStrategy: string, clusterInfo: any, manifestFilePaths: string[]) {
const requestUrl = getPublishDeploymentRequestUrl();
let metadata = {};
filePaths.forEach((filePath: string) => {
const fileContents = fs.readFileSync(filePath).toString();
yaml.safeLoadAll(fileContents, function (inputObject: any) {
if (!!inputObject && inputObject.kind && isDeploymentEntity(inputObject.kind)) {
metadata = getDeploymentMetadata(inputObject, allPods, deploymentStrategy, clusterInfo, getManifestUrls(manifestFilePaths));
pushDeploymentDataToEvidenceStore(JSON.stringify(metadata), requestUrl).then((result) => {
tl.debug("DeploymentDetailsApiResponse: " + JSON.stringify(result));
}, (error) => {
tl.warning("publishToImageMetadataStore failed with error: " + error);
});
}
});
});
}
async function pushDeploymentDataToEvidenceStore(requestBody: string, requestUrl: string): Promise<any> {
const request = new WebRequest();
const accessToken: string = tl.getEndpointAuthorizationParameter('SYSTEMVSSCONNECTION', 'ACCESSTOKEN', false);
request.uri = requestUrl;
request.method = 'POST';
request.body = requestBody;
request.headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + accessToken
};
tl.debug("requestUrl: " + requestUrl);
tl.debug("requestBody: " + requestBody);
try {
tl.debug("Sending request for pushing deployment data to Image meta data store");
const response = await sendRequest(request);
return response;
}
catch (error) {
tl.debug("Unable to push to deployment details to Artifact Store, Error: " + error);
}
return Promise.resolve();
}
function isCanaryDeploymentStrategy(deploymentStrategy: string): boolean {
return deploymentStrategy != null && deploymentStrategy.toUpperCase() === canaryDeploymentHelper.CANARY_DEPLOYMENT_STRATEGY.toUpperCase();
}
async function checkPodStatus(kubectl: Kubectl, podName: string): Promise<void> {
const sleepTimeout = 10 * 1000; // 10 seconds
const iterations = 60; // 60 * 10 seconds timeout = 10 minutes max timeout
let podStatus;
for (let i = 0; i < iterations; i++) {
await sleep(sleepTimeout);
tl.debug(`Polling for pod status: ${podName}`);
podStatus = getPodStatus(kubectl, podName);
if (podStatus.phase && podStatus.phase !== 'Pending' && podStatus.phase !== 'Unknown') {
break;
}
}
podStatus = getPodStatus(kubectl, podName);
switch (podStatus.phase) {
case 'Succeeded':
case 'Running':
if (isPodReady(podStatus)) {
console.log(`pod/${podName} is successfully rolled out`);
}
break;
case 'Pending':
if (!isPodReady(podStatus)) {
tl.warning(`pod/${podName} rollout status check timedout`);
}
break;
case 'Failed':
tl.error(`pod/${podName} rollout failed`);
break;
default:
tl.warning(`pod/${podName} rollout status: ${podStatus.phase}`);
}
}
function getPodStatus(kubectl: Kubectl, podName: string): any {
const podResult = kubectl.getResource('pod', podName);
utils.checkForErrors([podResult]);
const podStatus = JSON.parse(podResult.stdout).status;
tl.debug(`Pod Status: ${JSON.stringify(podStatus)}`);
return podStatus;
}
function isPodReady(podStatus: any): boolean {
let allContainersAreReady = true;
podStatus.containerStatuses.forEach(container => {
if (container.ready === false) {
console.log(`'${container.name}' status: ${JSON.stringify(container.state)}`);
allContainersAreReady = false;
}
});
if (!allContainersAreReady) {
tl.warning(tl.loc('AllContainersNotInReadyState'));
}
return allContainersAreReady;
}
function getService(kubectl: Kubectl, serviceName) {
const serviceResult = kubectl.getResource(constants.DiscoveryAndLoadBalancerResource.service, serviceName);
utils.checkForErrors([serviceResult]);
return JSON.parse(serviceResult.stdout);
}
async function waitForServiceExternalIPAssignment(kubectl: Kubectl, serviceName: string): Promise<void> {
const sleepTimeout = 10 * 1000; // 10 seconds
const iterations = 18; // 18 * 10 seconds timeout = 3 minutes max timeout
for (let i = 0; i < iterations; i++) {
console.log(tl.loc('waitForServiceIpAssignment', serviceName));
await sleep(sleepTimeout);
let status = getService(kubectl, serviceName).status;
if (isLoadBalancerIPAssigned(status)) {
return;
}
}
tl.warning(tl.loc('waitForServiceIpAssignmentTimedOut', serviceName));
}
function isLoadBalancerIPAssigned(status: any) {
if (status && status.loadBalancer && status.loadBalancer.ingress && status.loadBalancer.ingress.length > 0) {
return true;
}
return false;
}
function sleep(timeout: number) {
return new Promise(resolve => setTimeout(resolve, timeout));
}