@fbl-plugins/k8s-kubectl
Version:
FBL plugin for K8s Kubectl CLI
182 lines • 7.36 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
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 step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseActionProcessor = void 0;
const fbl_1 = require("fbl");
const js_yaml_1 = require("js-yaml");
const util_1 = require("util");
const fs_1 = require("fs");
const crypto_1 = require("crypto");
const glob = require("glob");
const path_1 = require("path");
const writeFileAsync = util_1.promisify(fs_1.writeFile);
class BaseActionProcessor extends fbl_1.ActionProcessor {
/**
* Execute "helm" command
* @return {Promise<IExecOutput>}
*/
execKubectlCommand(args, debug, joinWith = '\n') {
return __awaiter(this, void 0, void 0, function* () {
const childProcessService = fbl_1.ChildProcessService.instance;
const stdout = [];
const stderr = [];
if (debug) {
this.snapshot.log(`Running command "kubectl ${args.join(' ')}"`);
}
const code = yield childProcessService.exec('kubectl', args, this.snapshot.wd, {
stdout: (chunk) => {
stdout.push(chunk.toString().trim());
},
stderr: (chunk) => {
stderr.push(chunk.toString().trim());
},
});
if (code !== 0 || debug) {
this.snapshot.log('exit code: ' + code, true);
/* istanbul ignore else */
if (stdout) {
this.snapshot.log('stdout: ' + stdout, true);
}
/* istanbul ignore else */
if (stderr) {
this.snapshot.log('sterr: ' + stderr, true);
}
}
if (code !== 0) {
throw new Error(`"kubectl ${args.join(' ')}" command failed.`);
}
return {
code,
stdout: stdout.join(joinWith),
stderr: stderr.join(joinWith),
};
});
}
/**
* Push argument with value if value exists
*/
pushWithValue(args, name, value) {
if (value !== undefined) {
args.push(name, value.toString());
}
}
/**
* Push multiple arguments with value
*/
pushMultipleWithValue(args, name, values, transformer) {
return __awaiter(this, void 0, void 0, function* () {
if (values) {
for (const value of values) {
let transformed = value;
/* istanbul ignore else */
if (transformer) {
transformed = yield transformer(value);
}
args.push(name, transformed.toString());
}
}
});
}
/**
* Push argument only if value is true
*/
pushWithoutValue(args, name, value) {
if (value) {
args.push(name);
}
}
/**
* Write string to temp file
* @returns temp file path
*/
writeStringToTempFile(data) {
return __awaiter(this, void 0, void 0, function* () {
const tempPathsRegistry = fbl_1.TempPathsRegistry.instance;
const filePath = yield tempPathsRegistry.createTempFile(false, '.yaml');
yield writeFileAsync(filePath, data, 'utf8');
return filePath;
});
}
/**
* Write YAML to temp file
* @returns temp file path
*/
writeYamlToTempFile(data) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.writeStringToTempFile(js_yaml_1.dump(data));
});
}
/**
* Write JSON to temp file
* @returns temp file path
*/
writeJsonToTempFile(data) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.writeStringToTempFile(JSON.stringify(data));
});
}
getHash(path) {
return crypto_1.createHash('sha256').update(path, 'utf8').digest('hex');
}
/**
* Process glob path
*/
processGlobPath(path, targetDir) {
return __awaiter(this, void 0, void 0, function* () {
const absolutePath = fbl_1.FSUtil.getAbsolutePath(path, this.snapshot.wd);
const matches = yield util_1.promisify(glob)(absolutePath);
const dir = path_1.join(targetDir, this.getHash(absolutePath));
yield fbl_1.FSUtil.mkdirp(dir);
let i = 0;
for (const match of matches) {
let ext = path_1.extname(match);
ext = ext && ext.toLowerCase();
/* istanbul ignore else */
if (['.json', '.yml', '.yaml'].indexOf(ext) >= 0) {
const filePath = path_1.join(dir, `${i++}_${path_1.basename(match)}`);
yield this.processTemplateFile(match, filePath);
}
}
if (i === 0) {
throw new Error(`Unable to find any json or yaml files matching: ${path}`);
}
});
}
processTemplateFile(sourcePath, targetPath) {
return __awaiter(this, void 0, void 0, function* () {
const flowService = fbl_1.FlowService.instance;
const absolutePath = fbl_1.FSUtil.getAbsolutePath(sourcePath, this.snapshot.wd);
let fileContent = yield fbl_1.FSUtil.readTextFile(absolutePath);
if (!fileContent) {
throw new Error(`File is empty. ${sourcePath}`);
}
// resolve global template
fileContent = yield flowService.resolveTemplate(this.context.ejsTemplateDelimiters.global, fileContent, this.context, this.snapshot, this.parameters);
const raw = js_yaml_1.loadAll(fileContent);
const docs = [];
for (const doc of raw) {
// resolve local template
let fileContentObject = yield flowService.resolveOptionsWithNoHandlerCheck(this.context.ejsTemplateDelimiters.local, doc, this.context, this.snapshot, this.parameters, false);
// resolve references
fileContentObject = fbl_1.ContextUtil.resolveReferences(fileContentObject, this.context, this.parameters);
docs.push(fileContentObject);
}
if (docs.length === 1) {
yield writeFileAsync(targetPath, js_yaml_1.dump(docs[0]), 'utf8');
}
else {
yield writeFileAsync(targetPath, '---\n' + docs.map((d) => js_yaml_1.dump(d)).join('\n---\n'), 'utf8');
}
});
}
}
exports.BaseActionProcessor = BaseActionProcessor;
//# sourceMappingURL=BaseActionProcessor.js.map