Committing changes in js files

This commit is contained in:
Ajinkya 2020-09-17 13:02:22 +05:30
parent 309ae69061
commit 68ed252e91
17 changed files with 2495 additions and 2495 deletions

View File

@ -1,107 +1,107 @@
'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.promote = void 0; exports.promote = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const deploymentHelper = require("../utilities/strategy-helpers/deployment-helper"); const deploymentHelper = require("../utilities/strategy-helpers/deployment-helper");
const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper"); const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper");
const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper"); const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper");
const utils = require("../utilities/manifest-utilities"); const utils = require("../utilities/manifest-utilities");
const TaskInputParameters = require("../input-parameters"); const TaskInputParameters = require("../input-parameters");
const manifest_utilities_1 = require("../utilities/manifest-utilities"); const manifest_utilities_1 = require("../utilities/manifest-utilities");
const KubernetesObjectUtility = require("../utilities/resource-object-utility"); const KubernetesObjectUtility = require("../utilities/resource-object-utility");
const models = require("../constants"); const models = require("../constants");
const KubernetesManifestUtility = require("../utilities/manifest-stability-utility"); const KubernetesManifestUtility = require("../utilities/manifest-stability-utility");
const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper"); const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper");
const blue_green_helper_2 = require("../utilities/strategy-helpers/blue-green-helper"); const blue_green_helper_2 = require("../utilities/strategy-helpers/blue-green-helper");
const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper"); const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper");
const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper"); const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper");
const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper"); const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper");
const kubectl_object_model_1 = require("../kubectl-object-model"); const kubectl_object_model_1 = require("../kubectl-object-model");
function promote() { function promote() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true); const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true);
if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) { if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
yield promoteCanary(kubectl); yield promoteCanary(kubectl);
} }
else if (blue_green_helper_2.isBlueGreenDeploymentStrategy()) { else if (blue_green_helper_2.isBlueGreenDeploymentStrategy()) {
yield promoteBlueGreen(kubectl); yield promoteBlueGreen(kubectl);
} }
else { else {
core.debug('Strategy is not canary or blue-green deployment. Invalid request.'); core.debug('Strategy is not canary or blue-green deployment. Invalid request.');
throw ('InvalidPromotetActionDeploymentStrategy'); throw ('InvalidPromotetActionDeploymentStrategy');
} }
}); });
} }
exports.promote = promote; exports.promote = promote;
function promoteCanary(kubectl) { function promoteCanary(kubectl) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
let includeServices = false; let includeServices = false;
if (canaryDeploymentHelper.isSMICanaryStrategy()) { if (canaryDeploymentHelper.isSMICanaryStrategy()) {
includeServices = true; includeServices = true;
// In case of SMI traffic split strategy when deployment is promoted, first we will redirect traffic to // In case of SMI traffic split strategy when deployment is promoted, first we will redirect traffic to
// Canary deployment, then update stable deployment and then redirect traffic to stable deployment // Canary deployment, then update stable deployment and then redirect traffic to stable deployment
core.debug('Redirecting traffic to canary deployment'); core.debug('Redirecting traffic to canary deployment');
SMICanaryDeploymentHelper.redirectTrafficToCanaryDeployment(kubectl, TaskInputParameters.manifests); SMICanaryDeploymentHelper.redirectTrafficToCanaryDeployment(kubectl, TaskInputParameters.manifests);
core.debug('Deploying input manifests with SMI canary strategy'); core.debug('Deploying input manifests with SMI canary strategy');
yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None'); yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None');
core.debug('Redirecting traffic to stable deployment'); core.debug('Redirecting traffic to stable deployment');
SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests); SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests);
} }
else { else {
core.debug('Deploying input manifests'); core.debug('Deploying input manifests');
yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None'); yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None');
} }
core.debug('Deployment strategy selected is Canary. Deleting canary and baseline workloads.'); core.debug('Deployment strategy selected is Canary. Deleting canary and baseline workloads.');
try { try {
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices); canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices);
} }
catch (ex) { catch (ex) {
core.warning('Exception occurred while deleting canary and baseline workloads. Exception: ' + ex); core.warning('Exception occurred while deleting canary and baseline workloads. Exception: ' + ex);
} }
}); });
} }
function promoteBlueGreen(kubectl) { function promoteBlueGreen(kubectl) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
// updated container images and pull secrets // updated container images and pull secrets
let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(TaskInputParameters.manifests); let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(TaskInputParameters.manifests);
const manifestObjects = blue_green_helper_1.getManifestObjects(inputManifestFiles); const manifestObjects = blue_green_helper_1.getManifestObjects(inputManifestFiles);
core.debug('deleting old deployment and making new ones'); core.debug('deleting old deployment and making new ones');
let result; let result;
if (blue_green_helper_2.isIngressRoute()) { if (blue_green_helper_2.isIngressRoute()) {
result = yield ingress_blue_green_helper_1.promoteBlueGreenIngress(kubectl, manifestObjects); result = yield ingress_blue_green_helper_1.promoteBlueGreenIngress(kubectl, manifestObjects);
} }
else if (blue_green_helper_2.isSMIRoute()) { else if (blue_green_helper_2.isSMIRoute()) {
result = yield smi_blue_green_helper_1.promoteBlueGreenSMI(kubectl, manifestObjects); result = yield smi_blue_green_helper_1.promoteBlueGreenSMI(kubectl, manifestObjects);
} }
else { else {
result = yield service_blue_green_helper_1.promoteBlueGreenService(kubectl, manifestObjects); result = yield service_blue_green_helper_1.promoteBlueGreenService(kubectl, manifestObjects);
} }
// checking stability of newly created deployments // checking stability of newly created deployments
const deployedManifestFiles = result.newFilePaths; const deployedManifestFiles = result.newFilePaths;
const resources = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([models.DiscoveryAndLoadBalancerResource.service])); const resources = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([models.DiscoveryAndLoadBalancerResource.service]));
yield KubernetesManifestUtility.checkManifestStability(kubectl, resources); yield KubernetesManifestUtility.checkManifestStability(kubectl, resources);
core.debug('routing to new deployments'); core.debug('routing to new deployments');
if (blue_green_helper_2.isIngressRoute()) { if (blue_green_helper_2.isIngressRoute()) {
ingress_blue_green_helper_1.routeBlueGreenIngress(kubectl, null, manifestObjects.serviceNameMap, manifestObjects.ingressEntityList); ingress_blue_green_helper_1.routeBlueGreenIngress(kubectl, null, manifestObjects.serviceNameMap, manifestObjects.ingressEntityList);
blue_green_helper_1.deleteWorkloadsAndServicesWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList, manifestObjects.serviceEntityList); blue_green_helper_1.deleteWorkloadsAndServicesWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList, manifestObjects.serviceEntityList);
} }
else if (blue_green_helper_2.isSMIRoute()) { else if (blue_green_helper_2.isSMIRoute()) {
smi_blue_green_helper_1.routeBlueGreenSMI(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList); smi_blue_green_helper_1.routeBlueGreenSMI(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList); blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
smi_blue_green_helper_1.cleanupSMI(kubectl, manifestObjects.serviceEntityList); smi_blue_green_helper_1.cleanupSMI(kubectl, manifestObjects.serviceEntityList);
} }
else { else {
service_blue_green_helper_1.routeBlueGreenService(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList); service_blue_green_helper_1.routeBlueGreenService(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList); blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
} }
}); });
} }

View File

@ -1,65 +1,65 @@
'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.reject = void 0; exports.reject = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper"); const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper");
const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper"); const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper");
const kubectl_object_model_1 = require("../kubectl-object-model"); const kubectl_object_model_1 = require("../kubectl-object-model");
const utils = require("../utilities/manifest-utilities"); const utils = require("../utilities/manifest-utilities");
const TaskInputParameters = require("../input-parameters"); const TaskInputParameters = require("../input-parameters");
const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper"); const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper");
const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper"); const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper");
const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper"); const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper");
const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper"); const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper");
const deployment_helper_1 = require("../utilities/strategy-helpers/deployment-helper"); const deployment_helper_1 = require("../utilities/strategy-helpers/deployment-helper");
function reject() { function reject() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true); const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true);
if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) { if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
yield rejectCanary(kubectl); yield rejectCanary(kubectl);
} }
else if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) { else if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) {
yield rejectBlueGreen(kubectl); yield rejectBlueGreen(kubectl);
} }
else { else {
core.debug('Strategy is not canary or blue-green deployment. Invalid request.'); core.debug('Strategy is not canary or blue-green deployment. Invalid request.');
throw ('InvalidDeletetActionDeploymentStrategy'); throw ('InvalidDeletetActionDeploymentStrategy');
} }
}); });
} }
exports.reject = reject; exports.reject = reject;
function rejectCanary(kubectl) { function rejectCanary(kubectl) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
let includeServices = false; let includeServices = false;
if (canaryDeploymentHelper.isSMICanaryStrategy()) { if (canaryDeploymentHelper.isSMICanaryStrategy()) {
core.debug('Reject deployment with SMI canary strategy'); core.debug('Reject deployment with SMI canary strategy');
includeServices = true; includeServices = true;
SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests); SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests);
} }
core.debug('Deployment strategy selected is Canary. Deleting baseline and canary workloads.'); core.debug('Deployment strategy selected is Canary. Deleting baseline and canary workloads.');
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices); canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices);
}); });
} }
function rejectBlueGreen(kubectl) { function rejectBlueGreen(kubectl) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
let inputManifestFiles = deployment_helper_1.getManifestFiles(TaskInputParameters.manifests); let inputManifestFiles = deployment_helper_1.getManifestFiles(TaskInputParameters.manifests);
if (blue_green_helper_1.isIngressRoute()) { if (blue_green_helper_1.isIngressRoute()) {
yield ingress_blue_green_helper_1.rejectBlueGreenIngress(kubectl, inputManifestFiles); yield ingress_blue_green_helper_1.rejectBlueGreenIngress(kubectl, inputManifestFiles);
} }
else if (blue_green_helper_1.isSMIRoute()) { else if (blue_green_helper_1.isSMIRoute()) {
yield smi_blue_green_helper_1.rejectBlueGreenSMI(kubectl, inputManifestFiles); yield smi_blue_green_helper_1.rejectBlueGreenSMI(kubectl, inputManifestFiles);
} }
else { else {
yield service_blue_green_helper_1.rejectBlueGreenService(kubectl, inputManifestFiles); yield service_blue_green_helper_1.rejectBlueGreenService(kubectl, inputManifestFiles);
} }
}); });
} }

View File

@ -1,39 +1,39 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.workflowAnnotations = exports.workloadTypesWithRolloutStatus = exports.workloadTypes = exports.deploymentTypes = exports.ServiceTypes = exports.DiscoveryAndLoadBalancerResource = exports.KubernetesWorkload = void 0; exports.workflowAnnotations = exports.workloadTypesWithRolloutStatus = exports.workloadTypes = exports.deploymentTypes = exports.ServiceTypes = exports.DiscoveryAndLoadBalancerResource = exports.KubernetesWorkload = void 0;
class KubernetesWorkload { class KubernetesWorkload {
} }
exports.KubernetesWorkload = KubernetesWorkload; exports.KubernetesWorkload = KubernetesWorkload;
KubernetesWorkload.pod = 'Pod'; KubernetesWorkload.pod = 'Pod';
KubernetesWorkload.replicaset = 'Replicaset'; KubernetesWorkload.replicaset = 'Replicaset';
KubernetesWorkload.deployment = 'Deployment'; KubernetesWorkload.deployment = 'Deployment';
KubernetesWorkload.statefulSet = 'StatefulSet'; KubernetesWorkload.statefulSet = 'StatefulSet';
KubernetesWorkload.daemonSet = 'DaemonSet'; KubernetesWorkload.daemonSet = 'DaemonSet';
KubernetesWorkload.job = 'job'; KubernetesWorkload.job = 'job';
KubernetesWorkload.cronjob = 'cronjob'; KubernetesWorkload.cronjob = 'cronjob';
class DiscoveryAndLoadBalancerResource { class DiscoveryAndLoadBalancerResource {
} }
exports.DiscoveryAndLoadBalancerResource = DiscoveryAndLoadBalancerResource; exports.DiscoveryAndLoadBalancerResource = DiscoveryAndLoadBalancerResource;
DiscoveryAndLoadBalancerResource.service = 'service'; DiscoveryAndLoadBalancerResource.service = 'service';
DiscoveryAndLoadBalancerResource.ingress = 'ingress'; DiscoveryAndLoadBalancerResource.ingress = 'ingress';
class ServiceTypes { class ServiceTypes {
} }
exports.ServiceTypes = ServiceTypes; exports.ServiceTypes = ServiceTypes;
ServiceTypes.loadBalancer = 'LoadBalancer'; ServiceTypes.loadBalancer = 'LoadBalancer';
ServiceTypes.nodePort = 'NodePort'; ServiceTypes.nodePort = 'NodePort';
ServiceTypes.clusterIP = 'ClusterIP'; ServiceTypes.clusterIP = 'ClusterIP';
exports.deploymentTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset']; exports.deploymentTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset'];
exports.workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob']; exports.workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
exports.workloadTypesWithRolloutStatus = ['deployment', 'daemonset', 'statefulset']; exports.workloadTypesWithRolloutStatus = ['deployment', 'daemonset', 'statefulset'];
exports.workflowAnnotations = [ exports.workflowAnnotations = [
`run=${process.env['GITHUB_RUN_ID']}`, `run=${process.env['GITHUB_RUN_ID']}`,
`repository=${process.env['GITHUB_REPOSITORY']}`, `repository=${process.env['GITHUB_REPOSITORY']}`,
`workflow=${process.env['GITHUB_WORKFLOW']}`, `workflow=${process.env['GITHUB_WORKFLOW']}`,
`jobName=${process.env['GITHUB_JOB']}`, `jobName=${process.env['GITHUB_JOB']}`,
`createdBy=${process.env['GITHUB_ACTOR']}`, `createdBy=${process.env['GITHUB_ACTOR']}`,
`runUri=https://github.com/${process.env['GITHUB_REPOSITORY']}/actions/runs/${process.env['GITHUB_RUN_ID']}`, `runUri=https://github.com/${process.env['GITHUB_REPOSITORY']}/actions/runs/${process.env['GITHUB_RUN_ID']}`,
`commit=${process.env['GITHUB_SHA']}`, `commit=${process.env['GITHUB_SHA']}`,
`branch=${process.env['GITHUB_REF']}`, `branch=${process.env['GITHUB_REF']}`,
`deployTimestamp=${Date.now()}`, `deployTimestamp=${Date.now()}`,
`provider=GitHub` `provider=GitHub`
]; ];

View File

