Users/jysin/pm feedback changes v1.2 (#100)

* Changed dockerfile, manifest, helmchart links and README
This commit is contained in:
Jyotsna 2021-01-07 12:52:48 +05:30 committed by GitHub
parent 87674d7272
commit d1dd574643
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 238 additions and 232 deletions

View File

@ -1,218 +1,221 @@
"use strict"; "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.isHttpUrl = exports.getCurrentTime = exports.getRandomInt = exports.sleep = exports.getDeploymentConfig = exports.annotateChildPods = exports.getWorkflowFilePath = exports.getLastSuccessfulRunSha = exports.checkForErrors = exports.isEqual = exports.getExecutableExtension = void 0; exports.getNormalizedPath = exports.isHttpUrl = exports.getCurrentTime = exports.getRandomInt = exports.sleep = exports.getDeploymentConfig = exports.annotateChildPods = exports.getWorkflowFilePath = exports.getLastSuccessfulRunSha = exports.checkForErrors = exports.isEqual = exports.getExecutableExtension = void 0;
const os = require("os"); const os = require("os");
const core = require("@actions/core"); const core = require("@actions/core");
const githubClient_1 = require("../githubClient"); const githubClient_1 = require("../githubClient");
const httpClient_1 = require("./httpClient"); const httpClient_1 = require("./httpClient");
const inputParams = require("../input-parameters"); const inputParams = require("../input-parameters");
const docker_object_model_1 = require("../docker-object-model"); const docker_object_model_1 = require("../docker-object-model");
const io = require("@actions/io"); const io = require("@actions/io");
function getExecutableExtension() { function getExecutableExtension() {
if (os.type().match(/^Win/)) { if (os.type().match(/^Win/)) {
return '.exe'; return '.exe';
} }
return ''; return '';
} }
exports.getExecutableExtension = getExecutableExtension; exports.getExecutableExtension = getExecutableExtension;
function isEqual(str1, str2, ignoreCase) { function isEqual(str1, str2, ignoreCase) {
if (str1 == null && str2 == null) { if (str1 == null && str2 == null) {
return true; return true;
} }
if (str1 == null || str2 == null) { if (str1 == null || str2 == null) {
return false; return false;
} }
if (ignoreCase) { if (ignoreCase) {
return str1.toUpperCase() === str2.toUpperCase(); return str1.toUpperCase() === str2.toUpperCase();
} }
else { else {
return str1 === str2; return str1 === str2;
} }
} }
exports.isEqual = isEqual; exports.isEqual = isEqual;
function checkForErrors(execResults, warnIfError) { function checkForErrors(execResults, warnIfError) {
if (execResults.length !== 0) { if (execResults.length !== 0) {
let stderr = ''; let stderr = '';
execResults.forEach(result => { execResults.forEach(result => {
if (result && result.stderr) { if (result && result.stderr) {
if (result.code !== 0) { if (result.code !== 0) {
stderr += result.stderr + '\n'; stderr += result.stderr + '\n';
} }
else { else {
core.warning(result.stderr); core.warning(result.stderr);
} }
} }
}); });
if (stderr.length > 0) { if (stderr.length > 0) {
if (warnIfError) { if (warnIfError) {
core.warning(stderr.trim()); core.warning(stderr.trim());
} }
else { else {
throw new Error(stderr.trim()); throw new Error(stderr.trim());
} }
} }
} }
} }
exports.checkForErrors = checkForErrors; exports.checkForErrors = checkForErrors;
function getLastSuccessfulRunSha(kubectl, namespaceName, annotationKey) { function getLastSuccessfulRunSha(kubectl, namespaceName, annotationKey) {
try { try {
const result = kubectl.getResource('namespace', namespaceName); const result = kubectl.getResource('namespace', namespaceName);
if (result) { if (result) {
if (result.stderr) { if (result.stderr) {
core.warning(`${result.stderr}`); core.warning(`${result.stderr}`);
return process.env.GITHUB_SHA; return process.env.GITHUB_SHA;
} }
else if (result.stdout) { else if (result.stdout) {
const annotationsSet = JSON.parse(result.stdout).metadata.annotations; const annotationsSet = JSON.parse(result.stdout).metadata.annotations;
if (annotationsSet && annotationsSet[annotationKey]) { if (annotationsSet && annotationsSet[annotationKey]) {
return JSON.parse(annotationsSet[annotationKey].replace(/'/g, '"')).commit; return JSON.parse(annotationsSet[annotationKey].replace(/'/g, '"')).commit;
} }
else { else {
return 'NA'; return 'NA';
} }
} }
} }
} }
catch (ex) { catch (ex) {
core.warning(`Failed to get commits from cluster. ${JSON.stringify(ex)}`); core.warning(`Failed to get commits from cluster. ${JSON.stringify(ex)}`);
return ''; return '';
} }
} }
exports.getLastSuccessfulRunSha = getLastSuccessfulRunSha; exports.getLastSuccessfulRunSha = getLastSuccessfulRunSha;
function getWorkflowFilePath(githubToken) { function getWorkflowFilePath(githubToken) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
let workflowFilePath = process.env.GITHUB_WORKFLOW; let workflowFilePath = process.env.GITHUB_WORKFLOW;
if (!workflowFilePath.startsWith('.github/workflows/')) { if (!workflowFilePath.startsWith('.github/workflows/')) {
const githubClient = new githubClient_1.GitHubClient(process.env.GITHUB_REPOSITORY, githubToken); const githubClient = new githubClient_1.GitHubClient(process.env.GITHUB_REPOSITORY, githubToken);
const response = yield githubClient.getWorkflows(); const response = yield githubClient.getWorkflows();
if (response) { if (response) {
if (response.statusCode == httpClient_1.StatusCodes.OK if (response.statusCode == httpClient_1.StatusCodes.OK
&& response.body && response.body
&& response.body.total_count) { && response.body.total_count) {
if (response.body.total_count > 0) { if (response.body.total_count > 0) {
for (let workflow of response.body.workflows) { for (let workflow of response.body.workflows) {
if (process.env.GITHUB_WORKFLOW === workflow.name) { if (process.env.GITHUB_WORKFLOW === workflow.name) {
workflowFilePath = workflow.path; workflowFilePath = workflow.path;
break; break;
} }
} }
} }
} }
else if (response.statusCode != httpClient_1.StatusCodes.OK) { else if (response.statusCode != httpClient_1.StatusCodes.OK) {
core.debug(`An error occured while getting list of workflows on the repo. Statuscode: ${response.statusCode}, StatusMessage: ${response.statusMessage}`); core.debug(`An error occured while getting list of workflows on the repo. Statuscode: ${response.statusCode}, StatusMessage: ${response.statusMessage}`);
} }
} }
else { else {
core.warning(`Failed to get response from workflow list API`); core.warning(`Failed to get response from workflow list API`);
} }
} }
return Promise.resolve(workflowFilePath); return Promise.resolve(workflowFilePath);
}); });
} }
exports.getWorkflowFilePath = getWorkflowFilePath; exports.getWorkflowFilePath = getWorkflowFilePath;
function annotateChildPods(kubectl, resourceType, resourceName, annotationKeyValStr, allPods) { function annotateChildPods(kubectl, resourceType, resourceName, annotationKeyValStr, allPods) {
const commandExecutionResults = []; const commandExecutionResults = [];
let owner = resourceName; let owner = resourceName;
if (resourceType.toLowerCase().indexOf('deployment') > -1) { if (resourceType.toLowerCase().indexOf('deployment') > -1) {
owner = kubectl.getNewReplicaSet(resourceName); owner = kubectl.getNewReplicaSet(resourceName);
} }
if (allPods && allPods.items && allPods.items.length > 0) { if (allPods && allPods.items && allPods.items.length > 0) {
allPods.items.forEach((pod) => { allPods.items.forEach((pod) => {
const owners = pod.metadata.ownerReferences; const owners = pod.metadata.ownerReferences;
if (owners) { if (owners) {
owners.forEach(ownerRef => { owners.forEach(ownerRef => {
if (ownerRef.name === owner) { if (ownerRef.name === owner) {
commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, annotationKeyValStr)); commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, annotationKeyValStr));
} }
}); });
} }
}); });
} }
return commandExecutionResults; return commandExecutionResults;
} }
exports.annotateChildPods = annotateChildPods; exports.annotateChildPods = annotateChildPods;
function getDeploymentConfig() { function getDeploymentConfig() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const inputManifestFiles = inputParams.manifests || []; let helmChartPaths = (process.env.HELM_CHART_PATHS && process.env.HELM_CHART_PATHS.split(';').filter(path => path != "")) || [];
const helmChartPaths = (process.env.HELM_CHART_PATHS && process.env.HELM_CHART_PATHS.split('\n').filter(path => path != "")) || []; helmChartPaths = helmChartPaths.map(helmchart => getNormalizedPath(helmchart.trim()));
const imageNames = inputParams.containers || []; let inputManifestFiles = inputParams.manifests || [];
let imageDockerfilePathMap = {}; if (!helmChartPaths.length) {
//Fetching from image label if available inputManifestFiles = inputManifestFiles.map(manifestFile => getNormalizedPath(manifestFile));
for (const image of imageNames) { }
let imageConfig, imageInspectResult; const imageNames = inputParams.containers || [];
try { let imageDockerfilePathMap = {};
imageDockerfilePathMap[image] = yield getDockerfilePath(image); //Fetching from image label if available
} for (const image of imageNames) {
catch (ex) { try {
core.warning(`Failed to get dockerfile path for image ${image.toString()} | ` + ex); imageDockerfilePathMap[image] = yield getDockerfilePath(image);
} }
} catch (ex) {
const deploymentConfig = { core.warning(`Failed to get dockerfile path for image ${image.toString()} | ` + ex);
manifestFilePaths: inputManifestFiles, }
helmChartFilePaths: helmChartPaths, }
dockerfilePaths: imageDockerfilePathMap const deploymentConfig = {
}; manifestFilePaths: inputManifestFiles,
return Promise.resolve(deploymentConfig); helmChartFilePaths: helmChartPaths,
}); dockerfilePaths: imageDockerfilePathMap
} };
exports.getDeploymentConfig = getDeploymentConfig; return Promise.resolve(deploymentConfig);
function sleep(timeout) { });
return new Promise(resolve => setTimeout(resolve, timeout)); }
} exports.getDeploymentConfig = getDeploymentConfig;
exports.sleep = sleep; function sleep(timeout) {
function getRandomInt(max) { return new Promise(resolve => setTimeout(resolve, timeout));
return Math.floor(Math.random() * Math.floor(max)); }
} exports.sleep = sleep;
exports.getRandomInt = getRandomInt; function getRandomInt(max) {
function getCurrentTime() { return Math.floor(Math.random() * Math.floor(max));
return new Date().getTime(); }
} exports.getRandomInt = getRandomInt;
exports.getCurrentTime = getCurrentTime; function getCurrentTime() {
function checkDockerPath() { return new Date().getTime();
return __awaiter(this, void 0, void 0, function* () { }
let dockerPath = yield io.which('docker', false); exports.getCurrentTime = getCurrentTime;
if (!dockerPath) { function checkDockerPath() {
throw new Error('Docker is not installed.'); return __awaiter(this, void 0, void 0, function* () {
} let dockerPath = yield io.which('docker', false);
}); if (!dockerPath) {
} throw new Error('Docker is not installed.');
function getDockerfilePath(image) { }
return __awaiter(this, void 0, void 0, function* () { });
let imageConfig, imageInspectResult; }
var dockerExec = new docker_object_model_1.DockerExec('docker'); function getDockerfilePath(image) {
yield checkDockerPath(); return __awaiter(this, void 0, void 0, function* () {
dockerExec.pull(image, [], true); let imageConfig, imageInspectResult;
imageInspectResult = dockerExec.inspect(image, [], true); var dockerExec = new docker_object_model_1.DockerExec('docker');
imageConfig = JSON.parse(imageInspectResult)[0]; yield checkDockerPath();
const DOCKERFILE_PATH_LABEL_KEY = 'dockerfile-path'; dockerExec.pull(image, [], true);
const ref = process.env.GITHUB_REF && process.env.GITHUB_REF.replace('refs/heads/', '').replace('refs/tags/', ''); imageInspectResult = dockerExec.inspect(image, [], true);
let pathValue = ''; imageConfig = JSON.parse(imageInspectResult)[0];
if (imageConfig) { const DOCKERFILE_PATH_LABEL_KEY = 'dockerfile-path';
if ((imageConfig.Config) && (imageConfig.Config.Labels) && (imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY])) { let pathValue = '';
const pathLabel = imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY]; if (imageConfig) {
if (!isHttpUrl(pathLabel)) { //if it is relative filepath convert to link from current repo if ((imageConfig.Config) && (imageConfig.Config.Labels) && (imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY])) {
let pathLink = `https://github.com/${process.env.GITHUB_REPOSITORY}/blob/${ref}/${pathLabel}`; const pathLabel = imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY];
pathValue = pathLink; pathValue = getNormalizedPath(pathLabel);
} }
else { }
pathValue = pathLabel; return pathValue;
} });
} }
} function isHttpUrl(url) {
return pathValue; const HTTP_REGEX = /^https?:\/\/.*$/;
}); return HTTP_REGEX.test(url);
} }
function isHttpUrl(url) { exports.isHttpUrl = isHttpUrl;
const HTTP_REGEX = /^https?:\/\/.*$/; function getNormalizedPath(pathValue) {
return HTTP_REGEX.test(url); if (!isHttpUrl(pathValue)) { //if it is not an http url then convert to link from current repo and commit
} return `https://github.com/${process.env.GITHUB_REPOSITORY}/blob/${process.env.GITHUB_SHA}/${pathValue}`;
exports.isHttpUrl = isHttpUrl; }
return pathValue;
}
exports.getNormalizedPath = getNormalizedPath;

