UNPKG

@adastradev/serverless-discovery-plugin

Version:

Serverless plugin to register/de-register endpoints upon deploy and remove command hooks

309 lines (308 loc) 16.7 kB
"use strict"; 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()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); // tslint:disable-next-line: no-var-requires var assert = require('assert'); var util = require("util"); var serverless_discovery_sdk_1 = require("@adastradev/serverless-discovery-sdk"); var file_1 = require("./file"); var PluginIAMCredentials_1 = require("./PluginIAMCredentials"); var ServiceDiscoveryPlugin = /** @class */ (function () { function ServiceDiscoveryPlugin(serverless, options) { this.serverless = serverless; this.options = options; this.hooks = { 'after:deploy:deploy': this.deploy.bind(this), 'before:remove:remove': this.remove.bind(this) }; this.discoveryConfig = this.serverless.service.custom.discovery; } Object.defineProperty(ServiceDiscoveryPlugin.prototype, "file", { get: function () { return this.getConfigPathValue('file'); }, enumerable: false, configurable: true }); Object.defineProperty(ServiceDiscoveryPlugin.prototype, "deployHandler", { get: function () { return this.getConfigPathValue('deployHandler'); }, enumerable: false, configurable: true }); Object.defineProperty(ServiceDiscoveryPlugin.prototype, "removeHandler", { get: function () { return this.getConfigPathValue('removeHandler'); }, enumerable: false, configurable: true }); Object.defineProperty(ServiceDiscoveryPlugin.prototype, "discoveryServiceUri", { get: function () { return this.getConfig('discoveryServiceUri'); }, enumerable: false, configurable: true }); Object.defineProperty(ServiceDiscoveryPlugin.prototype, "stackName", { get: function () { return this.serverless.getProvider('aws').naming.getStackName(); }, enumerable: false, configurable: true }); ServiceDiscoveryPlugin.prototype.hasConfig = function (key) { return !!this.discoveryConfig && !!this.discoveryConfig[key]; }; ServiceDiscoveryPlugin.prototype.hasDeployHandler = function () { return this.hasConfig('deployHandler'); }; ServiceDiscoveryPlugin.prototype.hasRemoveHandler = function () { return this.hasConfig('removeHandler'); }; ServiceDiscoveryPlugin.prototype.hasDiscoveryServiceUri = function () { return this.hasConfig('discoveryServiceUri'); }; ServiceDiscoveryPlugin.prototype.hasFile = function () { return this.hasConfig('file'); }; ServiceDiscoveryPlugin.prototype.processDeploymentPropTags = function (propData, deploymentData) { var result; this.serverless.cli.log("Processing deployment prop tags ".concat(JSON.stringify(propData), " in serviceUrl")); if (!propData) { return result; } result = {}; for (var _i = 0, _a = Object.keys(propData); _i < _a.length; _i++) { var property = _a[_i]; var childProp = propData[property]; this.serverless.cli.log("Processing property ".concat(property, " in serviceUrl")); // see if this child property is using the @DeploymentProp if (childProp['@DeploymentProp']) { result[property] = deploymentData[childProp['@DeploymentProp']]; this.serverless.cli.log("Using deployment property ".concat(childProp['@DeploymentProp'], " in serviceUrl")); } else { result[property] = propData[property]; } } return result; }; ServiceDiscoveryPlugin.prototype.getConfigPathValue = function (key) { return util.format('%s/%s', this.serverless.config.servicePath, this.discoveryConfig[key]); }; ServiceDiscoveryPlugin.prototype.getConfig = function (key) { return this.discoveryConfig[key]; }; ServiceDiscoveryPlugin.prototype.callHandler = function (handler, data) { var splits = handler.split('.'); var func = splits.pop() || ''; var file = splits.join('.'); return require(file)[func](data, this.serverless, this.options); }; ServiceDiscoveryPlugin.prototype.saveFile = function (data) { var f = new file_1.default(this.file); return f.save(data); }; ServiceDiscoveryPlugin.prototype.fetch = function () { return this.serverless.getProvider('aws').request('CloudFormation', 'describeStacks', { StackName: this.stackName }, this.serverless.getProvider('aws').getStage(), this.serverless.getProvider('aws').getRegion()); }; ServiceDiscoveryPlugin.prototype.beautify = function (data) { var stack = data.Stacks.pop() || { Outputs: [] }; var output = stack.Outputs || []; return output.reduce(function (obj, item) { var _a; return (Object.assign(obj, (_a = {}, _a[item.OutputKey] = item.OutputValue, _a))); }, {}); }; ServiceDiscoveryPlugin.prototype.handleDeploy = function (data) { return Promise.all([ this.register(data), this.handleDeployHandler(data), this.handleFile(data) ]); }; ServiceDiscoveryPlugin.prototype.handleRemove = function (data) { return Promise.all([ this.deregister(data), this.handleRemoveHandler(data) ]); }; ServiceDiscoveryPlugin.prototype.register = function (data) { var _this = this; return this.hasDiscoveryServiceUri() ? (new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { var discoveryApi, customServiceUrl, service, result; return __generator(this, function (_a) { switch (_a.label) { case 0: this.serverless.cli.log('Registering service endpoint with service: ' + this.discoveryServiceUri); discoveryApi = new serverless_discovery_sdk_1.DiscoveryServiceApi(this.discoveryServiceUri, this.serverless.getProvider('aws').getRegion(), new PluginIAMCredentials_1.PluginIAMCredentials(this.discoveryConfig)); customServiceUrl = this.processDeploymentPropTags(this.getConfig('serviceURL'), data); service = { ExternalID: this.getConfig('externalID'), ServiceName: this.serverless.service.getServiceName(), // This data variable is looking for the service endpoint from CloudFormation // The alternative will look for a custom, freeform field under custom.discovery // in the Serverless.yml ServiceURL: JSON.stringify(customServiceUrl) || data['ServiceEndpoint'], StageName: this.serverless.getProvider('aws').getStage(), Version: this.getConfig('version') }; this.serverless.cli.log("Registering: ".concat(JSON.stringify(service))); return [4 /*yield*/, discoveryApi.createService(service)]; case 1: result = _a.sent(); this.serverless.cli.log('Successfully registered.'); return [2 /*return*/, resolve(result)]; } }); }); })) : Promise.resolve(); }; ServiceDiscoveryPlugin.prototype.deregister = function (data) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2 /*return*/, this.hasDiscoveryServiceUri() ? (new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { var discoveryApi, response, existingService; return __generator(this, function (_a) { switch (_a.label) { case 0: this.serverless.cli.log('De-registering service endpoint with service: ' + this.discoveryServiceUri); discoveryApi = new serverless_discovery_sdk_1.DiscoveryServiceApi(this.discoveryServiceUri, this.serverless.getProvider('aws').getRegion(), new PluginIAMCredentials_1.PluginIAMCredentials(this.discoveryConfig)); return [4 /*yield*/, discoveryApi.lookupService(this.serverless.service.getServiceName(), this.serverless.getProvider('aws').getStage(), this.getConfig('version'), this.getConfig('externalID'))]; case 1: response = _a.sent(); existingService = response.data[0]; if (!(existingService !== undefined && existingService.ServiceID !== undefined)) return [3 /*break*/, 3]; this.serverless.cli.log("Found service to delete: ".concat(JSON.stringify(existingService))); return [4 /*yield*/, discoveryApi.deleteService(existingService.ServiceID)]; case 2: _a.sent(); this.serverless.cli.log('Successfully de-registered service'); return [2 /*return*/, resolve(existingService.ServiceID)]; case 3: this.serverless.cli.log('No service registration record was found for this service name and stage'); return [2 /*return*/, resolve(null)]; } }); }); })) : Promise.resolve()]; }); }); }; ServiceDiscoveryPlugin.prototype.handleDeployHandler = function (data) { var _this = this; return this.hasDeployHandler() ? (this.callHandler(this.deployHandler, data).then(function () { return _this.serverless.cli.log(util.format('Stack Output processed with handler: %s', _this.deployHandler)); })) : Promise.resolve(); }; ServiceDiscoveryPlugin.prototype.handleRemoveHandler = function (data) { var _this = this; return this.hasRemoveHandler() ? (this.callHandler(this.removeHandler, data).then(function () { return _this.serverless.cli.log(util.format('Stack Output processed with handler: %s', _this.removeHandler)); })) : Promise.resolve(); }; ServiceDiscoveryPlugin.prototype.handleFile = function (data) { var _this = this; return this.hasFile() ? (this.saveFile(data).then(function () { return _this.serverless.cli.log(util.format('Stack Output saved to file: %s', _this.discoveryConfig.file)); })) : Promise.resolve(); }; ServiceDiscoveryPlugin.prototype.validate = function () { assert(this.serverless, 'Invalid serverless configuration'); assert(this.serverless.service, 'Invalid serverless configuration'); assert(this.serverless.service.provider, 'Invalid serverless configuration'); assert(this.serverless.service.provider.name, 'Invalid serverless configuration'); assert(this.serverless.service.provider.name === 'aws', 'Only supported for AWS provider'); assert(this.options && !this.options.noDeploy, 'Skipping deployment with --noDeploy flag'); }; ServiceDiscoveryPlugin.prototype.deploy = function () { return __awaiter(this, void 0, void 0, function () { var rawData, beautifulData, Error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 5, , 6]); return [4 /*yield*/, this.validate()]; case 1: _a.sent(); return [4 /*yield*/, this.fetch()]; case 2: rawData = _a.sent(); return [4 /*yield*/, this.beautify(rawData)]; case 3: beautifulData = _a.sent(); return [4 /*yield*/, this.handleDeploy(beautifulData)]; case 4: _a.sent(); return [3 /*break*/, 6]; case 5: Error_1 = _a.sent(); this.serverless.cli.log(util.format('Cannot process Discovery Plugin: %s!', Error_1.message)); return [3 /*break*/, 6]; case 6: return [2 /*return*/]; } }); }); }; ServiceDiscoveryPlugin.prototype.remove = function () { return __awaiter(this, void 0, void 0, function () { var rawData, beautifulData, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 5, , 6]); return [4 /*yield*/, this.validate()]; case 1: _a.sent(); return [4 /*yield*/, this.fetch()]; case 2: rawData = _a.sent(); return [4 /*yield*/, this.beautify(rawData)]; case 3: beautifulData = _a.sent(); return [4 /*yield*/, this.handleRemove(beautifulData)]; case 4: _a.sent(); return [3 /*break*/, 6]; case 5: error_1 = _a.sent(); this.serverless.cli.log(util.format('Cannot process Discovery Plugin: %s!', error_1.message)); return [3 /*break*/, 6]; case 6: return [2 /*return*/]; } }); }); }; return ServiceDiscoveryPlugin; }()); exports.default = ServiceDiscoveryPlugin;