@ -1,53 +1,53 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.forceDeployment = exports.args = exports.baselineAndCanaryReplicas = exports.versionSwitchBuffer = exports.routeMethod = exports.trafficSplitMethod = exports.deploymentStrategy = exports.canaryPercentage = exports.manifests = exports.imagePullSecrets = exports.containers = exports.namespace = void 0; exports.forceDeployment = exports.args = exports.baselineAndCanaryReplicas = exports.versionSwitchBuffer = exports.routeMethod = exports.trafficSplitMethod = exports.deploymentStrategy = exports.canaryPercentage = exports.manifests = exports.imagePullSecrets = exports.containers = exports.namespace = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
exports.namespace = core.getInput('namespace'); exports.namespace = core.getInput('namespace');
exports.containers = core.getInput('images').split('\n'); exports.containers = core.getInput('images').split('\n');
exports.imagePullSecrets = core.getInput('imagepullsecrets').split('\n').filter(secret => secret.trim().length > 0); exports.imagePullSecrets = core.getInput('imagepullsecrets').split('\n').filter(secret => secret.trim().length > 0);
exports.manifests = core.getInput('manifests').split('\n'); exports.manifests = core.getInput('manifests').split('\n');
exports.canaryPercentage = core.getInput('percentage'); exports.canaryPercentage = core.getInput('percentage');
exports.deploymentStrategy = core.getInput('strategy'); exports.deploymentStrategy = core.getInput('strategy');
exports.trafficSplitMethod = core.getInput('traffic-split-method'); exports.trafficSplitMethod = core.getInput('traffic-split-method');
exports.routeMethod = core.getInput('route-method'); exports.routeMethod = core.getInput('route-method');
exports.versionSwitchBuffer = core.getInput('version-switch-buffer'); exports.versionSwitchBuffer = core.getInput('version-switch-buffer');
exports.baselineAndCanaryReplicas = core.getInput('baseline-and-canary-replicas'); exports.baselineAndCanaryReplicas = core.getInput('baseline-and-canary-replicas');
exports.args = core.getInput('arguments'); exports.args = core.getInput('arguments');
exports.forceDeployment = core.getInput('force').toLowerCase() == 'true'; exports.forceDeployment = core.getInput('force').toLowerCase() == 'true';
if (!exports.namespace) { if (!exports.namespace) {
core.debug('Namespace was not supplied; using "default" namespace instead.'); core.debug('Namespace was not supplied; using "default" namespace instead.');
exports.namespace = 'default'; exports.namespace = 'default';
} }
try { try {
const pe = parseInt(exports.canaryPercentage); const pe = parseInt(exports.canaryPercentage);
if (pe < 0 || pe > 100) { if (pe < 0 || pe > 100) {
core.setFailed('A valid percentage value is between 0 and 100'); core.setFailed('A valid percentage value is between 0 and 100');
process.exit(1); process.exit(1);
} }
} }
catch (ex) { catch (ex) {
core.setFailed("Enter a valid 'percentage' integer value "); core.setFailed("Enter a valid 'percentage' integer value ");
process.exit(1); process.exit(1);
} }
try { try {
const pe = parseInt(exports.baselineAndCanaryReplicas); const pe = parseInt(exports.baselineAndCanaryReplicas);
if (pe < 0 || pe > 100) { if (pe < 0 || pe > 100) {
core.setFailed('A valid baseline-and-canary-replicas value is between 0 and 100'); core.setFailed('A valid baseline-and-canary-replicas value is between 0 and 100');
process.exit(1); process.exit(1);
} }
} }
catch (ex) { catch (ex) {
core.setFailed("Enter a valid 'baseline-and-canary-replicas' integer value"); core.setFailed("Enter a valid 'baseline-and-canary-replicas' integer value");
process.exit(1); process.exit(1);
} }
try { try {
const pe = parseInt(exports.versionSwitchBuffer); const pe = parseInt(exports.versionSwitchBuffer);
if (pe < 0 || pe > 300) { if (pe < 0 || pe > 300) {
core.setFailed('Invalid buffer time, valid version-switch-buffer is a value more than or equal to 0 and lesser than or equal 300'); core.setFailed('Invalid buffer time, valid version-switch-buffer is a value more than or equal to 0 and lesser than or equal 300');
process.exit(1); process.exit(1);
} }
} }
catch (ex) { catch (ex) {
core.setFailed("Enter a valid 'version-switch-buffer' integer value"); core.setFailed("Enter a valid 'version-switch-buffer' integer value");
process.exit(1); process.exit(1);
} }

View File

@ -1,114 +1,114 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.Kubectl = void 0; exports.Kubectl = void 0;
const tool_runner_1 = require("./utilities/tool-runner"); const tool_runner_1 = require("./utilities/tool-runner");
class Kubectl { class Kubectl {
constructor(kubectlPath, namespace, ignoreSSLErrors) { constructor(kubectlPath, namespace, ignoreSSLErrors) {
this.kubectlPath = kubectlPath; this.kubectlPath = kubectlPath;
this.ignoreSSLErrors = !!ignoreSSLErrors; this.ignoreSSLErrors = !!ignoreSSLErrors;
if (!!namespace) { if (!!namespace) {
this.namespace = namespace; this.namespace = namespace;
} }
else { else {
this.namespace = 'default'; this.namespace = 'default';
} }
} }
apply(configurationPaths, force) { apply(configurationPaths, force) {
let applyArgs = ['apply', '-f', this.createInlineArray(configurationPaths)]; let applyArgs = ['apply', '-f', this.createInlineArray(configurationPaths)];
if (!!force) { if (!!force) {
console.log("force flag is on, deployment will continue even if previous deployment already exists"); console.log("force flag is on, deployment will continue even if previous deployment already exists");
applyArgs.push('--force'); applyArgs.push('--force');
} }
return this.execute(applyArgs); return this.execute(applyArgs);
} }
describe(resourceType, resourceName, silent) { describe(resourceType, resourceName, silent) {
return this.execute(['describe', resourceType, resourceName], silent); return this.execute(['describe', resourceType, resourceName], silent);
} }
getNewReplicaSet(deployment) { getNewReplicaSet(deployment) {
let newReplicaSet = ''; let newReplicaSet = '';
const result = this.describe('deployment', deployment, true); const result = this.describe('deployment', deployment, true);
if (result && result.stdout) { if (result && result.stdout) {
const stdout = result.stdout.split('\n'); const stdout = result.stdout.split('\n');
stdout.forEach((line) => { stdout.forEach((line) => {
if (!!line && line.toLowerCase().indexOf('newreplicaset') > -1) { if (!!line && line.toLowerCase().indexOf('newreplicaset') > -1) {
newReplicaSet = line.substr(14).trim().split(' ')[0]; newReplicaSet = line.substr(14).trim().split(' ')[0];
} }
}); });
} }
return newReplicaSet; return newReplicaSet;
} }
annotate(resourceType, resourceName, annotations, overwrite) { annotate(resourceType, resourceName, annotations, overwrite) {
let args = ['annotate', resourceType, resourceName]; let args = ['annotate', resourceType, resourceName];
args = args.concat(annotations); args = args.concat(annotations);
if (!!overwrite) { if (!!overwrite) {
args.push(`--overwrite`); args.push(`--overwrite`);
} }
return this.execute(args); return this.execute(args);
} }
annotateFiles(files, annotations, overwrite) { annotateFiles(files, annotations, overwrite) {
let args = ['annotate']; let args = ['annotate'];
args = args.concat(['-f', this.createInlineArray(files)]); args = args.concat(['-f', this.createInlineArray(files)]);
args = args.concat(annotations); args = args.concat(annotations);
if (!!overwrite) { if (!!overwrite) {
args.push(`--overwrite`); args.push(`--overwrite`);
} }
return this.execute(args); return this.execute(args);
} }
getAllPods() { getAllPods() {
return this.execute(['get', 'pods', '-o', 'json'], true); return this.execute(['get', 'pods', '-o', 'json'], true);
} }
getClusterInfo() { getClusterInfo() {
return this.execute(['cluster-info'], true); return this.execute(['cluster-info'], true);
} }
checkRolloutStatus(resourceType, name) { checkRolloutStatus(resourceType, name) {
return this.execute(['rollout', 'status', resourceType + '/' + name]); return this.execute(['rollout', 'status', resourceType + '/' + name]);
} }
getResource(resourceType, name) { getResource(resourceType, name) {
return this.execute(['get', resourceType + '/' + name, '-o', 'json']); return this.execute(['get', resourceType + '/' + name, '-o', 'json']);
} }
getResources(applyOutput, filterResourceTypes) { getResources(applyOutput, filterResourceTypes) {
const outputLines = applyOutput.split('\n'); const outputLines = applyOutput.split('\n');
const results = []; const results = [];
outputLines.forEach(line => { outputLines.forEach(line => {
const words = line.split(' '); const words = line.split(' ');
if (words.length > 2) { if (words.length > 2) {
const resourceType = words[0].trim(); const resourceType = words[0].trim();
const resourceName = JSON.parse(words[1].trim()); const resourceName = JSON.parse(words[1].trim());
if (filterResourceTypes.filter(type => !!type && resourceType.toLowerCase().startsWith(type.toLowerCase())).length > 0) { if (filterResourceTypes.filter(type => !!type && resourceType.toLowerCase().startsWith(type.toLowerCase())).length > 0) {
results.push({ results.push({
type: resourceType, type: resourceType,
name: resourceName name: resourceName
}); });
} }
} }
}); });
return results; return results;
} }
executeCommand(customCommand, args) { executeCommand(customCommand, args) {
if (!customCommand) if (!customCommand)
throw new Error('NullCommandForKubectl'); throw new Error('NullCommandForKubectl');
return args ? this.execute([customCommand, args]) : this.execute([customCommand]); return args ? this.execute([customCommand, args]) : this.execute([customCommand]);
} }
delete(args) { delete(args) {
if (typeof args === 'string') if (typeof args === 'string')
return this.execute(['delete', args]); return this.execute(['delete', args]);
else else
return this.execute(['delete'].concat(args)); return this.execute(['delete'].concat(args));
} }
execute(args, silent) { execute(args, silent) {
if (this.ignoreSSLErrors) { if (this.ignoreSSLErrors) {
args.push('--insecure-skip-tls-verify'); args.push('--insecure-skip-tls-verify');
} }
args = args.concat(['--namespace', this.namespace]); args = args.concat(['--namespace', this.namespace]);
const command = new tool_runner_1.ToolRunner(this.kubectlPath); const command = new tool_runner_1.ToolRunner(this.kubectlPath);
command.arg(args); command.arg(args);
return command.execSync({ silent: !!silent }); return command.execSync({ silent: !!silent });
} }
createInlineArray(str) { createInlineArray(str) {
if (typeof str === 'string') { if (typeof str === 'string') {
return str; return str;
} }
return str.join(','); return str.join(',');
} }
} }
exports.Kubectl = Kubectl; exports.Kubectl = Kubectl;

View File

@ -1,91 +1,91 @@
"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.run = void 0; exports.run = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const io = require("@actions/io"); const io = require("@actions/io");
const path = require("path"); const path = require("path");
const toolCache = require("@actions/tool-cache"); const toolCache = require("@actions/tool-cache");
const kubectl_util_1 = require("./utilities/kubectl-util"); const kubectl_util_1 = require("./utilities/kubectl-util");
const utility_1 = require("./utilities/utility"); const utility_1 = require("./utilities/utility");
const kubectl_object_model_1 = require("./kubectl-object-model"); const kubectl_object_model_1 = require("./kubectl-object-model");
const deployment_helper_1 = require("./utilities/strategy-helpers/deployment-helper"); const deployment_helper_1 = require("./utilities/strategy-helpers/deployment-helper");
const promote_1 = require("./actions/promote"); const promote_1 = require("./actions/promote");
const reject_1 = require("./actions/reject"); const reject_1 = require("./actions/reject");
let kubectlPath = ""; let kubectlPath = "";
function setKubectlPath() { function setKubectlPath() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
if (core.getInput('kubectl-version')) { if (core.getInput('kubectl-version')) {
const version = core.getInput('kubectl-version'); const version = core.getInput('kubectl-version');
kubectlPath = toolCache.find('kubectl', version); kubectlPath = toolCache.find('kubectl', version);
if (!kubectlPath) { if (!kubectlPath) {
kubectlPath = yield installKubectl(version); kubectlPath = yield installKubectl(version);
} }
} }
else { else {
kubectlPath = yield io.which('kubectl', false); kubectlPath = yield io.which('kubectl', false);
if (!kubectlPath) { if (!kubectlPath) {
const allVersions = toolCache.findAllVersions('kubectl'); const allVersions = toolCache.findAllVersions('kubectl');
kubectlPath = allVersions.length > 0 ? toolCache.find('kubectl', allVersions[0]) : ''; kubectlPath = allVersions.length > 0 ? toolCache.find('kubectl', allVersions[0]) : '';
if (!kubectlPath) { if (!kubectlPath) {
throw new Error('Kubectl is not installed, either add install-kubectl action or provide "kubectl-version" input to download kubectl'); throw new Error('Kubectl is not installed, either add install-kubectl action or provide "kubectl-version" input to download kubectl');
} }
kubectlPath = path.join(kubectlPath, `kubectl${utility_1.getExecutableExtension()}`); kubectlPath = path.join(kubectlPath, `kubectl${utility_1.getExecutableExtension()}`);
} }
} }
}); });
} }
function installKubectl(version) { function installKubectl(version) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
if (utility_1.isEqual(version, 'latest')) { if (utility_1.isEqual(version, 'latest')) {
version = yield kubectl_util_1.getStableKubectlVersion(); version = yield kubectl_util_1.getStableKubectlVersion();
} }
return yield kubectl_util_1.downloadKubectl(version); return yield kubectl_util_1.downloadKubectl(version);
}); });
} }
function checkClusterContext() { function checkClusterContext() {
if (!process.env["KUBECONFIG"]) { if (!process.env["KUBECONFIG"]) {
throw new Error('Cluster context not set. Use k8ssetcontext action to set cluster context'); throw new Error('Cluster context not set. Use k8ssetcontext action to set cluster context');
} }
} }
function run() { function run() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
checkClusterContext(); checkClusterContext();
yield setKubectlPath(); yield setKubectlPath();
let manifestsInput = core.getInput('manifests'); let manifestsInput = core.getInput('manifests');
if (!manifestsInput) { if (!manifestsInput) {
core.setFailed('No manifests supplied to deploy'); core.setFailed('No manifests supplied to deploy');
return; return;
} }
let namespace = core.getInput('namespace'); let namespace = core.getInput('namespace');
if (!namespace) { if (!namespace) {
namespace = 'default'; namespace = 'default';
} }
let action = core.getInput('action'); let action = core.getInput('action');
let manifests = manifestsInput.split('\n'); let manifests = manifestsInput.split('\n');
if (action === 'deploy') { if (action === 'deploy') {
let strategy = core.getInput('strategy'); let strategy = core.getInput('strategy');
console.log("strategy: ", strategy); console.log("strategy: ", strategy);
yield deployment_helper_1.deploy(new kubectl_object_model_1.Kubectl(kubectlPath, namespace), manifests, strategy); yield deployment_helper_1.deploy(new kubectl_object_model_1.Kubectl(kubectlPath, namespace), manifests, strategy);
} }
else if (action === 'promote') { else if (action === 'promote') {
yield promote_1.promote(); yield promote_1.promote();
} }
else if (action === 'reject') { else if (action === 'reject') {
yield reject_1.reject(); yield reject_1.reject();
} }
else { else {
core.setFailed('Not a valid action. The allowed actions are deploy, promote, reject'); core.setFailed('Not a valid action. The allowed actions are deploy, promote, reject');
} }
}); });
} }
exports.run = run; exports.run = run;
run().catch(core.setFailed); run().catch(core.setFailed);

View File