View File

@ -138,15 +138,19 @@ export function annotateChildPods(kubectl: Kubectl, resourceType: string, resour
export async function getDeploymentConfig(): Promise<DeploymentConfig> { export async function getDeploymentConfig(): Promise<DeploymentConfig> {
const inputManifestFiles = inputParams.manifests || []; let helmChartPaths: string[] = (process.env.HELM_CHART_PATHS && process.env.HELM_CHART_PATHS.split(';').filter(path => path != "")) || [];
const helmChartPaths = (process.env.HELM_CHART_PATHS && process.env.HELM_CHART_PATHS.split('\n').filter(path => path != "")) || []; helmChartPaths = helmChartPaths.map(helmchart => getNormalizedPath(helmchart.trim()));
let inputManifestFiles: string[] = inputParams.manifests || [];
if (!helmChartPaths.length) {
inputManifestFiles = inputManifestFiles.map(manifestFile => getNormalizedPath(manifestFile));
}
const imageNames = inputParams.containers || []; const imageNames = inputParams.containers || [];
let imageDockerfilePathMap: { [id: string]: string; } = {}; let imageDockerfilePathMap: { [id: string]: string; } = {};
//Fetching from image label if available //Fetching from image label if available
for (const image of imageNames) { for (const image of imageNames) {
let imageConfig: any, imageInspectResult: string;
try { try {
imageDockerfilePathMap[image] = await getDockerfilePath(image); imageDockerfilePathMap[image] = await getDockerfilePath(image);
} }
@ -160,7 +164,6 @@ export async function getDeploymentConfig(): Promise<DeploymentConfig> {
helmChartFilePaths: helmChartPaths, helmChartFilePaths: helmChartPaths,
dockerfilePaths: imageDockerfilePathMap dockerfilePaths: imageDockerfilePathMap
}; };
return Promise.resolve(deploymentConfig); return Promise.resolve(deploymentConfig);
} }
@ -192,18 +195,11 @@ async function getDockerfilePath(image: any): Promise<string> {
imageInspectResult = dockerExec.inspect(image, [], true); imageInspectResult = dockerExec.inspect(image, [], true);
imageConfig = JSON.parse(imageInspectResult)[0]; imageConfig = JSON.parse(imageInspectResult)[0];
const DOCKERFILE_PATH_LABEL_KEY = 'dockerfile-path'; const DOCKERFILE_PATH_LABEL_KEY = 'dockerfile-path';
const ref: string = process.env.GITHUB_REF && process.env.GITHUB_REF.replace('refs/heads/', '').replace('refs/tags/', '');
let pathValue: string = ''; let pathValue: string = '';
if (imageConfig) { if (imageConfig) {
if ((imageConfig.Config) && (imageConfig.Config.Labels) && (imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY])) { if ((imageConfig.Config) && (imageConfig.Config.Labels) && (imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY])) {
const pathLabel = imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY]; const pathLabel = imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY];
if (!isHttpUrl(pathLabel)) { //if it is relative filepath convert to link from current repo pathValue = getNormalizedPath(pathLabel);
let pathLink: string = `https://github.com/${process.env.GITHUB_REPOSITORY}/blob/${ref}/${pathLabel}`;
pathValue = pathLink;
}
else {
pathValue = pathLabel;
}
} }
} }
return pathValue; return pathValue;
@ -212,4 +208,11 @@ async function getDockerfilePath(image: any): Promise<string> {
export function isHttpUrl(url: string) { export function isHttpUrl(url: string) {
const HTTP_REGEX = /^https?:\/\/.*$/; const HTTP_REGEX = /^https?:\/\/.*$/;
return HTTP_REGEX.test(url); return HTTP_REGEX.test(url);
} }
export function getNormalizedPath(pathValue: string) {
if (!isHttpUrl(pathValue)) { //if it is not an http url then convert to link from current repo and commit
return `https://github.com/${process.env.GITHUB_REPOSITORY}/blob/${process.env.GITHUB_SHA}/${pathValue}`;
}
return pathValue;
}