Skip to content

Commit 2c8e7a0

Browse files
authored
Merge pull request #49 from Azure/users/koushdey/fixAnnotateNamespace
Checks in annotateNamespace to not error during failed annotation
2 parents af5108b + b3381a2 commit 2c8e7a0

File tree

3 files changed

+61
-25
lines changed

3 files changed

+61
-25
lines changed

__tests__/run.test.ts

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import * as io from '@actions/io';
88
import * as toolCache from '@actions/tool-cache';
99
import * as fileHelper from '../src/utilities/files-helper';
1010
import { workflowAnnotations } from '../src/constants';
11-
import * as utility from '../src/utilities/utility';
1211
import * as inputParam from '../src/input-parameters';
1312

1413
import { Kubectl, Resource } from '../src/kubectl-object-model';
@@ -21,7 +20,6 @@ const os = require("os");
2120

2221
const coreMock = mocked(core, true);
2322
const ioMock = mocked(io, true);
24-
const utilityMock = mocked(utility, true);
2523
const inputParamMock = mocked(inputParam, true);
2624

2725
const toolCacheMock = mocked(toolCache, true);
@@ -43,7 +41,7 @@ const getNamespaceMock = {
4341

4442
const resources: Resource[] = [{ type: "Deployment", name: "AppName" }];
4543

46-
beforeAll(() => {
44+
beforeEach(() => {
4745
deploymentYaml = fs.readFileSync(path.join(__dirname, 'manifests', 'deployment.yml'), 'utf8');
4846

4947
process.env["KUBECONFIG"] = 'kubeConfig';
@@ -274,6 +272,31 @@ test("deployment - deploy() - Annotate resources", async () => {
274272
expect(kubeCtl.annotate).toBeCalledTimes(2);
275273
});
276274

275+
test("deployment - deploy() - Skip Annotate namespace", async () => {
276+
process.env['GITHUB_REPOSITORY'] = 'test1Repo';
277+
const KubernetesManifestUtilityMock = mocked(KubernetesManifestUtility, true);
278+
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
279+
const KubernetesObjectUtilityMock = mocked(KubernetesObjectUtility, true);
280+
KubernetesObjectUtilityMock.getResources = jest.fn().mockReturnValue(resources);
281+
const fileHelperMock = mocked(fileHelper, true);
282+
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue(["~/Deployment_testapp_currentTimestamp"]);
283+
const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any;
284+
kubeCtl.apply = jest.fn().mockReturnValue("");
285+
kubeCtl.getResource = jest.fn().mockReturnValue(getNamespaceMock);
286+
kubeCtl.getAllPods = jest.fn().mockReturnValue(getAllPodsMock);
287+
kubeCtl.getNewReplicaSet = jest.fn().mockReturnValue("testpod-776cbc86f9");
288+
kubeCtl.annotateFiles = jest.fn().mockReturnValue("");
289+
kubeCtl.annotate = jest.fn().mockReturnValue("");
290+
291+
const consoleOutputSpy = jest.spyOn(process.stdout, "write").mockImplementation();
292+
293+
//Invoke and assert
294+
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
295+
expect(kubeCtl.annotateFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp"], workflowAnnotations, true);
296+
expect(kubeCtl.annotate).toBeCalledTimes(1);
297+
expect(consoleOutputSpy).toHaveBeenNthCalledWith(2, `##[debug]Skipping 'annotate namespace' as namespace annotated by other workflow` + os.EOL)
298+
});
299+
277300
test("deployment - deploy() - Annotate resources failed", async () => {
278301
//Mocks
279302
inputParamMock.forceDeployment = true;

lib/utilities/utility.js

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ function checkForErrors(execResults, warnIfError) {
3030
if (execResults.length !== 0) {
3131
let stderr = '';
3232
execResults.forEach(result => {
33-
if (result.stderr) {
33+
if (result && result.stderr) {
3434
if (result.code !== 0) {
3535
stderr += result.stderr + '\n';
3636
}
@@ -40,7 +40,7 @@ function checkForErrors(execResults, warnIfError) {
4040
}
4141
});
4242
if (stderr.length > 0) {
43-
if (!!warnIfError) {
43+
if (warnIfError) {
4444
core.warning(stderr.trim());
4545
}
4646
else {
@@ -56,10 +56,10 @@ function annotateChildPods(kubectl, resourceType, resourceName, allPods) {
5656
if (resourceType.toLowerCase().indexOf('deployment') > -1) {
5757
owner = kubectl.getNewReplicaSet(resourceName);
5858
}
59-
if (!!allPods && !!allPods.items && allPods.items.length > 0) {
59+
if (allPods && allPods.items && allPods.items.length > 0) {
6060
allPods.items.forEach((pod) => {
6161
const owners = pod.metadata.ownerReferences;
62-
if (!!owners) {
62+
if (owners) {
6363
owners.forEach(ownerRef => {
6464
if (ownerRef.name === owner) {
6565
commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, constants_1.workflowAnnotations, true));
@@ -72,15 +72,21 @@ function annotateChildPods(kubectl, resourceType, resourceName, allPods) {
7272
}
7373
exports.annotateChildPods = annotateChildPods;
7474
function annotateNamespace(kubectl, namespaceName) {
75-
let annotate = true;
7675
const result = kubectl.getResource('namespace', namespaceName);
77-
this.checkForErrors([result]);
78-
const annotationsSet = JSON.parse(result.stdout).metadata.annotations;
79-
if (!!annotationsSet && !!annotationsSet.runUri && annotationsSet.runUri.indexOf(process.env['GITHUB_REPOSITORY']) == -1) {
80-
annotate = false;
81-
core.debug(`Skipping 'annotate namespace' as namespace annotated by other workflow`);
76+
if (!result) {
77+
return { code: -1, stderr: 'Failed to get resource' };
8278
}
83-
if (annotate) {
79+
else if (result && result.stderr) {
80+
return result;
81+
}
82+
if (result && result.stdout) {
83+
const annotationsSet = JSON.parse(result.stdout).metadata.annotations;
84+
if (annotationsSet && annotationsSet.runUri) {
85+
if (annotationsSet.runUri.indexOf(process.env['GITHUB_REPOSITORY']) == -1) {
86+
core.debug(`Skipping 'annotate namespace' as namespace annotated by other workflow`);
87+
return { code: 0, stdout: '' };
88+
}
89+
}
8490
return kubectl.annotate('namespace', namespaceName, constants_1.workflowAnnotations, true);
8591
}
8692
}

src/utilities/utility.ts

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export function checkForErrors(execResults: IExecSyncResult[], warnIfError?: boo
3232
if (execResults.length !== 0) {
3333
let stderr = '';
3434
execResults.forEach(result => {
35-
if (result.stderr) {
35+
if (result && result.stderr) {
3636
if (result.code !== 0) {
3737
stderr += result.stderr + '\n';
3838
} else {
@@ -41,7 +41,7 @@ export function checkForErrors(execResults: IExecSyncResult[], warnIfError?: boo
4141
}
4242
});
4343
if (stderr.length > 0) {
44-
if (!!warnIfError) {
44+
if (warnIfError) {
4545
core.warning(stderr.trim());
4646
} else {
4747
throw new Error(stderr.trim());
@@ -57,10 +57,10 @@ export function annotateChildPods(kubectl: Kubectl, resourceType: string, resour
5757
owner = kubectl.getNewReplicaSet(resourceName);
5858
}
5959

60-
if (!!allPods && !!allPods.items && allPods.items.length > 0) {
60+
if (allPods && allPods.items && allPods.items.length > 0) {
6161
allPods.items.forEach((pod) => {
6262
const owners = pod.metadata.ownerReferences;
63-
if (!!owners) {
63+
if (owners) {
6464
owners.forEach(ownerRef => {
6565
if (ownerRef.name === owner) {
6666
commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, workflowAnnotations, true));
@@ -74,15 +74,22 @@ export function annotateChildPods(kubectl: Kubectl, resourceType: string, resour
7474
}
7575

7676
export function annotateNamespace(kubectl: Kubectl, namespaceName: string): IExecSyncResult {
77-
let annotate = true;
7877
const result = kubectl.getResource('namespace', namespaceName);
79-
this.checkForErrors([result]);
80-
const annotationsSet = JSON.parse(result.stdout).metadata.annotations;
81-
if (!!annotationsSet && !!annotationsSet.runUri && annotationsSet.runUri.indexOf(process.env['GITHUB_REPOSITORY']) == -1) {
82-
annotate = false;
83-
core.debug(`Skipping 'annotate namespace' as namespace annotated by other workflow`);
78+
if (!result) {
79+
return { code: -1, stderr: 'Failed to get resource' } as IExecSyncResult;
8480
}
85-
if (annotate) {
81+
else if (result && result.stderr) {
82+
return result;
83+
}
84+
85+
if (result && result.stdout) {
86+
const annotationsSet = JSON.parse(result.stdout).metadata.annotations;
87+
if (annotationsSet && annotationsSet.runUri) {
88+
if (annotationsSet.runUri.indexOf(process.env['GITHUB_REPOSITORY']) == -1) {
89+
core.debug(`Skipping 'annotate namespace' as namespace annotated by other workflow`);
90+
return { code: 0, stdout: '' } as IExecSyncResult;
91+
}
92+
}
8693
return kubectl.annotate('namespace', namespaceName, workflowAnnotations, true);
8794
}
8895
}

0 commit comments

Comments
 (0)