@ -1,78 +1,78 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.writeManifestToFile = exports.writeObjectsToFile = exports.assertFileExists = exports.ensureDirExists = exports.getNewUserDirPath = exports.getTempDirectory = void 0; exports.writeManifestToFile = exports.writeObjectsToFile = exports.assertFileExists = exports.ensureDirExists = exports.getNewUserDirPath = exports.getTempDirectory = void 0;
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const core = require("@actions/core"); const core = require("@actions/core");
const os = require("os"); const os = require("os");
function getTempDirectory() { function getTempDirectory() {
return process.env['runner.tempDirectory'] || os.tmpdir(); return process.env['runner.tempDirectory'] || os.tmpdir();
} }
exports.getTempDirectory = getTempDirectory; exports.getTempDirectory = getTempDirectory;
function getNewUserDirPath() { function getNewUserDirPath() {
let userDir = path.join(getTempDirectory(), 'kubectlTask'); let userDir = path.join(getTempDirectory(), 'kubectlTask');
ensureDirExists(userDir); ensureDirExists(userDir);
userDir = path.join(userDir, getCurrentTime().toString()); userDir = path.join(userDir, getCurrentTime().toString());
ensureDirExists(userDir); ensureDirExists(userDir);
return userDir; return userDir;
} }
exports.getNewUserDirPath = getNewUserDirPath; exports.getNewUserDirPath = getNewUserDirPath;
function ensureDirExists(dirPath) { function ensureDirExists(dirPath) {
if (!fs.existsSync(dirPath)) { if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath); fs.mkdirSync(dirPath);
} }
} }
exports.ensureDirExists = ensureDirExists; exports.ensureDirExists = ensureDirExists;
function assertFileExists(path) { function assertFileExists(path) {
if (!fs.existsSync(path)) { if (!fs.existsSync(path)) {
core.error(`FileNotFoundException : ${path}`); core.error(`FileNotFoundException : ${path}`);
throw new Error(`FileNotFoundException: ${path}`); throw new Error(`FileNotFoundException: ${path}`);
} }
} }
exports.assertFileExists = assertFileExists; exports.assertFileExists = assertFileExists;
function writeObjectsToFile(inputObjects) { function writeObjectsToFile(inputObjects) {
const newFilePaths = []; const newFilePaths = [];
if (!!inputObjects) { if (!!inputObjects) {
inputObjects.forEach((inputObject) => { inputObjects.forEach((inputObject) => {
try { try {
const inputObjectString = JSON.stringify(inputObject); const inputObjectString = JSON.stringify(inputObject);
if (!!inputObject.kind && !!inputObject.metadata && !!inputObject.metadata.name) { if (!!inputObject.kind && !!inputObject.metadata && !!inputObject.metadata.name) {
const fileName = getManifestFileName(inputObject.kind, inputObject.metadata.name); const fileName = getManifestFileName(inputObject.kind, inputObject.metadata.name);
fs.writeFileSync(path.join(fileName), inputObjectString); fs.writeFileSync(path.join(fileName), inputObjectString);
newFilePaths.push(fileName); newFilePaths.push(fileName);
} }
else { else {
core.debug('Input object is not proper K8s resource object. Object: ' + inputObjectString); core.debug('Input object is not proper K8s resource object. Object: ' + inputObjectString);
} }
} }
catch (ex) { catch (ex) {
core.debug('Exception occurred while writing object to file : ' + inputObject + ' . Exception: ' + ex); core.debug('Exception occurred while writing object to file : ' + inputObject + ' . Exception: ' + ex);
} }
}); });
} }
return newFilePaths; return newFilePaths;
} }
exports.writeObjectsToFile = writeObjectsToFile; exports.writeObjectsToFile = writeObjectsToFile;
function writeManifestToFile(inputObjectString, kind, name) { function writeManifestToFile(inputObjectString, kind, name) {
if (inputObjectString) { if (inputObjectString) {
try { try {
const fileName = getManifestFileName(kind, name); const fileName = getManifestFileName(kind, name);
fs.writeFileSync(path.join(fileName), inputObjectString); fs.writeFileSync(path.join(fileName), inputObjectString);
return fileName; return fileName;
} }
catch (ex) { catch (ex) {
core.debug('Exception occurred while writing object to file : ' + inputObjectString + ' . Exception: ' + ex); core.debug('Exception occurred while writing object to file : ' + inputObjectString + ' . Exception: ' + ex);
} }
} }
return ''; return '';
} }
exports.writeManifestToFile = writeManifestToFile; exports.writeManifestToFile = writeManifestToFile;
function getManifestFileName(kind, name) { function getManifestFileName(kind, name) {
const filePath = kind + '_' + name + '_' + getCurrentTime().toString(); const filePath = kind + '_' + name + '_' + getCurrentTime().toString();
const tempDirectory = getTempDirectory(); const tempDirectory = getTempDirectory();
const fileName = path.join(tempDirectory, path.basename(filePath)); const fileName = path.join(tempDirectory, path.basename(filePath));
return fileName; return fileName;
} }
function getCurrentTime() { function getCurrentTime() {
return new Date().getTime(); return new Date().getTime();
} }

View File

@ -1,158 +1,158 @@
'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.checkPodStatus = exports.checkManifestStability = void 0; exports.checkPodStatus = exports.checkManifestStability = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const utils = require("./utility"); const utils = require("./utility");
const KubernetesConstants = require("../constants"); const KubernetesConstants = require("../constants");
function checkManifestStability(kubectl, resources) { function checkManifestStability(kubectl, resources) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
let rolloutStatusHasErrors = false; let rolloutStatusHasErrors = false;
const numberOfResources = resources.length; const numberOfResources = resources.length;
for (let i = 0; i < numberOfResources; i++) { for (let i = 0; i < numberOfResources; i++) {
const resource = resources[i]; const resource = resources[i];
if (KubernetesConstants.workloadTypesWithRolloutStatus.indexOf(resource.type.toLowerCase()) >= 0) { if (KubernetesConstants.workloadTypesWithRolloutStatus.indexOf(resource.type.toLowerCase()) >= 0) {
try { try {
var result = kubectl.checkRolloutStatus(resource.type, resource.name); var result = kubectl.checkRolloutStatus(resource.type, resource.name);
utils.checkForErrors([result]); utils.checkForErrors([result]);
} }
catch (ex) { catch (ex) {
core.error(ex); core.error(ex);
kubectl.describe(resource.type, resource.name); kubectl.describe(resource.type, resource.name);
rolloutStatusHasErrors = true; rolloutStatusHasErrors = true;
} }
} }
if (utils.isEqual(resource.type, KubernetesConstants.KubernetesWorkload.pod, true)) { if (utils.isEqual(resource.type, KubernetesConstants.KubernetesWorkload.pod, true)) {
try { try {
yield checkPodStatus(kubectl, resource.name); yield checkPodStatus(kubectl, resource.name);
} }
catch (ex) { catch (ex) {
core.warning(`CouldNotDeterminePodStatus ${JSON.stringify(ex)}`); core.warning(`CouldNotDeterminePodStatus ${JSON.stringify(ex)}`);
kubectl.describe(resource.type, resource.name); kubectl.describe(resource.type, resource.name);
} }
} }
if (utils.isEqual(resource.type, KubernetesConstants.DiscoveryAndLoadBalancerResource.service, true)) { if (utils.isEqual(resource.type, KubernetesConstants.DiscoveryAndLoadBalancerResource.service, true)) {
try { try {
const service = getService(kubectl, resource.name); const service = getService(kubectl, resource.name);
const spec = service.spec; const spec = service.spec;
const status = service.status; const status = service.status;
if (utils.isEqual(spec.type, KubernetesConstants.ServiceTypes.loadBalancer, true)) { if (utils.isEqual(spec.type, KubernetesConstants.ServiceTypes.loadBalancer, true)) {
if (!isLoadBalancerIPAssigned(status)) { if (!isLoadBalancerIPAssigned(status)) {
yield waitForServiceExternalIPAssignment(kubectl, resource.name); yield waitForServiceExternalIPAssignment(kubectl, resource.name);
} }
else { else {
console.log('ServiceExternalIP', resource.name, status.loadBalancer.ingress[0].ip); console.log('ServiceExternalIP', resource.name, status.loadBalancer.ingress[0].ip);
} }
} }
} }
catch (ex) { catch (ex) {
core.warning(`CouldNotDetermineServiceStatus of: ${resource.name} Error: ${JSON.stringify(ex)}`); core.warning(`CouldNotDetermineServiceStatus of: ${resource.name} Error: ${JSON.stringify(ex)}`);
kubectl.describe(resource.type, resource.name); kubectl.describe(resource.type, resource.name);
} }
} }
} }
if (rolloutStatusHasErrors) { if (rolloutStatusHasErrors) {
throw new Error('RolloutStatusTimedout'); throw new Error('RolloutStatusTimedout');
} }
}); });
} }
exports.checkManifestStability = checkManifestStability; exports.checkManifestStability = checkManifestStability;
function checkPodStatus(kubectl, podName) { function checkPodStatus(kubectl, podName) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const sleepTimeout = 10 * 1000; // 10 seconds const sleepTimeout = 10 * 1000; // 10 seconds
const iterations = 60; // 60 * 10 seconds timeout = 10 minutes max timeout const iterations = 60; // 60 * 10 seconds timeout = 10 minutes max timeout
let podStatus; let podStatus;
let kubectlDescribeNeeded = false; let kubectlDescribeNeeded = false;
for (let i = 0; i < iterations; i++) { for (let i = 0; i < iterations; i++) {
yield utils.sleep(sleepTimeout); yield utils.sleep(sleepTimeout);
core.debug(`Polling for pod status: ${podName}`); core.debug(`Polling for pod status: ${podName}`);
podStatus = getPodStatus(kubectl, podName); podStatus = getPodStatus(kubectl, podName);
if (podStatus.phase && podStatus.phase !== 'Pending' && podStatus.phase !== 'Unknown') { if (podStatus.phase && podStatus.phase !== 'Pending' && podStatus.phase !== 'Unknown') {
break; break;
} }
} }
podStatus = getPodStatus(kubectl, podName); podStatus = getPodStatus(kubectl, podName);
switch (podStatus.phase) { switch (podStatus.phase) {
case 'Succeeded': case 'Succeeded':
case 'Running': case 'Running':
if (isPodReady(podStatus)) { if (isPodReady(podStatus)) {
console.log(`pod/${podName} is successfully rolled out`); console.log(`pod/${podName} is successfully rolled out`);
} }
else { else {
kubectlDescribeNeeded = true; kubectlDescribeNeeded = true;
} }
break; break;
case 'Pending': case 'Pending':
if (!isPodReady(podStatus)) { if (!isPodReady(podStatus)) {
core.warning(`pod/${podName} rollout status check timedout`); core.warning(`pod/${podName} rollout status check timedout`);
kubectlDescribeNeeded = true; kubectlDescribeNeeded = true;
} }
break; break;
case 'Failed': case 'Failed':
core.error(`pod/${podName} rollout failed`); core.error(`pod/${podName} rollout failed`);
kubectlDescribeNeeded = true; kubectlDescribeNeeded = true;
break; break;
default: default:
core.warning(`pod/${podName} rollout status: ${podStatus.phase}`); core.warning(`pod/${podName} rollout status: ${podStatus.phase}`);
} }
if (kubectlDescribeNeeded) { if (kubectlDescribeNeeded) {
kubectl.describe('pod', podName); kubectl.describe('pod', podName);
} }
}); });
} }
exports.checkPodStatus = checkPodStatus; exports.checkPodStatus = checkPodStatus;
function getPodStatus(kubectl, podName) { function getPodStatus(kubectl, podName) {
const podResult = kubectl.getResource('pod', podName); const podResult = kubectl.getResource('pod', podName);
utils.checkForErrors([podResult]); utils.checkForErrors([podResult]);
const podStatus = JSON.parse(podResult.stdout).status; const podStatus = JSON.parse(podResult.stdout).status;
core.debug(`Pod Status: ${JSON.stringify(podStatus)}`); core.debug(`Pod Status: ${JSON.stringify(podStatus)}`);
return podStatus; return podStatus;
} }
function isPodReady(podStatus) { function isPodReady(podStatus) {
let allContainersAreReady = true; let allContainersAreReady = true;
podStatus.containerStatuses.forEach(container => { podStatus.containerStatuses.forEach(container => {
if (container.ready === false) { if (container.ready === false) {
console.log(`'${container.name}' status: ${JSON.stringify(container.state)}`); console.log(`'${container.name}' status: ${JSON.stringify(container.state)}`);
allContainersAreReady = false; allContainersAreReady = false;
} }
}); });
if (!allContainersAreReady) { if (!allContainersAreReady) {
core.warning('AllContainersNotInReadyState'); core.warning('AllContainersNotInReadyState');
} }
return allContainersAreReady; return allContainersAreReady;
} }
function getService(kubectl, serviceName) { function getService(kubectl, serviceName) {
const serviceResult = kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.service, serviceName); const serviceResult = kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.service, serviceName);
utils.checkForErrors([serviceResult]); utils.checkForErrors([serviceResult]);
return JSON.parse(serviceResult.stdout); return JSON.parse(serviceResult.stdout);
} }
function waitForServiceExternalIPAssignment(kubectl, serviceName) { function waitForServiceExternalIPAssignment(kubectl, serviceName) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const sleepTimeout = 10 * 1000; // 10 seconds const sleepTimeout = 10 * 1000; // 10 seconds
const iterations = 18; // 18 * 10 seconds timeout = 3 minutes max timeout const iterations = 18; // 18 * 10 seconds timeout = 3 minutes max timeout
for (let i = 0; i < iterations; i++) { for (let i = 0; i < iterations; i++) {
console.log(`waitForServiceIpAssignment : ${serviceName}`); console.log(`waitForServiceIpAssignment : ${serviceName}`);
yield utils.sleep(sleepTimeout); yield utils.sleep(sleepTimeout);
let status = (getService(kubectl, serviceName)).status; let status = (getService(kubectl, serviceName)).status;
if (isLoadBalancerIPAssigned(status)) { if (isLoadBalancerIPAssigned(status)) {
console.log('ServiceExternalIP', serviceName, status.loadBalancer.ingress[0].ip); console.log('ServiceExternalIP', serviceName, status.loadBalancer.ingress[0].ip);
return; return;
} }
} }
core.warning(`waitForServiceIpAssignmentTimedOut ${serviceName}`); core.warning(`waitForServiceIpAssignmentTimedOut ${serviceName}`);
}); });
} }
function isLoadBalancerIPAssigned(status) { function isLoadBalancerIPAssigned(status) {
if (status && status.loadBalancer && status.loadBalancer.ingress && status.loadBalancer.ingress.length > 0) { if (status && status.loadBalancer && status.loadBalancer.ingress && status.loadBalancer.ingress.length > 0) {
return true; return true;
} }
return false; return false;
} }

View File

@ -1,283 +1,283 @@
'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.isWorkloadEntity = exports.getUpdatedManifestFiles = exports.updateImagePullSecrets = exports.substituteImageNameInSpecFile = exports.getDeleteCmdArgs = exports.createKubectlArgs = exports.getKubectl = exports.getManifestFiles = void 0; exports.isWorkloadEntity = exports.getUpdatedManifestFiles = exports.updateImagePullSecrets = exports.substituteImageNameInSpecFile = exports.getDeleteCmdArgs = exports.createKubectlArgs = exports.getKubectl = exports.getManifestFiles = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const fs = require("fs"); const fs = require("fs");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const path = require("path"); const path = require("path");
const kubectlutility = require("./kubectl-util"); const kubectlutility = require("./kubectl-util");
const io = require("@actions/io"); const io = require("@actions/io");
const utility_1 = require("./utility"); const utility_1 = require("./utility");
const fileHelper = require("./files-helper"); const fileHelper = require("./files-helper");
const KubernetesObjectUtility = require("./resource-object-utility"); const KubernetesObjectUtility = require("./resource-object-utility");
const TaskInputParameters = require("../input-parameters"); const TaskInputParameters = require("../input-parameters");
function getManifestFiles(manifestFilePaths) { function getManifestFiles(manifestFilePaths) {
if (!manifestFilePaths) { if (!manifestFilePaths) {
core.debug('file input is not present'); core.debug('file input is not present');
return null; return null;
} }
return manifestFilePaths; return manifestFilePaths;
} }
exports.getManifestFiles = getManifestFiles; exports.getManifestFiles = getManifestFiles;
function getKubectl() { function getKubectl() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try { try {
return Promise.resolve(io.which('kubectl', true)); return Promise.resolve(io.which('kubectl', true));
} }
catch (ex) { catch (ex) {
return kubectlutility.downloadKubectl(yield kubectlutility.getStableKubectlVersion()); return kubectlutility.downloadKubectl(yield kubectlutility.getStableKubectlVersion());
} }
}); });
} }
exports.getKubectl = getKubectl; exports.getKubectl = getKubectl;
function createKubectlArgs(kinds, names) { function createKubectlArgs(kinds, names) {
let args = ''; let args = '';
if (!!kinds && kinds.size > 0) { if (!!kinds && kinds.size > 0) {
args = args + createInlineArray(Array.from(kinds.values())); args = args + createInlineArray(Array.from(kinds.values()));
} }
if (!!names && names.size > 0) { if (!!names && names.size > 0) {
args = args + ' ' + Array.from(names.values()).join(' '); args = args + ' ' + Array.from(names.values()).join(' ');
} }
return args; return args;
} }
exports.createKubectlArgs = createKubectlArgs; exports.createKubectlArgs = createKubectlArgs;
function getDeleteCmdArgs(argsPrefix, inputArgs) { function getDeleteCmdArgs(argsPrefix, inputArgs) {
let args = ''; let args = '';
if (!!argsPrefix && argsPrefix.length > 0) { if (!!argsPrefix && argsPrefix.length > 0) {
args = argsPrefix; args = argsPrefix;
} }
if (!!inputArgs && inputArgs.length > 0) { if (!!inputArgs && inputArgs.length > 0) {
if (args.length > 0) { if (args.length > 0) {
args = args + ' '; args = args + ' ';
} }
args = args + inputArgs; args = args + inputArgs;
} }
return args; return args;
} }
exports.getDeleteCmdArgs = getDeleteCmdArgs; exports.getDeleteCmdArgs = getDeleteCmdArgs;
/* /*
For example, For example,
currentString: `image: "example/example-image"` currentString: `image: "example/example-image"`
imageName: `example/example-image` imageName: `example/example-image`
imageNameWithNewTag: `example/example-image:identifiertag` imageNameWithNewTag: `example/example-image:identifiertag`
This substituteImageNameInSpecFile function would return This substituteImageNameInSpecFile function would return
return Value: `image: "example/example-image:identifiertag"` return Value: `image: "example/example-image:identifiertag"`
*/ */
function substituteImageNameInSpecFile(currentString, imageName, imageNameWithNewTag) { function substituteImageNameInSpecFile(currentString, imageName, imageNameWithNewTag) {
if (currentString.indexOf(imageName) < 0) { if (currentString.indexOf(imageName) < 0) {
core.debug(`No occurence of replacement token: ${imageName} found`); core.debug(`No occurence of replacement token: ${imageName} found`);
return currentString; return currentString;
} }
return currentString.split('\n').reduce((acc, line) => { return currentString.split('\n').reduce((acc, line) => {
const imageKeyword = line.match(/^ *image:/); const imageKeyword = line.match(/^ *image:/);
if (imageKeyword) { if (imageKeyword) {
let [currentImageName, currentImageTag] = line let [currentImageName, currentImageTag] = line
.substring(imageKeyword[0].length) // consume the line from keyword onwards .substring(imageKeyword[0].length) // consume the line from keyword onwards
.trim() .trim()
.replace(/[',"]/g, '') // replace allowed quotes with nothing .replace(/[',"]/g, '') // replace allowed quotes with nothing
.split(':'); .split(':');
if (!currentImageTag && currentImageName.indexOf(' ') > 0) { if (!currentImageTag && currentImageName.indexOf(' ') > 0) {
currentImageName = currentImageName.split(' ')[0]; // Stripping off comments currentImageName = currentImageName.split(' ')[0]; // Stripping off comments
} }
if (currentImageName === imageName) { if (currentImageName === imageName) {
return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`; return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`;
} }
} }
return acc + line + '\n'; return acc + line + '\n';
}, ''); }, '');
} }
exports.substituteImageNameInSpecFile = substituteImageNameInSpecFile; exports.substituteImageNameInSpecFile = substituteImageNameInSpecFile;
function createInlineArray(str) { function createInlineArray(str) {
if (typeof str === 'string') { if (typeof str === 'string') {
return str; return str;
} }
return str.join(','); return str.join(',');
} }
function getImagePullSecrets(inputObject) { function getImagePullSecrets(inputObject) {
if (!inputObject || !inputObject.spec) { if (!inputObject || !inputObject.spec) {
return; return;
} }
if (utility_1.isEqual(inputObject.kind, 'pod') if (utility_1.isEqual(inputObject.kind, 'pod')
&& inputObject && inputObject
&& inputObject.spec && inputObject.spec
&& inputObject.spec.imagePullSecrets) { && inputObject.spec.imagePullSecrets) {
return inputObject.spec.imagePullSecrets; return inputObject.spec.imagePullSecrets;
} }
else if (utility_1.isEqual(inputObject.kind, 'cronjob') else if (utility_1.isEqual(inputObject.kind, 'cronjob')
&& inputObject && inputObject
&& inputObject.spec && inputObject.spec
&& inputObject.spec.jobTemplate && inputObject.spec.jobTemplate
&& inputObject.spec.jobTemplate.spec && inputObject.spec.jobTemplate.spec
&& inputObject.spec.jobTemplate.spec.template && inputObject.spec.jobTemplate.spec.template
&& inputObject.spec.jobTemplate.spec.template.spec && inputObject.spec.jobTemplate.spec.template.spec
&& inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets) { && inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets) {
return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets; return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
} }
else if (inputObject else if (inputObject
&& inputObject.spec && inputObject.spec
&& inputObject.spec.template && inputObject.spec.template
&& inputObject.spec.template.spec && inputObject.spec.template.spec
&& inputObject.spec.template.spec.imagePullSecrets) { && inputObject.spec.template.spec.imagePullSecrets) {
return inputObject.spec.template.spec.imagePullSecrets; return inputObject.spec.template.spec.imagePullSecrets;
} }
} }
function setImagePullSecrets(inputObject, newImagePullSecrets) { function setImagePullSecrets(inputObject, newImagePullSecrets) {
if (!inputObject || !inputObject.spec || !newImagePullSecrets) { if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
return; return;
} }
if (utility_1.isEqual(inputObject.kind, 'pod')) { if (utility_1.isEqual(inputObject.kind, 'pod')) {
if (inputObject if (inputObject
&& inputObject.spec) { && inputObject.spec) {
if (newImagePullSecrets.length > 0) { if (newImagePullSecrets.length > 0) {
inputObject.spec.imagePullSecrets = newImagePullSecrets; inputObject.spec.imagePullSecrets = newImagePullSecrets;
} }
else { else {
delete inputObject.spec.imagePullSecrets; delete inputObject.spec.imagePullSecrets;
} }
} }
} }
else if (utility_1.isEqual(inputObject.kind, 'cronjob')) { else if (utility_1.isEqual(inputObject.kind, 'cronjob')) {
if (inputObject if (inputObject
&& inputObject.spec && inputObject.spec
&& inputObject.spec.jobTemplate && inputObject.spec.jobTemplate
&& inputObject.spec.jobTemplate.spec && inputObject.spec.jobTemplate.spec
&& inputObject.spec.jobTemplate.spec.template && inputObject.spec.jobTemplate.spec.template
&& inputObject.spec.jobTemplate.spec.template.spec) { && inputObject.spec.jobTemplate.spec.template.spec) {
if (newImagePullSecrets.length > 0) { if (newImagePullSecrets.length > 0) {
inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets; inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets;
} }
else { else {
delete inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets; delete inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
} }
} }
} }
else if (!!inputObject.spec.template && !!inputObject.spec.template.spec) { else if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
if (inputObject if (inputObject
&& inputObject.spec && inputObject.spec
&& inputObject.spec.template && inputObject.spec.template
&& inputObject.spec.template.spec) { && inputObject.spec.template.spec) {
if (newImagePullSecrets.length > 0) { if (newImagePullSecrets.length > 0) {
inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets; inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets;
} }
else { else {
delete inputObject.spec.template.spec.imagePullSecrets; delete inputObject.spec.template.spec.imagePullSecrets;
} }
} }
} }
} }
function substituteImageNameInSpecContent(currentString, imageName, imageNameWithNewTag) { function substituteImageNameInSpecContent(currentString, imageName, imageNameWithNewTag) {
if (currentString.indexOf(imageName) < 0) { if (currentString.indexOf(imageName) < 0) {
core.debug(`No occurence of replacement token: ${imageName} found`); core.debug(`No occurence of replacement token: ${imageName} found`);
return currentString; return currentString;
} }
return currentString.split('\n').reduce((acc, line) => { return currentString.split('\n').reduce((acc, line) => {
const imageKeyword = line.match(/^ *image:/); const imageKeyword = line.match(/^ *image:/);
if (imageKeyword) { if (imageKeyword) {
const [currentImageName, currentImageTag] = line const [currentImageName, currentImageTag] = line
.substring(imageKeyword[0].length) // consume the line from keyword onwards .substring(imageKeyword[0].length) // consume the line from keyword onwards
.trim() .trim()
.replace(/[',"]/g, '') // replace allowed quotes with nothing .replace(/[',"]/g, '') // replace allowed quotes with nothing
.split(':'); .split(':');
if (currentImageName === imageName) { if (currentImageName === imageName) {
return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`; return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`;
} }
} }
return acc + line + '\n'; return acc + line + '\n';
}, ''); }, '');
} }
function updateContainerImagesInManifestFiles(filePaths, containers) { function updateContainerImagesInManifestFiles(filePaths, containers) {
if (!!containers && containers.length > 0) { if (!!containers && containers.length > 0) {
const newFilePaths = []; const newFilePaths = [];
const tempDirectory = fileHelper.getTempDirectory(); const tempDirectory = fileHelper.getTempDirectory();
filePaths.forEach((filePath) => { filePaths.forEach((filePath) => {
let contents = fs.readFileSync(filePath).toString(); let contents = fs.readFileSync(filePath).toString();
containers.forEach((container) => { containers.forEach((container) => {
let imageName = container.split(':')[0]; let imageName = container.split(':')[0];
if (imageName.indexOf('@') > 0) { if (imageName.indexOf('@') > 0) {
imageName = imageName.split('@')[0]; imageName = imageName.split('@')[0];
} }
if (contents.indexOf(imageName) > 0) { if (contents.indexOf(imageName) > 0) {
contents = substituteImageNameInSpecFile(contents, imageName, container); contents = substituteImageNameInSpecFile(contents, imageName, container);
} }
}); });
const fileName = path.join(tempDirectory, path.basename(filePath)); const fileName = path.join(tempDirectory, path.basename(filePath));
fs.writeFileSync(path.join(fileName), contents); fs.writeFileSync(path.join(fileName), contents);
newFilePaths.push(fileName); newFilePaths.push(fileName);
}); });
return newFilePaths; return newFilePaths;
} }
return filePaths; return filePaths;
} }
function updateImagePullSecrets(inputObject, newImagePullSecrets) { function updateImagePullSecrets(inputObject, newImagePullSecrets) {
if (!inputObject || !inputObject.spec || !newImagePullSecrets) { if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
return; return;
} }
let newImagePullSecretsObjects; let newImagePullSecretsObjects;
if (newImagePullSecrets.length > 0) { if (newImagePullSecrets.length > 0) {
newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return !!x ? { 'name': x } : null; }); newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return !!x ? { 'name': x } : null; });
} }
else { else {
newImagePullSecretsObjects = []; newImagePullSecretsObjects = [];
} }
let existingImagePullSecretObjects = getImagePullSecrets(inputObject); let existingImagePullSecretObjects = getImagePullSecrets(inputObject);
if (!existingImagePullSecretObjects) { if (!existingImagePullSecretObjects) {
existingImagePullSecretObjects = new Array(); existingImagePullSecretObjects = new Array();
} }
existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects); existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects);
setImagePullSecrets(inputObject, existingImagePullSecretObjects); setImagePullSecrets(inputObject, existingImagePullSecretObjects);
} }
exports.updateImagePullSecrets = updateImagePullSecrets; exports.updateImagePullSecrets = updateImagePullSecrets;
function updateImagePullSecretsInManifestFiles(filePaths, imagePullSecrets) { function updateImagePullSecretsInManifestFiles(filePaths, imagePullSecrets) {
if (!!imagePullSecrets && imagePullSecrets.length > 0) { if (!!imagePullSecrets && imagePullSecrets.length > 0) {
const newObjectsList = []; const newObjectsList = [];
filePaths.forEach((filePath) => { filePaths.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath).toString(); const fileContents = fs.readFileSync(filePath).toString();
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
if (!!inputObject && !!inputObject.kind) { if (!!inputObject && !!inputObject.kind) {
const kind = inputObject.kind; const kind = inputObject.kind;
if (KubernetesObjectUtility.isWorkloadEntity(kind)) { if (KubernetesObjectUtility.isWorkloadEntity(kind)) {
KubernetesObjectUtility.updateImagePullSecrets(inputObject, imagePullSecrets, false); KubernetesObjectUtility.updateImagePullSecrets(inputObject, imagePullSecrets, false);
} }
newObjectsList.push(inputObject); newObjectsList.push(inputObject);
} }
}); });
}); });
core.debug('New K8s objects after adding imagePullSecrets are :' + JSON.stringify(newObjectsList)); core.debug('New K8s objects after adding imagePullSecrets are :' + JSON.stringify(newObjectsList));
const newFilePaths = fileHelper.writeObjectsToFile(newObjectsList); const newFilePaths = fileHelper.writeObjectsToFile(newObjectsList);
return newFilePaths; return newFilePaths;
} }
return filePaths; return filePaths;
} }
function getUpdatedManifestFiles(manifestFilePaths) { function getUpdatedManifestFiles(manifestFilePaths) {
let inputManifestFiles = getManifestFiles(manifestFilePaths); let inputManifestFiles = getManifestFiles(manifestFilePaths);
if (!inputManifestFiles || inputManifestFiles.length === 0) { if (!inputManifestFiles || inputManifestFiles.length === 0) {
throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`); throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`);
} }
// artifact substitution // artifact substitution
inputManifestFiles = updateContainerImagesInManifestFiles(inputManifestFiles, TaskInputParameters.containers); inputManifestFiles = updateContainerImagesInManifestFiles(inputManifestFiles, TaskInputParameters.containers);
// imagePullSecrets addition // imagePullSecrets addition
inputManifestFiles = updateImagePullSecretsInManifestFiles(inputManifestFiles, TaskInputParameters.imagePullSecrets); inputManifestFiles = updateImagePullSecretsInManifestFiles(inputManifestFiles, TaskInputParameters.imagePullSecrets);
return inputManifestFiles; return inputManifestFiles;
} }
exports.getUpdatedManifestFiles = getUpdatedManifestFiles; exports.getUpdatedManifestFiles = getUpdatedManifestFiles;
const workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob']; const workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
function isWorkloadEntity(kind) { function isWorkloadEntity(kind) {
if (!kind) { if (!kind) {
core.debug('ResourceKindNotDefined'); core.debug('ResourceKindNotDefined');
return false; return false;
} }
return workloadTypes.some((type) => { return workloadTypes.some((type) => {
return utility_1.isEqual(type, kind); return utility_1.isEqual(type, kind);
}); });
} }
exports.isWorkloadEntity = isWorkloadEntity; exports.isWorkloadEntity = isWorkloadEntity;

View File

@ -1,277 +1,277 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.getResources = exports.updateSelectorLabels = exports.updateSpecLabels = exports.updateImagePullSecrets = exports.updateObjectAnnotations = exports.updateObjectLabels = exports.getReplicaCount = exports.isIngressEntity = exports.isServiceEntity = exports.isWorkloadEntity = exports.isDeploymentEntity = void 0; exports.getResources = exports.updateSelectorLabels = exports.updateSpecLabels = exports.updateImagePullSecrets = exports.updateObjectAnnotations = exports.updateObjectLabels = exports.getReplicaCount = exports.isIngressEntity = exports.isServiceEntity = exports.isWorkloadEntity = exports.isDeploymentEntity = void 0;
const fs = require("fs"); const fs = require("fs");
const core = require("@actions/core"); const core = require("@actions/core");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const constants_1 = require("../constants"); const constants_1 = require("../constants");
const string_comparison_1 = require("./string-comparison"); const string_comparison_1 = require("./string-comparison");
const INGRESS = "Ingress"; const INGRESS = "Ingress";
function isDeploymentEntity(kind) { function isDeploymentEntity(kind) {
if (!kind) { if (!kind) {
throw ('ResourceKindNotDefined'); throw ('ResourceKindNotDefined');
} }
return constants_1.deploymentTypes.some((type) => { return constants_1.deploymentTypes.some((type) => {
return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase); return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
}); });
} }
exports.isDeploymentEntity = isDeploymentEntity; exports.isDeploymentEntity = isDeploymentEntity;
function isWorkloadEntity(kind) { function isWorkloadEntity(kind) {
if (!kind) { if (!kind) {
throw ('ResourceKindNotDefined'); throw ('ResourceKindNotDefined');
} }
return constants_1.workloadTypes.some((type) => { return constants_1.workloadTypes.some((type) => {
return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase); return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
}); });
} }
exports.isWorkloadEntity = isWorkloadEntity; exports.isWorkloadEntity = isWorkloadEntity;
function isServiceEntity(kind) { function isServiceEntity(kind) {
if (!kind) { if (!kind) {
throw ('ResourceKindNotDefined'); throw ('ResourceKindNotDefined');
} }
return string_comparison_1.isEqual("Service", kind, string_comparison_1.StringComparer.OrdinalIgnoreCase); return string_comparison_1.isEqual("Service", kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
} }
exports.isServiceEntity = isServiceEntity; exports.isServiceEntity = isServiceEntity;
function isIngressEntity(kind) { function isIngressEntity(kind) {
if (!kind) { if (!kind) {
throw ('ResourceKindNotDefined'); throw ('ResourceKindNotDefined');
} }
return string_comparison_1.isEqual(INGRESS, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase); return string_comparison_1.isEqual(INGRESS, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
} }
exports.isIngressEntity = isIngressEntity; exports.isIngressEntity = isIngressEntity;
function getReplicaCount(inputObject) { function getReplicaCount(inputObject) {
if (!inputObject) { if (!inputObject) {
throw ('NullInputObject'); throw ('NullInputObject');
} }
if (!inputObject.kind) { if (!inputObject.kind) {
throw ('ResourceKindNotDefined'); throw ('ResourceKindNotDefined');
} }
const kind = inputObject.kind; const kind = inputObject.kind;
if (!string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) && !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { if (!string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) && !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
return inputObject.spec.replicas; return inputObject.spec.replicas;
} }
return 0; return 0;
} }
exports.getReplicaCount = getReplicaCount; exports.getReplicaCount = getReplicaCount;
function updateObjectLabels(inputObject, newLabels, override) { function updateObjectLabels(inputObject, newLabels, override) {
if (!inputObject) { if (!inputObject) {
throw ('NullInputObject'); throw ('NullInputObject');
} }
if (!inputObject.metadata) { if (!inputObject.metadata) {
throw ('NullInputObjectMetadata'); throw ('NullInputObjectMetadata');
} }
if (!newLabels) { if (!newLabels) {
return; return;
} }
if (override) { if (override) {
inputObject.metadata.labels = newLabels; inputObject.metadata.labels = newLabels;
} }
else { else {
let existingLabels = inputObject.metadata.labels; let existingLabels = inputObject.metadata.labels;
if (!existingLabels) { if (!existingLabels) {
existingLabels = new Map(); existingLabels = new Map();
} }
Object.keys(newLabels).forEach(function (key) { Object.keys(newLabels).forEach(function (key) {
existingLabels[key] = newLabels[key]; existingLabels[key] = newLabels[key];
}); });
inputObject.metadata.labels = existingLabels; inputObject.metadata.labels = existingLabels;
} }
} }
exports.updateObjectLabels = updateObjectLabels; exports.updateObjectLabels = updateObjectLabels;
function updateObjectAnnotations(inputObject, newAnnotations, override) { function updateObjectAnnotations(inputObject, newAnnotations, override) {
if (!inputObject) { if (!inputObject) {
throw ('NullInputObject'); throw ('NullInputObject');
} }
if (!inputObject.metadata) { if (!inputObject.metadata) {
throw ('NullInputObjectMetadata'); throw ('NullInputObjectMetadata');
} }
if (!newAnnotations) { if (!newAnnotations) {
return; return;
} }
if (override) { if (override) {
inputObject.metadata.annotations = newAnnotations; inputObject.metadata.annotations = newAnnotations;
} }
else { else {
let existingAnnotations = inputObject.metadata.annotations; let existingAnnotations = inputObject.metadata.annotations;
if (!existingAnnotations) { if (!existingAnnotations) {
existingAnnotations = new Map(); existingAnnotations = new Map();
} }
Object.keys(newAnnotations).forEach(function (key) { Object.keys(newAnnotations).forEach(function (key) {
existingAnnotations[key] = newAnnotations[key]; existingAnnotations[key] = newAnnotations[key];
}); });
inputObject.metadata.annotations = existingAnnotations; inputObject.metadata.annotations = existingAnnotations;
} }
} }
exports.updateObjectAnnotations = updateObjectAnnotations; exports.updateObjectAnnotations = updateObjectAnnotations;
function updateImagePullSecrets(inputObject, newImagePullSecrets, override) { function updateImagePullSecrets(inputObject, newImagePullSecrets, override) {
if (!inputObject || !inputObject.spec || !newImagePullSecrets) { if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
return; return;
} }
const newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return { 'name': x }; }); const newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return { 'name': x }; });
let existingImagePullSecretObjects = getImagePullSecrets(inputObject); let existingImagePullSecretObjects = getImagePullSecrets(inputObject);
if (override) { if (override) {
existingImagePullSecretObjects = newImagePullSecretsObjects; existingImagePullSecretObjects = newImagePullSecretsObjects;
} }
else { else {
if (!existingImagePullSecretObjects) { if (!existingImagePullSecretObjects) {
existingImagePullSecretObjects = new Array(); existingImagePullSecretObjects = new Array();
} }
existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects); existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects);
} }
setImagePullSecrets(inputObject, existingImagePullSecretObjects); setImagePullSecrets(inputObject, existingImagePullSecretObjects);
} }
exports.updateImagePullSecrets = updateImagePullSecrets; exports.updateImagePullSecrets = updateImagePullSecrets;
function updateSpecLabels(inputObject, newLabels, override) { function updateSpecLabels(inputObject, newLabels, override) {
if (!inputObject) { if (!inputObject) {
throw ('NullInputObject'); throw ('NullInputObject');
} }
if (!inputObject.kind) { if (!inputObject.kind) {
throw ('ResourceKindNotDefined'); throw ('ResourceKindNotDefined');
} }
if (!newLabels) { if (!newLabels) {
return; return;
} }
let existingLabels = getSpecLabels(inputObject); let existingLabels = getSpecLabels(inputObject);
if (override) { if (override) {
existingLabels = newLabels; existingLabels = newLabels;
} }
else { else {
if (!existingLabels) { if (!existingLabels) {
existingLabels = new Map(); existingLabels = new Map();
} }
Object.keys(newLabels).forEach(function (key) { Object.keys(newLabels).forEach(function (key) {
existingLabels[key] = newLabels[key]; existingLabels[key] = newLabels[key];
}); });
} }
setSpecLabels(inputObject, existingLabels); setSpecLabels(inputObject, existingLabels);
} }
exports.updateSpecLabels = updateSpecLabels; exports.updateSpecLabels = updateSpecLabels;
function updateSelectorLabels(inputObject, newLabels, override) { function updateSelectorLabels(inputObject, newLabels, override) {
if (!inputObject) { if (!inputObject) {
throw ('NullInputObject'); throw ('NullInputObject');
} }
if (!inputObject.kind) { if (!inputObject.kind) {
throw ('ResourceKindNotDefined'); throw ('ResourceKindNotDefined');
} }
if (!newLabels) { if (!newLabels) {
return; return;
} }
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
return; return;
} }
let existingLabels = getSpecSelectorLabels(inputObject); let existingLabels = getSpecSelectorLabels(inputObject);
if (override) { if (override) {
existingLabels = newLabels; existingLabels = newLabels;
} }
else { else {
if (!existingLabels) { if (!existingLabels) {
existingLabels = new Map(); existingLabels = new Map();
} }
Object.keys(newLabels).forEach(function (key) { Object.keys(newLabels).forEach(function (key) {
existingLabels[key] = newLabels[key]; existingLabels[key] = newLabels[key];
}); });
} }
setSpecSelectorLabels(inputObject, existingLabels); setSpecSelectorLabels(inputObject, existingLabels);
} }
exports.updateSelectorLabels = updateSelectorLabels; exports.updateSelectorLabels = updateSelectorLabels;
function getResources(filePaths, filterResourceTypes) { function getResources(filePaths, filterResourceTypes) {
if (!filePaths) { if (!filePaths) {
return []; return [];
} }
const resources = []; const resources = [];
filePaths.forEach((filePath) => { filePaths.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const inputObjectKind = inputObject ? inputObject.kind : ''; const inputObjectKind = inputObject ? inputObject.kind : '';
if (filterResourceTypes.filter(type => string_comparison_1.isEqual(inputObjectKind, type, string_comparison_1.StringComparer.OrdinalIgnoreCase)).length > 0) { if (filterResourceTypes.filter(type => string_comparison_1.isEqual(inputObjectKind, type, string_comparison_1.StringComparer.OrdinalIgnoreCase)).length > 0) {
const resource = { const resource = {
type: inputObject.kind, type: inputObject.kind,
name: inputObject.metadata.name name: inputObject.metadata.name
}; };
resources.push(resource); resources.push(resource);
} }
}); });
}); });
return resources; return resources;
} }
exports.getResources = getResources; exports.getResources = getResources;
function getSpecLabels(inputObject) { function getSpecLabels(inputObject) {
if (!inputObject) { if (!inputObject) {
return null; return null;
} }
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
return inputObject.metadata.labels; return inputObject.metadata.labels;
} }
if (!!inputObject.spec && !!inputObject.spec.template && !!inputObject.spec.template.metadata) { if (!!inputObject.spec && !!inputObject.spec.template && !!inputObject.spec.template.metadata) {
return inputObject.spec.template.metadata.labels; return inputObject.spec.template.metadata.labels;
} }
return null; return null;
} }
function getImagePullSecrets(inputObject) { function getImagePullSecrets(inputObject) {
if (!inputObject || !inputObject.spec) { if (!inputObject || !inputObject.spec) {
return null; return null;
} }
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
try { try {
return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets; return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
} }
catch (ex) { catch (ex) {
core.debug(`Fetching imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`); core.debug(`Fetching imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`);
return null; return null;
} }
} }
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
return inputObject.spec.imagePullSecrets; return inputObject.spec.imagePullSecrets;
} }
if (!!inputObject.spec.template && !!inputObject.spec.template.spec) { if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
return inputObject.spec.template.spec.imagePullSecrets; return inputObject.spec.template.spec.imagePullSecrets;
} }
return null; return null;
} }
function setImagePullSecrets(inputObject, newImagePullSecrets) { function setImagePullSecrets(inputObject, newImagePullSecrets) {
if (!inputObject || !inputObject.spec || !newImagePullSecrets) { if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
return; return;
} }
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
inputObject.spec.imagePullSecrets = newImagePullSecrets; inputObject.spec.imagePullSecrets = newImagePullSecrets;
return; return;
} }
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
try { try {
inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets; inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets;
} }
catch (ex) { catch (ex) {
core.debug(`Overriding imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`); core.debug(`Overriding imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`);
//Do nothing //Do nothing
} }
return; return;
} }
if (!!inputObject.spec.template && !!inputObject.spec.template.spec) { if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets; inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets;
return; return;
} }
return; return;
} }
function setSpecLabels(inputObject, newLabels) { function setSpecLabels(inputObject, newLabels) {
let specLabels = getSpecLabels(inputObject); let specLabels = getSpecLabels(inputObject);
if (!!newLabels) { if (!!newLabels) {
specLabels = newLabels; specLabels = newLabels;
} }
} }
function getSpecSelectorLabels(inputObject) { function getSpecSelectorLabels(inputObject) {
if (!!inputObject && !!inputObject.spec && !!inputObject.spec.selector) { if (!!inputObject && !!inputObject.spec && !!inputObject.spec.selector) {
if (isServiceEntity(inputObject.kind)) { if (isServiceEntity(inputObject.kind)) {
return inputObject.spec.selector; return inputObject.spec.selector;
} }
else { else {
return inputObject.spec.selector.matchLabels; return inputObject.spec.selector.matchLabels;
} }
} }
return null; return null;
} }
function setSpecSelectorLabels(inputObject, newLabels) { function setSpecSelectorLabels(inputObject, newLabels) {
let selectorLabels = getSpecSelectorLabels(inputObject); let selectorLabels = getSpecSelectorLabels(inputObject);
if (!!selectorLabels) { if (!!selectorLabels) {
selectorLabels = newLabels; selectorLabels = newLabels;
} }
} }

View File

@ -1,187 +1,187 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.getStableResourceName = exports.getBaselineResourceName = exports.getCanaryResourceName = exports.isSMICanaryStrategy = exports.isCanaryDeploymentStrategy = exports.fetchResource = exports.fetchCanaryResource = exports.getNewCanaryResource = exports.getNewBaselineResource = exports.getStableResource = exports.isResourceMarkedAsStable = exports.markResourceAsStable = exports.deleteCanaryDeployment = exports.STABLE_LABEL_VALUE = exports.STABLE_SUFFIX = exports.CANARY_LABEL_VALUE = exports.BASELINE_LABEL_VALUE = exports.CANARY_VERSION_LABEL = exports.TRAFFIC_SPLIT_STRATEGY = exports.CANARY_DEPLOYMENT_STRATEGY = void 0; exports.getStableResourceName = exports.getBaselineResourceName = exports.getCanaryResourceName = exports.isSMICanaryStrategy = exports.isCanaryDeploymentStrategy = exports.fetchResource = exports.fetchCanaryResource = exports.getNewCanaryResource = exports.getNewBaselineResource = exports.getStableResource = exports.isResourceMarkedAsStable = exports.markResourceAsStable = exports.deleteCanaryDeployment = exports.STABLE_LABEL_VALUE = exports.STABLE_SUFFIX = exports.CANARY_LABEL_VALUE = exports.BASELINE_LABEL_VALUE = exports.CANARY_VERSION_LABEL = exports.TRAFFIC_SPLIT_STRATEGY = exports.CANARY_DEPLOYMENT_STRATEGY = void 0;
const fs = require("fs"); const fs = require("fs");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const core = require("@actions/core"); const core = require("@actions/core");
const TaskInputParameters = require("../../input-parameters"); const TaskInputParameters = require("../../input-parameters");
const helper = require("../resource-object-utility"); const helper = require("../resource-object-utility");
const constants_1 = require("../../constants"); const constants_1 = require("../../constants");
const string_comparison_1 = require("../string-comparison"); const string_comparison_1 = require("../string-comparison");
const utility_1 = require("../utility"); const utility_1 = require("../utility");
const utils = require("../manifest-utilities"); const utils = require("../manifest-utilities");
exports.CANARY_DEPLOYMENT_STRATEGY = 'CANARY'; exports.CANARY_DEPLOYMENT_STRATEGY = 'CANARY';
exports.TRAFFIC_SPLIT_STRATEGY = 'SMI'; exports.TRAFFIC_SPLIT_STRATEGY = 'SMI';
exports.CANARY_VERSION_LABEL = 'workflow/version'; exports.CANARY_VERSION_LABEL = 'workflow/version';
const BASELINE_SUFFIX = '-baseline'; const BASELINE_SUFFIX = '-baseline';
exports.BASELINE_LABEL_VALUE = 'baseline'; exports.BASELINE_LABEL_VALUE = 'baseline';
const CANARY_SUFFIX = '-canary'; const CANARY_SUFFIX = '-canary';
exports.CANARY_LABEL_VALUE = 'canary'; exports.CANARY_LABEL_VALUE = 'canary';
exports.STABLE_SUFFIX = '-stable'; exports.STABLE_SUFFIX = '-stable';
exports.STABLE_LABEL_VALUE = 'stable'; exports.STABLE_LABEL_VALUE = 'stable';
function deleteCanaryDeployment(kubectl, manifestFilePaths, includeServices) { function deleteCanaryDeployment(kubectl, manifestFilePaths, includeServices) {
// get manifest files // get manifest files
const inputManifestFiles = utils.getManifestFiles(manifestFilePaths); const inputManifestFiles = utils.getManifestFiles(manifestFilePaths);
if (inputManifestFiles == null || inputManifestFiles.length == 0) { if (inputManifestFiles == null || inputManifestFiles.length == 0) {
throw new Error('ManifestFileNotFound'); throw new Error('ManifestFileNotFound');
} }
// create delete cmd prefix // create delete cmd prefix
cleanUpCanary(kubectl, inputManifestFiles, includeServices); cleanUpCanary(kubectl, inputManifestFiles, includeServices);
} }
exports.deleteCanaryDeployment = deleteCanaryDeployment; exports.deleteCanaryDeployment = deleteCanaryDeployment;
function markResourceAsStable(inputObject) { function markResourceAsStable(inputObject) {
if (isResourceMarkedAsStable(inputObject)) { if (isResourceMarkedAsStable(inputObject)) {
return inputObject; return inputObject;
} }
const newObject = JSON.parse(JSON.stringify(inputObject)); const newObject = JSON.parse(JSON.stringify(inputObject));
// Adding labels and annotations. // Adding labels and annotations.
addCanaryLabelsAndAnnotations(newObject, exports.STABLE_LABEL_VALUE); addCanaryLabelsAndAnnotations(newObject, exports.STABLE_LABEL_VALUE);
core.debug("Added stable label: " + JSON.stringify(newObject)); core.debug("Added stable label: " + JSON.stringify(newObject));
return newObject; return newObject;
} }
exports.markResourceAsStable = markResourceAsStable; exports.markResourceAsStable = markResourceAsStable;
function isResourceMarkedAsStable(inputObject) { function isResourceMarkedAsStable(inputObject) {
return inputObject && return inputObject &&
inputObject.metadata && inputObject.metadata &&
inputObject.metadata.labels && inputObject.metadata.labels &&
inputObject.metadata.labels[exports.CANARY_VERSION_LABEL] == exports.STABLE_LABEL_VALUE; inputObject.metadata.labels[exports.CANARY_VERSION_LABEL] == exports.STABLE_LABEL_VALUE;
} }
exports.isResourceMarkedAsStable = isResourceMarkedAsStable; exports.isResourceMarkedAsStable = isResourceMarkedAsStable;
function getStableResource(inputObject) { function getStableResource(inputObject) {
var replicaCount = isSpecContainsReplicas(inputObject.kind) ? inputObject.metadata.replicas : 0; var replicaCount = isSpecContainsReplicas(inputObject.kind) ? inputObject.metadata.replicas : 0;
return getNewCanaryObject(inputObject, replicaCount, exports.STABLE_LABEL_VALUE); return getNewCanaryObject(inputObject, replicaCount, exports.STABLE_LABEL_VALUE);
} }
exports.getStableResource = getStableResource; exports.getStableResource = getStableResource;
function getNewBaselineResource(stableObject, replicas) { function getNewBaselineResource(stableObject, replicas) {
return getNewCanaryObject(stableObject, replicas, exports.BASELINE_LABEL_VALUE); return getNewCanaryObject(stableObject, replicas, exports.BASELINE_LABEL_VALUE);
} }
exports.getNewBaselineResource = getNewBaselineResource; exports.getNewBaselineResource = getNewBaselineResource;
function getNewCanaryResource(inputObject, replicas) { function getNewCanaryResource(inputObject, replicas) {
return getNewCanaryObject(inputObject, replicas, exports.CANARY_LABEL_VALUE); return getNewCanaryObject(inputObject, replicas, exports.CANARY_LABEL_VALUE);
} }
exports.getNewCanaryResource = getNewCanaryResource; exports.getNewCanaryResource = getNewCanaryResource;
function fetchCanaryResource(kubectl, kind, name) { function fetchCanaryResource(kubectl, kind, name) {
return fetchResource(kubectl, kind, getCanaryResourceName(name)); return fetchResource(kubectl, kind, getCanaryResourceName(name));
} }
exports.fetchCanaryResource = fetchCanaryResource; exports.fetchCanaryResource = fetchCanaryResource;
function fetchResource(kubectl, kind, name) { function fetchResource(kubectl, kind, name) {
const result = kubectl.getResource(kind, name); const result = kubectl.getResource(kind, name);
if (result == null || !!result.stderr) { if (result == null || !!result.stderr) {
return null; return null;
} }
if (!!result.stdout) { if (!!result.stdout) {
const resource = JSON.parse(result.stdout); const resource = JSON.parse(result.stdout);
try { try {
UnsetsClusterSpecficDetails(resource); UnsetsClusterSpecficDetails(resource);
return resource; return resource;
} }
catch (ex) { catch (ex) {
core.debug('Exception occurred while Parsing ' + resource + ' in Json object'); core.debug('Exception occurred while Parsing ' + resource + ' in Json object');
core.debug(`Exception:${ex}`); core.debug(`Exception:${ex}`);
} }
} }
return null; return null;
} }
exports.fetchResource = fetchResource; exports.fetchResource = fetchResource;
function isCanaryDeploymentStrategy() { function isCanaryDeploymentStrategy() {
const deploymentStrategy = TaskInputParameters.deploymentStrategy; const deploymentStrategy = TaskInputParameters.deploymentStrategy;
return deploymentStrategy && deploymentStrategy.toUpperCase() === exports.CANARY_DEPLOYMENT_STRATEGY; return deploymentStrategy && deploymentStrategy.toUpperCase() === exports.CANARY_DEPLOYMENT_STRATEGY;
} }
exports.isCanaryDeploymentStrategy = isCanaryDeploymentStrategy; exports.isCanaryDeploymentStrategy = isCanaryDeploymentStrategy;
function isSMICanaryStrategy() { function isSMICanaryStrategy() {
const deploymentStrategy = TaskInputParameters.trafficSplitMethod; const deploymentStrategy = TaskInputParameters.trafficSplitMethod;
return isCanaryDeploymentStrategy() && deploymentStrategy && deploymentStrategy.toUpperCase() === exports.TRAFFIC_SPLIT_STRATEGY; return isCanaryDeploymentStrategy() && deploymentStrategy && deploymentStrategy.toUpperCase() === exports.TRAFFIC_SPLIT_STRATEGY;
} }
exports.isSMICanaryStrategy = isSMICanaryStrategy; exports.isSMICanaryStrategy = isSMICanaryStrategy;
function getCanaryResourceName(name) { function getCanaryResourceName(name) {
return name + CANARY_SUFFIX; return name + CANARY_SUFFIX;
} }
exports.getCanaryResourceName = getCanaryResourceName; exports.getCanaryResourceName = getCanaryResourceName;
function getBaselineResourceName(name) { function getBaselineResourceName(name) {
return name + BASELINE_SUFFIX; return name + BASELINE_SUFFIX;
} }
exports.getBaselineResourceName = getBaselineResourceName; exports.getBaselineResourceName = getBaselineResourceName;
function getStableResourceName(name) { function getStableResourceName(name) {
return name + exports.STABLE_SUFFIX; return name + exports.STABLE_SUFFIX;
} }
exports.getStableResourceName = getStableResourceName; exports.getStableResourceName = getStableResourceName;
function UnsetsClusterSpecficDetails(resource) { function UnsetsClusterSpecficDetails(resource) {
if (resource == null) { if (resource == null) {
return; return;
} }
// Unsets the cluster specific details in the object // Unsets the cluster specific details in the object
if (!!resource) { if (!!resource) {
const metadata = resource.metadata; const metadata = resource.metadata;
const status = resource.status; const status = resource.status;
if (!!metadata) { if (!!metadata) {
const newMetadata = { const newMetadata = {
'annotations': metadata.annotations, 'annotations': metadata.annotations,
'labels': metadata.labels, 'labels': metadata.labels,
'name': metadata.name 'name': metadata.name
}; };
resource.metadata = newMetadata; resource.metadata = newMetadata;
} }
if (!!status) { if (!!status) {
resource.status = {}; resource.status = {};
} }
} }
} }
function getNewCanaryObject(inputObject, replicas, type) { function getNewCanaryObject(inputObject, replicas, type) {
const newObject = JSON.parse(JSON.stringify(inputObject)); const newObject = JSON.parse(JSON.stringify(inputObject));
// Updating name // Updating name
if (type === exports.CANARY_LABEL_VALUE) { if (type === exports.CANARY_LABEL_VALUE) {
newObject.metadata.name = getCanaryResourceName(inputObject.metadata.name); newObject.metadata.name = getCanaryResourceName(inputObject.metadata.name);
} }
else if (type === exports.STABLE_LABEL_VALUE) { else if (type === exports.STABLE_LABEL_VALUE) {
newObject.metadata.name = getStableResourceName(inputObject.metadata.name); newObject.metadata.name = getStableResourceName(inputObject.metadata.name);
} }
else { else {
newObject.metadata.name = getBaselineResourceName(inputObject.metadata.name); newObject.metadata.name = getBaselineResourceName(inputObject.metadata.name);
} }
// Adding labels and annotations. // Adding labels and annotations.
addCanaryLabelsAndAnnotations(newObject, type); addCanaryLabelsAndAnnotations(newObject, type);
// Updating no. of replicas // Updating no. of replicas
if (isSpecContainsReplicas(newObject.kind)) { if (isSpecContainsReplicas(newObject.kind)) {
newObject.spec.replicas = replicas; newObject.spec.replicas = replicas;
} }
return newObject; return newObject;
} }
function isSpecContainsReplicas(kind) { function isSpecContainsReplicas(kind) {
return !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) && return !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) &&
!string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase) && !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase) &&
!helper.isServiceEntity(kind); !helper.isServiceEntity(kind);
} }
function addCanaryLabelsAndAnnotations(inputObject, type) { function addCanaryLabelsAndAnnotations(inputObject, type) {
const newLabels = new Map(); const newLabels = new Map();
newLabels[exports.CANARY_VERSION_LABEL] = type; newLabels[exports.CANARY_VERSION_LABEL] = type;
helper.updateObjectLabels(inputObject, newLabels, false); helper.updateObjectLabels(inputObject, newLabels, false);
helper.updateObjectAnnotations(inputObject, newLabels, false); helper.updateObjectAnnotations(inputObject, newLabels, false);
helper.updateSelectorLabels(inputObject, newLabels, false); helper.updateSelectorLabels(inputObject, newLabels, false);
if (!helper.isServiceEntity(inputObject.kind)) { if (!helper.isServiceEntity(inputObject.kind)) {
helper.updateSpecLabels(inputObject, newLabels, false); helper.updateSpecLabels(inputObject, newLabels, false);
} }
} }
function cleanUpCanary(kubectl, files, includeServices) { function cleanUpCanary(kubectl, files, includeServices) {
var deleteObject = function (kind, name) { var deleteObject = function (kind, name) {
try { try {
const result = kubectl.delete([kind, name]); const result = kubectl.delete([kind, name]);
utility_1.checkForErrors([result]); utility_1.checkForErrors([result]);
} }
catch (ex) { catch (ex) {
// Ignore failures of delete if doesn't exist // Ignore failures of delete if doesn't exist
} }
}; };
files.forEach((filePath) => { files.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const name = inputObject.metadata.name; const name = inputObject.metadata.name;
const kind = inputObject.kind; const kind = inputObject.kind;
if (helper.isDeploymentEntity(kind) || (includeServices && helper.isServiceEntity(kind))) { if (helper.isDeploymentEntity(kind) || (includeServices && helper.isServiceEntity(kind))) {
const canaryObjectName = getCanaryResourceName(name); const canaryObjectName = getCanaryResourceName(name);
const baselineObjectName = getBaselineResourceName(name); const baselineObjectName = getBaselineResourceName(name);
deleteObject(kind, canaryObjectName); deleteObject(kind, canaryObjectName);
deleteObject(kind, baselineObjectName); deleteObject(kind, baselineObjectName);
} }
}); });
}); });
} }

View File

@ -1,148 +1,148 @@
'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.getManifestFiles = exports.deploy = void 0; exports.getManifestFiles = exports.deploy = void 0;
const fs = require("fs"); const fs = require("fs");
const core = require("@actions/core"); const core = require("@actions/core");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const canaryDeploymentHelper = require("./canary-deployment-helper"); const canaryDeploymentHelper = require("./canary-deployment-helper");
const KubernetesObjectUtility = require("../resource-object-utility"); const KubernetesObjectUtility = require("../resource-object-utility");
const TaskInputParameters = require("../../input-parameters"); const TaskInputParameters = require("../../input-parameters");
const models = require("../../constants"); const models = require("../../constants");
const fileHelper = require("../files-helper"); const fileHelper = require("../files-helper");
const utils = require("../manifest-utilities"); const utils = require("../manifest-utilities");
const KubernetesManifestUtility = require("../manifest-stability-utility"); const KubernetesManifestUtility = require("../manifest-stability-utility");
const KubernetesConstants = require("../../constants"); const KubernetesConstants = require("../../constants");
const manifest_utilities_1 = require("../manifest-utilities"); const manifest_utilities_1 = require("../manifest-utilities");
const pod_canary_deployment_helper_1 = require("./pod-canary-deployment-helper"); const pod_canary_deployment_helper_1 = require("./pod-canary-deployment-helper");
const smi_canary_deployment_helper_1 = require("./smi-canary-deployment-helper"); const smi_canary_deployment_helper_1 = require("./smi-canary-deployment-helper");
const utility_1 = require("../utility"); const utility_1 = require("../utility");
const blue_green_helper_1 = require("./blue-green-helper"); const blue_green_helper_1 = require("./blue-green-helper");
const service_blue_green_helper_1 = require("./service-blue-green-helper"); const service_blue_green_helper_1 = require("./service-blue-green-helper");
const ingress_blue_green_helper_1 = require("./ingress-blue-green-helper"); const ingress_blue_green_helper_1 = require("./ingress-blue-green-helper");
const smi_blue_green_helper_1 = require("./smi-blue-green-helper"); const smi_blue_green_helper_1 = require("./smi-blue-green-helper");
function deploy(kubectl, manifestFilePaths, deploymentStrategy) { function deploy(kubectl, manifestFilePaths, deploymentStrategy) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
// get manifest files // get manifest files
let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(manifestFilePaths); let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(manifestFilePaths);
// deployment // deployment
const deployedManifestFiles = deployManifests(inputManifestFiles, kubectl, isCanaryDeploymentStrategy(deploymentStrategy), blue_green_helper_1.isBlueGreenDeploymentStrategy()); const deployedManifestFiles = deployManifests(inputManifestFiles, kubectl, isCanaryDeploymentStrategy(deploymentStrategy), blue_green_helper_1.isBlueGreenDeploymentStrategy());
// check manifest stability // check manifest stability
const resourceTypes = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([KubernetesConstants.DiscoveryAndLoadBalancerResource.service])); const resourceTypes = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([KubernetesConstants.DiscoveryAndLoadBalancerResource.service]));
yield checkManifestStability(kubectl, resourceTypes); yield checkManifestStability(kubectl, resourceTypes);
// route blue-green deployments // route blue-green deployments
if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) { if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) {
yield blue_green_helper_1.routeBlueGreen(kubectl, inputManifestFiles); yield blue_green_helper_1.routeBlueGreen(kubectl, inputManifestFiles);
} }
// print ingress resources // print ingress resources
const ingressResources = KubernetesObjectUtility.getResources(deployedManifestFiles, [KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress]); const ingressResources = KubernetesObjectUtility.getResources(deployedManifestFiles, [KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress]);
ingressResources.forEach(ingressResource => { ingressResources.forEach(ingressResource => {
kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress, ingressResource.name); kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress, ingressResource.name);
}); });
// annotate resources // annotate resources
let allPods; let allPods;
try { try {
allPods = JSON.parse((kubectl.getAllPods()).stdout); allPods = JSON.parse((kubectl.getAllPods()).stdout);
} }
catch (e) { catch (e) {
core.debug("Unable to parse pods; Error: " + e); core.debug("Unable to parse pods; Error: " + e);
} }
annotateResources(deployedManifestFiles, kubectl, resourceTypes, allPods); annotateResources(deployedManifestFiles, kubectl, resourceTypes, allPods);
}); });
} }
exports.deploy = deploy; exports.deploy = deploy;
function getManifestFiles(manifestFilePaths) { function getManifestFiles(manifestFilePaths) {
const files = utils.getManifestFiles(manifestFilePaths); const files = utils.getManifestFiles(manifestFilePaths);
if (files == null || files.length === 0) { if (files == null || files.length === 0) {
throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`); throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`);
} }
return files; return files;
} }
exports.getManifestFiles = getManifestFiles; exports.getManifestFiles = getManifestFiles;
function deployManifests(files, kubectl, isCanaryDeploymentStrategy, isBlueGreenDeploymentStrategy) { function deployManifests(files, kubectl, isCanaryDeploymentStrategy, isBlueGreenDeploymentStrategy) {
let result; let result;
if (isCanaryDeploymentStrategy) { if (isCanaryDeploymentStrategy) {
let canaryDeploymentOutput; let canaryDeploymentOutput;
if (canaryDeploymentHelper.isSMICanaryStrategy()) { if (canaryDeploymentHelper.isSMICanaryStrategy()) {
canaryDeploymentOutput = smi_canary_deployment_helper_1.deploySMICanary(kubectl, files); canaryDeploymentOutput = smi_canary_deployment_helper_1.deploySMICanary(kubectl, files);
} }
else { else {
canaryDeploymentOutput = pod_canary_deployment_helper_1.deployPodCanary(kubectl, files); canaryDeploymentOutput = pod_canary_deployment_helper_1.deployPodCanary(kubectl, files);
} }
result = canaryDeploymentOutput.result; result = canaryDeploymentOutput.result;
files = canaryDeploymentOutput.newFilePaths; files = canaryDeploymentOutput.newFilePaths;
} }
else if (isBlueGreenDeploymentStrategy) { else if (isBlueGreenDeploymentStrategy) {
let blueGreenDeploymentOutput; let blueGreenDeploymentOutput;
if (blue_green_helper_1.isIngressRoute()) { if (blue_green_helper_1.isIngressRoute()) {
blueGreenDeploymentOutput = ingress_blue_green_helper_1.deployBlueGreenIngress(kubectl, files); blueGreenDeploymentOutput = ingress_blue_green_helper_1.deployBlueGreenIngress(kubectl, files);
} }
else if (blue_green_helper_1.isSMIRoute()) { else if (blue_green_helper_1.isSMIRoute()) {
blueGreenDeploymentOutput = smi_blue_green_helper_1.deployBlueGreenSMI(kubectl, files); blueGreenDeploymentOutput = smi_blue_green_helper_1.deployBlueGreenSMI(kubectl, files);
} }
else { else {
blueGreenDeploymentOutput = service_blue_green_helper_1.deployBlueGreenService(kubectl, files); blueGreenDeploymentOutput = service_blue_green_helper_1.deployBlueGreenService(kubectl, files);
} }
result = blueGreenDeploymentOutput.result; result = blueGreenDeploymentOutput.result;
files = blueGreenDeploymentOutput.newFilePaths; files = blueGreenDeploymentOutput.newFilePaths;
} }
else { else {
if (canaryDeploymentHelper.isSMICanaryStrategy()) { if (canaryDeploymentHelper.isSMICanaryStrategy()) {
const updatedManifests = appendStableVersionLabelToResource(files, kubectl); const updatedManifests = appendStableVersionLabelToResource(files, kubectl);
result = kubectl.apply(updatedManifests, TaskInputParameters.forceDeployment); result = kubectl.apply(updatedManifests, TaskInputParameters.forceDeployment);
} }
else { else {
result = kubectl.apply(files, TaskInputParameters.forceDeployment); result = kubectl.apply(files, TaskInputParameters.forceDeployment);
} }
} }
utility_1.checkForErrors([result]); utility_1.checkForErrors([result]);
return files; return files;
} }
function appendStableVersionLabelToResource(files, kubectl) { function appendStableVersionLabelToResource(files, kubectl) {
const manifestFiles = []; const manifestFiles = [];
const newObjectsList = []; const newObjectsList = [];
files.forEach((filePath) => { files.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const kind = inputObject.kind; const kind = inputObject.kind;
if (KubernetesObjectUtility.isDeploymentEntity(kind)) { if (KubernetesObjectUtility.isDeploymentEntity(kind)) {
const updatedObject = canaryDeploymentHelper.markResourceAsStable(inputObject); const updatedObject = canaryDeploymentHelper.markResourceAsStable(inputObject);
newObjectsList.push(updatedObject); newObjectsList.push(updatedObject);
} }
else { else {
manifestFiles.push(filePath); manifestFiles.push(filePath);
} }
}); });
}); });
const updatedManifestFiles = fileHelper.writeObjectsToFile(newObjectsList); const updatedManifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
manifestFiles.push(...updatedManifestFiles); manifestFiles.push(...updatedManifestFiles);
return manifestFiles; return manifestFiles;
} }
function checkManifestStability(kubectl, resources) { function checkManifestStability(kubectl, resources) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
yield KubernetesManifestUtility.checkManifestStability(kubectl, resources); yield KubernetesManifestUtility.checkManifestStability(kubectl, resources);
}); });
} }
function annotateResources(files, kubectl, resourceTypes, allPods) { function annotateResources(files, kubectl, resourceTypes, allPods) {
const annotateResults = []; const annotateResults = [];
annotateResults.push(utility_1.annotateNamespace(kubectl, TaskInputParameters.namespace)); annotateResults.push(utility_1.annotateNamespace(kubectl, TaskInputParameters.namespace));
annotateResults.push(kubectl.annotateFiles(files, models.workflowAnnotations, true)); annotateResults.push(kubectl.annotateFiles(files, models.workflowAnnotations, true));
resourceTypes.forEach(resource => { resourceTypes.forEach(resource => {
if (resource.type.toUpperCase() !== models.KubernetesWorkload.pod.toUpperCase()) { if (resource.type.toUpperCase() !== models.KubernetesWorkload.pod.toUpperCase()) {
utility_1.annotateChildPods(kubectl, resource.type, resource.name, allPods) utility_1.annotateChildPods(kubectl, resource.type, resource.name, allPods)
.forEach(execResult => annotateResults.push(execResult)); .forEach(execResult => annotateResults.push(execResult));
} }
}); });
utility_1.checkForErrors(annotateResults, true); utility_1.checkForErrors(annotateResults, true);
} }
function isCanaryDeploymentStrategy(deploymentStrategy) { function isCanaryDeploymentStrategy(deploymentStrategy) {
return deploymentStrategy != null && deploymentStrategy.toUpperCase() === canaryDeploymentHelper.CANARY_DEPLOYMENT_STRATEGY.toUpperCase(); return deploymentStrategy != null && deploymentStrategy.toUpperCase() === canaryDeploymentHelper.CANARY_DEPLOYMENT_STRATEGY.toUpperCase();
} }

View File

@ -1,58 +1,58 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.deployPodCanary = void 0; exports.deployPodCanary = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const fs = require("fs"); const fs = require("fs");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const TaskInputParameters = require("../../input-parameters"); const TaskInputParameters = require("../../input-parameters");
const fileHelper = require("../files-helper"); const fileHelper = require("../files-helper");
const helper = require("../resource-object-utility"); const helper = require("../resource-object-utility");
const canaryDeploymentHelper = require("./canary-deployment-helper"); const canaryDeploymentHelper = require("./canary-deployment-helper");
function deployPodCanary(kubectl, filePaths) { function deployPodCanary(kubectl, filePaths) {
const newObjectsList = []; const newObjectsList = [];
const percentage = parseInt(TaskInputParameters.canaryPercentage); const percentage = parseInt(TaskInputParameters.canaryPercentage);
filePaths.forEach((filePath) => { filePaths.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const name = inputObject.metadata.name; const name = inputObject.metadata.name;
const kind = inputObject.kind; const kind = inputObject.kind;
if (helper.isDeploymentEntity(kind)) { if (helper.isDeploymentEntity(kind)) {
core.debug('Calculating replica count for canary'); core.debug('Calculating replica count for canary');
const canaryReplicaCount = calculateReplicaCountForCanary(inputObject, percentage); const canaryReplicaCount = calculateReplicaCountForCanary(inputObject, percentage);
core.debug('Replica count is ' + canaryReplicaCount); core.debug('Replica count is ' + canaryReplicaCount);
// Get stable object // Get stable object
core.debug('Querying stable object'); core.debug('Querying stable object');
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name); const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name);
if (!stableObject) { if (!stableObject) {
core.debug('Stable object not found. Creating only canary object'); core.debug('Stable object not found. Creating only canary object');
// If stable object not found, create canary deployment. // If stable object not found, create canary deployment.
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount); const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject)); core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
newObjectsList.push(newCanaryObject); newObjectsList.push(newCanaryObject);
} }
else { else {
core.debug('Stable object found. Creating canary and baseline objects'); core.debug('Stable object found. Creating canary and baseline objects');
// If canary object not found, create canary and baseline object. // If canary object not found, create canary and baseline object.
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount); const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount); const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount);
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject)); core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject)); core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject));
newObjectsList.push(newCanaryObject); newObjectsList.push(newCanaryObject);
newObjectsList.push(newBaselineObject); newObjectsList.push(newBaselineObject);
} }
} }
else { else {
// Updating non deployment entity as it is. // Updating non deployment entity as it is.
newObjectsList.push(inputObject); newObjectsList.push(inputObject);
} }
}); });
}); });
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList); const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment); const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
return { 'result': result, 'newFilePaths': manifestFiles }; return { 'result': result, 'newFilePaths': manifestFiles };
} }
exports.deployPodCanary = deployPodCanary; exports.deployPodCanary = deployPodCanary;
function calculateReplicaCountForCanary(inputObject, percentage) { function calculateReplicaCountForCanary(inputObject, percentage) {
const inputReplicaCount = helper.getReplicaCount(inputObject); const inputReplicaCount = helper.getReplicaCount(inputObject);
return Math.round((inputReplicaCount * percentage) / 100); return Math.round((inputReplicaCount * percentage) / 100);
} }

View File

@ -1,172 +1,172 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.redirectTrafficToStableDeployment = exports.redirectTrafficToCanaryDeployment = exports.deploySMICanary = void 0; exports.redirectTrafficToStableDeployment = exports.redirectTrafficToCanaryDeployment = exports.deploySMICanary = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const fs = require("fs"); const fs = require("fs");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const util = require("util"); const util = require("util");
const TaskInputParameters = require("../../input-parameters"); const TaskInputParameters = require("../../input-parameters");
const fileHelper = require("../files-helper"); const fileHelper = require("../files-helper");
const helper = require("../resource-object-utility"); const helper = require("../resource-object-utility");
const utils = require("../manifest-utilities"); const utils = require("../manifest-utilities");
const kubectlUtils = require("../kubectl-util"); const kubectlUtils = require("../kubectl-util");
const canaryDeploymentHelper = require("./canary-deployment-helper"); const canaryDeploymentHelper = require("./canary-deployment-helper");
const utility_1 = require("../utility"); const utility_1 = require("../utility");
const TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX = '-workflow-rollout'; const TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX = '-workflow-rollout';
const TRAFFIC_SPLIT_OBJECT = 'TrafficSplit'; const TRAFFIC_SPLIT_OBJECT = 'TrafficSplit';
let trafficSplitAPIVersion = ""; let trafficSplitAPIVersion = "";
function deploySMICanary(kubectl, filePaths) { function deploySMICanary(kubectl, filePaths) {
const newObjectsList = []; const newObjectsList = [];
const canaryReplicaCount = parseInt(TaskInputParameters.baselineAndCanaryReplicas); const canaryReplicaCount = parseInt(TaskInputParameters.baselineAndCanaryReplicas);
core.debug('Replica count is ' + canaryReplicaCount); core.debug('Replica count is ' + canaryReplicaCount);
filePaths.forEach((filePath) => { filePaths.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const name = inputObject.metadata.name; const name = inputObject.metadata.name;
const kind = inputObject.kind; const kind = inputObject.kind;
if (helper.isDeploymentEntity(kind)) { if (helper.isDeploymentEntity(kind)) {
// Get stable object // Get stable object
core.debug('Querying stable object'); core.debug('Querying stable object');
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name); const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name);
if (!stableObject) { if (!stableObject) {
core.debug('Stable object not found. Creating only canary object'); core.debug('Stable object not found. Creating only canary object');
// If stable object not found, create canary deployment. // If stable object not found, create canary deployment.
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount); const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject)); core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
newObjectsList.push(newCanaryObject); newObjectsList.push(newCanaryObject);
} }
else { else {
if (!canaryDeploymentHelper.isResourceMarkedAsStable(stableObject)) { if (!canaryDeploymentHelper.isResourceMarkedAsStable(stableObject)) {
throw (`StableSpecSelectorNotExist : ${name}`); throw (`StableSpecSelectorNotExist : ${name}`);
} }
core.debug('Stable object found. Creating canary and baseline objects'); core.debug('Stable object found. Creating canary and baseline objects');
// If canary object not found, create canary and baseline object. // If canary object not found, create canary and baseline object.
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount); const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount); const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount);
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject)); core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject)); core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject));
newObjectsList.push(newCanaryObject); newObjectsList.push(newCanaryObject);
newObjectsList.push(newBaselineObject); newObjectsList.push(newBaselineObject);
} }
} }
else { else {
// Updating non deployment entity as it is. // Updating non deployment entity as it is.
newObjectsList.push(inputObject); newObjectsList.push(inputObject);
} }
}); });
}); });
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList); const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment); const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
createCanaryService(kubectl, filePaths); createCanaryService(kubectl, filePaths);
return { 'result': result, 'newFilePaths': manifestFiles }; return { 'result': result, 'newFilePaths': manifestFiles };
} }
exports.deploySMICanary = deploySMICanary; exports.deploySMICanary = deploySMICanary;
function createCanaryService(kubectl, filePaths) { function createCanaryService(kubectl, filePaths) {
const newObjectsList = []; const newObjectsList = [];
const trafficObjectsList = []; const trafficObjectsList = [];
filePaths.forEach((filePath) => { filePaths.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const name = inputObject.metadata.name; const name = inputObject.metadata.name;
const kind = inputObject.kind; const kind = inputObject.kind;
if (helper.isServiceEntity(kind)) { if (helper.isServiceEntity(kind)) {
const newCanaryServiceObject = canaryDeploymentHelper.getNewCanaryResource(inputObject); const newCanaryServiceObject = canaryDeploymentHelper.getNewCanaryResource(inputObject);
core.debug('New canary service object is: ' + JSON.stringify(newCanaryServiceObject)); core.debug('New canary service object is: ' + JSON.stringify(newCanaryServiceObject));
newObjectsList.push(newCanaryServiceObject); newObjectsList.push(newCanaryServiceObject);
const newBaselineServiceObject = canaryDeploymentHelper.getNewBaselineResource(inputObject); const newBaselineServiceObject = canaryDeploymentHelper.getNewBaselineResource(inputObject);
core.debug('New baseline object is: ' + JSON.stringify(newBaselineServiceObject)); core.debug('New baseline object is: ' + JSON.stringify(newBaselineServiceObject));
newObjectsList.push(newBaselineServiceObject); newObjectsList.push(newBaselineServiceObject);
core.debug('Querying for stable service object'); core.debug('Querying for stable service object');
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, canaryDeploymentHelper.getStableResourceName(name)); const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, canaryDeploymentHelper.getStableResourceName(name));
if (!stableObject) { if (!stableObject) {
const newStableServiceObject = canaryDeploymentHelper.getStableResource(inputObject); const newStableServiceObject = canaryDeploymentHelper.getStableResource(inputObject);
core.debug('New stable service object is: ' + JSON.stringify(newStableServiceObject)); core.debug('New stable service object is: ' + JSON.stringify(newStableServiceObject));
newObjectsList.push(newStableServiceObject); newObjectsList.push(newStableServiceObject);
core.debug('Creating the traffic object for service: ' + name); core.debug('Creating the traffic object for service: ' + name);
const trafficObject = createTrafficSplitManifestFile(kubectl, name, 0, 0, 1000); const trafficObject = createTrafficSplitManifestFile(kubectl, name, 0, 0, 1000);
core.debug('Creating the traffic object for service: ' + trafficObject); core.debug('Creating the traffic object for service: ' + trafficObject);
trafficObjectsList.push(trafficObject); trafficObjectsList.push(trafficObject);
} }
else { else {
let updateTrafficObject = true; let updateTrafficObject = true;
const trafficObject = canaryDeploymentHelper.fetchResource(kubectl, TRAFFIC_SPLIT_OBJECT, getTrafficSplitResourceName(name)); const trafficObject = canaryDeploymentHelper.fetchResource(kubectl, TRAFFIC_SPLIT_OBJECT, getTrafficSplitResourceName(name));
if (trafficObject) { if (trafficObject) {
const trafficJObject = JSON.parse(JSON.stringify(trafficObject)); const trafficJObject = JSON.parse(JSON.stringify(trafficObject));
if (trafficJObject && trafficJObject.spec && trafficJObject.spec.backends) { if (trafficJObject && trafficJObject.spec && trafficJObject.spec.backends) {
trafficJObject.spec.backends.forEach((s) => { trafficJObject.spec.backends.forEach((s) => {
if (s.service === canaryDeploymentHelper.getCanaryResourceName(name) && s.weight === "1000m") { if (s.service === canaryDeploymentHelper.getCanaryResourceName(name) && s.weight === "1000m") {
core.debug('Update traffic objcet not required'); core.debug('Update traffic objcet not required');
updateTrafficObject = false; updateTrafficObject = false;
} }
}); });
} }
} }
if (updateTrafficObject) { if (updateTrafficObject) {
core.debug('Stable service object present so updating the traffic object for service: ' + name); core.debug('Stable service object present so updating the traffic object for service: ' + name);
trafficObjectsList.push(updateTrafficSplitObject(kubectl, name)); trafficObjectsList.push(updateTrafficSplitObject(kubectl, name));
} }
} }
} }
}); });
}); });
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList); const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
manifestFiles.push(...trafficObjectsList); manifestFiles.push(...trafficObjectsList);
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment); const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
utility_1.checkForErrors([result]); utility_1.checkForErrors([result]);
} }
function redirectTrafficToCanaryDeployment(kubectl, manifestFilePaths) { function redirectTrafficToCanaryDeployment(kubectl, manifestFilePaths) {
adjustTraffic(kubectl, manifestFilePaths, 0, 1000); adjustTraffic(kubectl, manifestFilePaths, 0, 1000);
} }
exports.redirectTrafficToCanaryDeployment = redirectTrafficToCanaryDeployment; exports.redirectTrafficToCanaryDeployment = redirectTrafficToCanaryDeployment;
function redirectTrafficToStableDeployment(kubectl, manifestFilePaths) { function redirectTrafficToStableDeployment(kubectl, manifestFilePaths) {
adjustTraffic(kubectl, manifestFilePaths, 1000, 0); adjustTraffic(kubectl, manifestFilePaths, 1000, 0);
} }
exports.redirectTrafficToStableDeployment = redirectTrafficToStableDeployment; exports.redirectTrafficToStableDeployment = redirectTrafficToStableDeployment;
function adjustTraffic(kubectl, manifestFilePaths, stableWeight, canaryWeight) { function adjustTraffic(kubectl, manifestFilePaths, stableWeight, canaryWeight) {
// get manifest files // get manifest files
const inputManifestFiles = utils.getManifestFiles(manifestFilePaths); const inputManifestFiles = utils.getManifestFiles(manifestFilePaths);
if (inputManifestFiles == null || inputManifestFiles.length == 0) { if (inputManifestFiles == null || inputManifestFiles.length == 0) {
return; return;
} }
const trafficSplitManifests = []; const trafficSplitManifests = [];
const serviceObjects = []; const serviceObjects = [];
inputManifestFiles.forEach((filePath) => { inputManifestFiles.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const name = inputObject.metadata.name; const name = inputObject.metadata.name;
const kind = inputObject.kind; const kind = inputObject.kind;
if (helper.isServiceEntity(kind)) { if (helper.isServiceEntity(kind)) {
trafficSplitManifests.push(createTrafficSplitManifestFile(kubectl, name, stableWeight, 0, canaryWeight)); trafficSplitManifests.push(createTrafficSplitManifestFile(kubectl, name, stableWeight, 0, canaryWeight));
serviceObjects.push(name); serviceObjects.push(name);
} }
}); });
}); });
if (trafficSplitManifests.length <= 0) { if (trafficSplitManifests.length <= 0) {
return; return;
} }
const result = kubectl.apply(trafficSplitManifests, TaskInputParameters.forceDeployment); const result = kubectl.apply(trafficSplitManifests, TaskInputParameters.forceDeployment);
core.debug('serviceObjects:' + serviceObjects.join(',') + ' result:' + result); core.debug('serviceObjects:' + serviceObjects.join(',') + ' result:' + result);
utility_1.checkForErrors([result]); utility_1.checkForErrors([result]);
} }
function updateTrafficSplitObject(kubectl, serviceName) { function updateTrafficSplitObject(kubectl, serviceName) {
const percentage = parseInt(TaskInputParameters.canaryPercentage) * 10; const percentage = parseInt(TaskInputParameters.canaryPercentage) * 10;
const baselineAndCanaryWeight = percentage / 2; const baselineAndCanaryWeight = percentage / 2;
const stableDeploymentWeight = 1000 - percentage; const stableDeploymentWeight = 1000 - percentage;
core.debug('Creating the traffic object with canary weight: ' + baselineAndCanaryWeight + ',baseling weight: ' + baselineAndCanaryWeight + ',stable: ' + stableDeploymentWeight); core.debug('Creating the traffic object with canary weight: ' + baselineAndCanaryWeight + ',baseling weight: ' + baselineAndCanaryWeight + ',stable: ' + stableDeploymentWeight);
return createTrafficSplitManifestFile(kubectl, serviceName, stableDeploymentWeight, baselineAndCanaryWeight, baselineAndCanaryWeight); return createTrafficSplitManifestFile(kubectl, serviceName, stableDeploymentWeight, baselineAndCanaryWeight, baselineAndCanaryWeight);
} }
function createTrafficSplitManifestFile(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight) { function createTrafficSplitManifestFile(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight) {
const smiObjectString = getTrafficSplitObject(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight); const smiObjectString = getTrafficSplitObject(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight);
const manifestFile = fileHelper.writeManifestToFile(smiObjectString, TRAFFIC_SPLIT_OBJECT, serviceName); const manifestFile = fileHelper.writeManifestToFile(smiObjectString, TRAFFIC_SPLIT_OBJECT, serviceName);
if (!manifestFile) { if (!manifestFile) {
throw new Error('UnableToCreateTrafficSplitManifestFile'); throw new Error('UnableToCreateTrafficSplitManifestFile');
} }
return manifestFile; return manifestFile;
} }
function getTrafficSplitObject(kubectl, name, stableWeight, baselineWeight, canaryWeight) { function getTrafficSplitObject(kubectl, name, stableWeight, baselineWeight, canaryWeight) {
if (!trafficSplitAPIVersion) { if (!trafficSplitAPIVersion) {
trafficSplitAPIVersion = kubectlUtils.getTrafficSplitAPIVersion(kubectl); trafficSplitAPIVersion = kubectlUtils.getTrafficSplitAPIVersion(kubectl);
} }
const trafficSplitObjectJson = `{ const trafficSplitObjectJson = `{
"apiVersion": "${trafficSplitAPIVersion}", "apiVersion": "${trafficSplitAPIVersion}",
"kind": "TrafficSplit", "kind": "TrafficSplit",
@ -190,10 +190,10 @@ function getTrafficSplitObject(kubectl, name, stableWeight, baselineWeight, cana
], ],
"service": "%s" "service": "%s"
} }
}`; }`;
const trafficSplitObject = util.format(trafficSplitObjectJson, getTrafficSplitResourceName(name), canaryDeploymentHelper.getStableResourceName(name), stableWeight, canaryDeploymentHelper.getBaselineResourceName(name), baselineWeight, canaryDeploymentHelper.getCanaryResourceName(name), canaryWeight, name); const trafficSplitObject = util.format(trafficSplitObjectJson, getTrafficSplitResourceName(name), canaryDeploymentHelper.getStableResourceName(name), stableWeight, canaryDeploymentHelper.getBaselineResourceName(name), baselineWeight, canaryDeploymentHelper.getCanaryResourceName(name), canaryWeight, name);
return trafficSplitObject; return trafficSplitObject;
} }
function getTrafficSplitResourceName(name) { function getTrafficSplitResourceName(name) {
return name + TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX; return name + TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX;
} }

View File

@ -1,26 +1,26 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.isEqual = exports.StringComparer = void 0; exports.isEqual = exports.StringComparer = void 0;
var StringComparer; var StringComparer;
(function (StringComparer) { (function (StringComparer) {
StringComparer[StringComparer["Ordinal"] = 0] = "Ordinal"; StringComparer[StringComparer["Ordinal"] = 0] = "Ordinal";
StringComparer[StringComparer["OrdinalIgnoreCase"] = 1] = "OrdinalIgnoreCase"; StringComparer[StringComparer["OrdinalIgnoreCase"] = 1] = "OrdinalIgnoreCase";
})(StringComparer = exports.StringComparer || (exports.StringComparer = {})); })(StringComparer = exports.StringComparer || (exports.StringComparer = {}));
function isEqual(str1, str2, stringComparer) { function isEqual(str1, str2, stringComparer) {
if (str1 == null && str2 == null) { if (str1 == null && str2 == null) {
return true; return true;
} }
if (str1 == null) { if (str1 == null) {
return false; return false;
} }
if (str2 == null) { if (str2 == null) {
return false; return false;
} }
if (stringComparer == StringComparer.OrdinalIgnoreCase) { if (stringComparer == StringComparer.OrdinalIgnoreCase) {
return str1.toUpperCase() === str2.toUpperCase(); return str1.toUpperCase() === str2.toUpperCase();
} }
else { else {
return str1 === str2; return str1 === str2;
} }
} }
exports.isEqual = isEqual; exports.isEqual = isEqual;

File diff suppressed because it is too large Load Diff

View File

@ -1,108 +1,108 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.getCurrentTime = exports.getRandomInt = exports.sleep = exports.annotateNamespace = exports.annotateChildPods = exports.checkForErrors = exports.isEqual = exports.getExecutableExtension = void 0; exports.getCurrentTime = exports.getRandomInt = exports.sleep = exports.annotateNamespace = exports.annotateChildPods = 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 constants_1 = require("../constants"); const constants_1 = require("../constants");
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 annotateChildPods(kubectl, resourceType, resourceName, allPods) { function annotateChildPods(kubectl, resourceType, resourceName, 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) {
for (let ownerRef of owners) { for (let ownerRef of owners) {
if (ownerRef.name === owner) { if (ownerRef.name === owner) {
commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, constants_1.workflowAnnotations, true)); commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, constants_1.workflowAnnotations, true));
break; break;
} }
} }
} }
}); });
} }
return commandExecutionResults; return commandExecutionResults;
} }
exports.annotateChildPods = annotateChildPods; exports.annotateChildPods = annotateChildPods;
function annotateNamespace(kubectl, namespaceName) { function annotateNamespace(kubectl, namespaceName) {
const result = kubectl.getResource('namespace', namespaceName); const result = kubectl.getResource('namespace', namespaceName);
if (!result) { if (!result) {
return { code: 1, stderr: 'Failed to get resource' }; return { code: 1, stderr: 'Failed to get resource' };
} }
else { else {
if (result.stderr) { if (result.stderr) {
return result; return result;
} }
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.runUri) { if (annotationsSet && annotationsSet.runUri) {
if (annotationsSet.runUri.indexOf(process.env['GITHUB_REPOSITORY']) == -1) { if (annotationsSet.runUri.indexOf(process.env['GITHUB_REPOSITORY']) == -1) {
core.debug(`Skipping 'annotate namespace' as namespace annotated by other workflow`); core.debug(`Skipping 'annotate namespace' as namespace annotated by other workflow`);
return { code: 0, stdout: '' }; return { code: 0, stdout: '' };
} }
} }
return kubectl.annotate('namespace', namespaceName, constants_1.workflowAnnotations, true); return kubectl.annotate('namespace', namespaceName, constants_1.workflowAnnotations, true);
} }
} }
} }
exports.annotateNamespace = annotateNamespace; exports.annotateNamespace = annotateNamespace;
function sleep(timeout) { function sleep(timeout) {
return new Promise(resolve => setTimeout(resolve, timeout)); return new Promise(resolve => setTimeout(resolve, timeout));
} }
exports.sleep = sleep; exports.sleep = sleep;
function getRandomInt(max) { function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max)); return Math.floor(Math.random() * Math.floor(max));
} }
exports.getRandomInt = getRandomInt; exports.getRandomInt = getRandomInt;
function getCurrentTime() { function getCurrentTime() {
return new Date().getTime(); return new Date().getTime();
} }
exports.getCurrentTime = getCurrentTime; exports.getCurrentTime = getCurrentTime;