@brunwig/mup-aws-beanstalk 0.8.6 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/.babelrc +15 -4
  2. package/.eslintrc.yml +2 -2
  3. package/.yarn/install-state.gz +0 -0
  4. package/docs/getting-started.md +1 -1
  5. package/docs/index.md +22 -6
  6. package/index.js +1 -1
  7. package/lib/assets/Procfile +1 -0
  8. package/lib/assets/health-check.js +9 -1
  9. package/lib/assets/health-check.js.map +1 -1
  10. package/lib/assets/nginx-server.conf +14 -0
  11. package/lib/assets/nginx.conf +6 -0
  12. package/lib/assets/node.sh +37 -7
  13. package/lib/assets/npm.sh +14 -0
  14. package/lib/assets/prevent-npm.sh +4 -0
  15. package/lib/assets/role-start.sh +61 -0
  16. package/lib/assets/start.sh +1 -1
  17. package/lib/assets/yarn.sh +17 -0
  18. package/lib/aws.js +43 -77
  19. package/lib/aws.js.map +1 -1
  20. package/lib/certificates.js +56 -53
  21. package/lib/certificates.js.map +1 -1
  22. package/lib/command-handlers.js +615 -634
  23. package/lib/command-handlers.js.map +1 -1
  24. package/lib/commands.js +144 -106
  25. package/lib/commands.js.map +1 -1
  26. package/lib/deployment-logs.js +127 -0
  27. package/lib/deployment-logs.js.map +1 -0
  28. package/lib/download.js +11 -18
  29. package/lib/download.js.map +1 -1
  30. package/lib/eb-config.js +246 -242
  31. package/lib/eb-config.js.map +1 -1
  32. package/lib/env-ready.js +87 -88
  33. package/lib/env-ready.js.map +1 -1
  34. package/lib/env-settings.js +13 -14
  35. package/lib/env-settings.js.map +1 -1
  36. package/lib/index.js +111 -81
  37. package/lib/index.js.map +1 -1
  38. package/lib/policies.js +130 -115
  39. package/lib/policies.js.map +1 -1
  40. package/lib/prepare-bundle.js +187 -194
  41. package/lib/prepare-bundle.js.map +1 -1
  42. package/lib/recheck.js +16 -13
  43. package/lib/recheck.js.map +1 -1
  44. package/lib/tsconfig.tsbuildinfo +1 -0
  45. package/lib/types.js +3 -0
  46. package/lib/types.js.map +1 -0
  47. package/lib/upload.js +35 -49
  48. package/lib/upload.js.map +1 -1
  49. package/lib/utils.js +561 -529
  50. package/lib/utils.js.map +1 -1
  51. package/lib/validate.js +61 -59
  52. package/lib/validate.js.map +1 -1
  53. package/lib/versions.js +74 -81
  54. package/lib/versions.js.map +1 -1
  55. package/package.json +60 -26
  56. package/readme.md +2 -1
  57. package/tsconfig.json +41 -0
@@ -1,689 +1,670 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
5
17
  });
6
- exports.clean = clean;
7
- exports.debug = debug;
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.setup = setup;
8
40
  exports.deploy = deploy;
9
- exports.events = events;
10
41
  exports.logs = logs;
11
- exports.logsEb = logsEb;
42
+ exports.fullLogs = fullLogs;
12
43
  exports.logsNginx = logsNginx;
13
- exports.reconfig = reconfig;
14
- exports.restart = restart;
15
- exports.setup = setup;
16
- exports.shell = shell;
17
- exports.ssl = ssl;
44
+ exports.logsEb = logsEb;
18
45
  exports.start = start;
19
- exports.status = status;
20
46
  exports.stop = stop;
21
- var _chalk = _interopRequireDefault(require("chalk"));
22
- var _ssh = require("ssh2");
23
- var _aws = require("./aws");
24
- var _certificates = _interopRequireDefault(require("./certificates"));
25
- var _policies = require("./policies");
26
- var _upload = _interopRequireWildcard(require("./upload"));
27
- var _prepareBundle = require("./prepare-bundle");
28
- var _utils = require("./utils");
29
- var _versions = require("./versions");
30
- var _envSettings = require("./env-settings");
31
- var _ebConfig = require("./eb-config");
32
- var _envReady = require("./env-ready");
33
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
34
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
35
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
36
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
37
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
38
- function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
39
- function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
40
- function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
47
+ exports.restart = restart;
48
+ exports.clean = clean;
49
+ exports.reconfig = reconfig;
50
+ exports.events = events;
51
+ exports.status = status;
52
+ exports.ssl = ssl;
53
+ exports.shell = shell;
54
+ exports.debug = debug;
55
+ const chalk_1 = __importDefault(require("chalk"));
56
+ const ssh2_1 = require("ssh2");
57
+ const aws_1 = require("./aws");
58
+ const certificates_1 = require("./certificates");
59
+ const policies_1 = require("./policies");
60
+ const upload_1 = __importStar(require("./upload"));
61
+ const prepare_bundle_1 = require("./prepare-bundle");
62
+ const utils_1 = require("./utils");
63
+ const versions_1 = require("./versions");
64
+ const env_settings_1 = require("./env-settings");
65
+ const eb_config_1 = require("./eb-config");
66
+ const env_ready_1 = require("./env-ready");
67
+ const deployment_logs_1 = require("./deployment-logs");
68
+ const client_elastic_beanstalk_1 = require("@aws-sdk/client-elastic-beanstalk");
41
69
  async function setup(api) {
42
- const config = api.getConfig();
43
- const appConfig = config.app;
44
- const {
45
- bucket: bucketName,
46
- app: appName,
47
- instanceProfile,
48
- serviceRole: serviceRoleName,
49
- trailBucketPrefix,
50
- trailName,
51
- deregisterRuleName,
52
- environment: environmentName,
53
- eventTargetRole: eventTargetRoleName,
54
- eventTargetPolicyName,
55
- eventTargetPassRoleName,
56
- automationDocument
57
- } = (0, _utils.names)(config);
58
- (0, _utils.logStep)('=> @Brunwig/mup-aws-beanstalk');
59
- (0, _utils.logStep)('=> Setting up');
60
-
61
- // Create bucket if needed
62
- const {
63
- Buckets
64
- } = await _aws.s3.listBuckets().promise();
65
- const beanstalkBucketCreated = await (0, _utils.ensureBucketExists)(Buckets, bucketName, appConfig.region);
66
- if (beanstalkBucketCreated) {
67
- console.log(' Created Bucket');
68
- }
69
- (0, _utils.logStep)('=> Ensuring IAM Roles and Instance Profiles are setup');
70
-
71
- // Create role and instance profile
72
- await (0, _utils.ensureRoleExists)(instanceProfile, _policies.rolePolicy);
73
- await (0, _utils.ensureInstanceProfileExists)(config, instanceProfile);
74
- await (0, _utils.ensurePoliciesAttached)(config, instanceProfile, ['arn:aws:iam::aws:policy/AWSElasticBeanstalkWebTier', 'arn:aws:iam::aws:policy/AWSElasticBeanstalkMulticontainerDocker', 'arn:aws:iam::aws:policy/AWSElasticBeanstalkWorkerTier', ...(appConfig.gracefulShutdown ? ['arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM'] : [])]);
75
- await (0, _utils.ensureRoleAdded)(config, instanceProfile, instanceProfile);
76
-
77
- // Create role used by enhanced health
78
- await (0, _utils.ensureRoleExists)(serviceRoleName, _policies.serviceRole);
79
- await (0, _utils.ensurePoliciesAttached)(config, serviceRoleName, ['arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkEnhancedHealth', 'arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkService']);
80
- if (appConfig.gracefulShutdown) {
81
- const accountId = await (0, _utils.getAccountId)();
82
- const policy = (0, _policies.eventTargetRolePolicy)(accountId, environmentName, appConfig.region || 'us-east-1');
83
- const passPolicy = (0, _policies.passRolePolicy)(accountId, eventTargetRoleName);
84
- await (0, _utils.ensureRoleExists)(eventTargetRoleName, _policies.eventTargetRole, true);
85
- await (0, _utils.ensureInlinePolicyAttached)(eventTargetRoleName, eventTargetPolicyName, policy);
86
- await (0, _utils.ensureInlinePolicyAttached)(eventTargetRoleName, eventTargetPassRoleName, passPolicy);
87
- }
88
-
89
- // Create beanstalk application if needed
90
- const {
91
- Applications
92
- } = await _aws.beanstalk.describeApplications().promise();
93
- if (!Applications.find(app => app.ApplicationName === appName)) {
94
- const params = {
95
- ApplicationName: appName,
96
- Description: `App "${appConfig.name}" managed by Meteor Up`
97
- };
98
- await _aws.beanstalk.createApplication(params).promise();
99
- console.log(' Created Beanstalk application');
100
- }
101
- if (appConfig.gracefulShutdown) {
102
- (0, _utils.logStep)('=> Ensuring Graceful Shutdown is setup');
103
- const existingBucket = (0, _utils.findBucketWithPrefix)(Buckets, trailBucketPrefix);
104
- const trailBucketName = existingBucket ? existingBucket.Name : (0, _utils.createUniqueName)(trailBucketPrefix);
105
- const region = appConfig.region || 'us-east-1';
106
- const accountId = await (0, _utils.getAccountId)();
107
- const policy = (0, _policies.trailBucketPolicy)(accountId, trailBucketName);
108
- const trailBucketCreated = await (0, _utils.ensureBucketExists)(Buckets, trailBucketName, appConfig.region);
109
- await (0, _utils.ensureBucketPolicyAttached)(trailBucketName, policy);
110
- if (trailBucketCreated) {
111
- console.log(' Created bucket for Cloud Trail');
112
- }
113
- const params = {
114
- trailNameList: [trailName]
115
- };
116
- const {
117
- trailList
118
- } = await _aws.cloudTrail.describeTrails(params).promise();
119
- if (trailList.length === 0) {
120
- const createParams = {
121
- Name: trailName,
122
- S3BucketName: trailBucketName
123
- };
124
- await _aws.cloudTrail.createTrail(createParams).promise();
125
- console.log(' Created CloudTrail trail');
70
+ const config = api.getConfig();
71
+ const appConfig = config.app;
72
+ const { bucket: bucketName, app: appName, instanceProfile, serviceRole: serviceRoleName, trailBucketPrefix, trailName, deregisterRuleName, environment: environmentName, eventTargetRole: eventTargetRoleName, eventTargetPolicyName, eventTargetPassRoleName, automationDocument } = (0, utils_1.names)(config);
73
+ (0, utils_1.logStep)('=> @Brunwig/mup-aws-beanstalk');
74
+ (0, utils_1.logStep)('=> Setting up');
75
+ // Create bucket if needed
76
+ const listBucketResult = await aws_1.s3.listBuckets({});
77
+ const Buckets = listBucketResult.Buckets;
78
+ const beanstalkBucketCreated = await (0, utils_1.ensureBucketExists)(Buckets, bucketName, appConfig.region);
79
+ if (beanstalkBucketCreated) {
80
+ console.log(' Created Bucket');
126
81
  }
127
- const createdDocument = await (0, _utils.ensureSsmDocument)(automationDocument, (0, _policies.gracefulShutdownAutomationDocument)());
128
- if (createdDocument) {
129
- console.log(' Created SSM Automation Document');
82
+ (0, utils_1.logStep)('=> Ensuring IAM Roles and Instance Profiles are setup');
83
+ // Create role and instance profile
84
+ await (0, utils_1.ensureRoleExists)(instanceProfile, policies_1.rolePolicy);
85
+ await (0, utils_1.ensureInstanceProfileExists)(instanceProfile);
86
+ await (0, utils_1.ensurePoliciesAttached)(instanceProfile, [
87
+ 'arn:aws:iam::aws:policy/AWSElasticBeanstalkWebTier',
88
+ 'arn:aws:iam::aws:policy/AWSElasticBeanstalkMulticontainerDocker',
89
+ 'arn:aws:iam::aws:policy/AWSElasticBeanstalkWorkerTier',
90
+ ...appConfig.gracefulShutdown ? ['arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM'] : []
91
+ ]);
92
+ await (0, utils_1.ensureRoleAdded)(instanceProfile, instanceProfile);
93
+ // Create role used by enhanced health
94
+ await (0, utils_1.ensureRoleExists)(serviceRoleName, policies_1.serviceRole);
95
+ await (0, utils_1.ensurePoliciesAttached)(serviceRoleName, [
96
+ 'arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkEnhancedHealth',
97
+ 'arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkService'
98
+ ]);
99
+ if (appConfig.gracefulShutdown) {
100
+ const accountId = await (0, utils_1.getAccountId)();
101
+ const policy = (0, policies_1.eventTargetRolePolicy)(accountId, environmentName, appConfig.region || 'us-east-1');
102
+ const passPolicy = (0, policies_1.passRolePolicy)(accountId, eventTargetRoleName);
103
+ await (0, utils_1.ensureRoleExists)(eventTargetRoleName, policies_1.eventTargetRole, true);
104
+ await (0, utils_1.ensureInlinePolicyAttached)(eventTargetRoleName, eventTargetPolicyName, policy);
105
+ await (0, utils_1.ensureInlinePolicyAttached)(eventTargetRoleName, eventTargetPassRoleName, passPolicy);
130
106
  }
131
- const createdRule = await (0, _utils.ensureCloudWatchRule)(deregisterRuleName, 'Used by Meteor Up for graceful shutdown', _policies.DeregisterEvent);
132
- if (createdRule) {
133
- console.log(' Created Cloud Watch rule');
107
+ // Create beanstalk application if needed
108
+ const { Applications } = await aws_1.beanstalk.describeApplications({});
109
+ if (!(Applications === null || Applications === void 0 ? void 0 : Applications.find(app => app.ApplicationName === appName))) {
110
+ const params = {
111
+ ApplicationName: appName,
112
+ Description: `App "${appConfig.name}" managed by Meteor Up`
113
+ };
114
+ await aws_1.beanstalk.createApplication(params);
115
+ console.log(' Created Beanstalk application');
134
116
  }
135
- const target = (0, _policies.deregisterEventTarget)(environmentName, eventTargetRoleName, accountId, region);
136
- const createdTarget = await (0, _utils.ensureRuleTargetExists)(deregisterRuleName, target, accountId);
137
- if (createdTarget) {
138
- console.log(' Created target for Cloud Watch rule');
117
+ if (appConfig.gracefulShutdown) {
118
+ (0, utils_1.logStep)('=> Ensuring Graceful Shutdown is setup');
119
+ const existingBucket = (0, utils_1.findBucketWithPrefix)(Buckets, trailBucketPrefix);
120
+ const trailBucketName = existingBucket ?
121
+ existingBucket.Name :
122
+ (0, utils_1.createUniqueName)(trailBucketPrefix);
123
+ const region = appConfig.region || 'us-east-1';
124
+ const accountId = await (0, utils_1.getAccountId)();
125
+ const policy = (0, policies_1.trailBucketPolicy)(accountId, trailBucketName);
126
+ const trailBucketCreated = await (0, utils_1.ensureBucketExists)(Buckets, trailBucketName, appConfig.region);
127
+ await (0, utils_1.ensureBucketPolicyAttached)(trailBucketName, policy);
128
+ if (trailBucketCreated) {
129
+ console.log(' Created bucket for Cloud Trail');
130
+ }
131
+ const params = {
132
+ trailNameList: [
133
+ trailName
134
+ ]
135
+ };
136
+ const { trailList } = await aws_1.cloudTrail.describeTrails(params);
137
+ if (trailList.length === 0) {
138
+ const createParams = {
139
+ Name: trailName,
140
+ S3BucketName: trailBucketName
141
+ };
142
+ await aws_1.cloudTrail.createTrail(createParams);
143
+ console.log(' Created CloudTrail trail');
144
+ }
145
+ const createdDocument = await (0, utils_1.ensureSsmDocument)(automationDocument, (0, policies_1.gracefulShutdownAutomationDocument)());
146
+ if (createdDocument) {
147
+ console.log(' Created SSM Automation Document');
148
+ }
149
+ const createdRule = await (0, utils_1.ensureCloudWatchRule)(deregisterRuleName, 'Used by Meteor Up for graceful shutdown', policies_1.DeregisterEvent);
150
+ if (createdRule) {
151
+ console.log(' Created Cloud Watch rule');
152
+ }
153
+ const target = (0, policies_1.deregisterEventTarget)(environmentName, eventTargetRoleName, accountId, region);
154
+ const createdTarget = await (0, utils_1.ensureRuleTargetExists)(deregisterRuleName, target);
155
+ if (createdTarget) {
156
+ console.log(' Created target for Cloud Watch rule');
157
+ }
139
158
  }
140
- }
141
159
  }
142
160
  async function deploy(api) {
143
- await api.runCommand('beanstalk.setup');
144
- const config = api.getConfig();
145
- const {
146
- app,
147
- bucket,
148
- bundlePrefix,
149
- environment
150
- } = (0, _utils.names)(config);
151
- const version = await (0, _versions.largestVersion)(api);
152
- const nextVersion = version + 1;
153
-
154
- // Mutates the config, so the meteor.build command will have the correct build location
155
- config.app.buildOptions.buildLocation = config.app.buildOptions.buildLocation || (0, _utils.tmpBuildPath)(config.app.path, api);
156
- const bundlePath = api.resolvePath(config.app.buildOptions.buildLocation, 'bundle.zip');
157
- const willBuild = (0, _utils.shouldRebuild)(bundlePath, api.getOptions()['cached-build']);
158
- if (willBuild) {
159
- await api.runCommand('meteor.build');
160
- (0, _prepareBundle.injectFiles)(api, app, nextVersion, config.app);
161
- await (0, _prepareBundle.archiveApp)(config.app.buildOptions.buildLocation, api);
162
- }
163
- (0, _utils.logStep)('=> Uploading bundle');
164
- const key = `${bundlePrefix}${nextVersion}`;
165
- await (0, _upload.default)(config.app, bucket, `${bundlePrefix}${nextVersion}`, bundlePath);
166
- (0, _utils.logStep)('=> Creating version');
167
- await _aws.beanstalk.createApplicationVersion({
168
- ApplicationName: app,
169
- VersionLabel: nextVersion.toString(),
170
- Description: (0, _utils.createVersionDescription)(api, config.app),
171
- SourceBundle: {
172
- S3Bucket: bucket,
173
- S3Key: key
161
+ var _a, _b, _c;
162
+ await api.runCommand('beanstalk.setup');
163
+ const config = api.getConfig();
164
+ const { app, bucket, bundlePrefix, environment } = (0, utils_1.names)(config);
165
+ const version = await (0, versions_1.largestVersion)(api);
166
+ const nextVersion = version + 1;
167
+ // Mutates the config, so the meteor.build command will have the correct build location
168
+ config.app.buildOptions.buildLocation = ((_a = config.app.buildOptions) === null || _a === void 0 ? void 0 : _a.buildLocation) ||
169
+ (0, utils_1.tmpBuildPath)(config.app.path, api);
170
+ const bundlePath = api.resolvePath(config.app.buildOptions.buildLocation, 'bundle.zip');
171
+ const willBuild = (0, utils_1.shouldRebuild)(bundlePath, api.getOptions()['cached-build']);
172
+ if (willBuild) {
173
+ await api.runCommand('meteor.build');
174
+ (0, prepare_bundle_1.injectFiles)(api, app, nextVersion, config.app);
175
+ await (0, prepare_bundle_1.archiveApp)(config.app.buildOptions.buildLocation, api);
174
176
  }
175
- }).promise();
176
- await api.runCommand('beanstalk.reconfig');
177
- await (0, _envReady.waitForEnvReady)(config, true);
178
- (0, _utils.logStep)('=> Deploying new version');
179
- const {
180
- toRemove,
181
- toUpdate
182
- } = await (0, _ebConfig.prepareUpdateEnvironment)(api);
183
- if (api.verbose) {
184
- console.log('EB Config changes:');
185
- console.dir({
186
- toRemove,
187
- toUpdate
177
+ const key = `${bundlePrefix}${nextVersion}`;
178
+ (0, utils_1.logStep)(`=> Uploading bundle ${key} ${bundlePath}`);
179
+ await (0, upload_1.default)(bucket, `${bundlePrefix}${nextVersion}`, bundlePath);
180
+ (0, utils_1.logStep)('=> Creating version');
181
+ await aws_1.beanstalk.createApplicationVersion({
182
+ ApplicationName: app,
183
+ VersionLabel: nextVersion.toString(),
184
+ Description: (0, utils_1.createVersionDescription)(api, config.app),
185
+ SourceBundle: {
186
+ S3Bucket: bucket,
187
+ S3Key: key
188
+ }
189
+ });
190
+ await api.runCommand('beanstalk.reconfig');
191
+ await (0, env_ready_1.waitForEnvReady)(config, true);
192
+ (0, utils_1.logStep)('=> Deploying new version');
193
+ const { toRemove, toUpdate } = await (0, eb_config_1.prepareUpdateEnvironment)(api);
194
+ const eventLog = [];
195
+ if (api.verbose) {
196
+ console.log('EB Config changes:');
197
+ console.dir({
198
+ toRemove,
199
+ toUpdate
200
+ });
201
+ if (config.app.streamLogs) {
202
+ await (0, deployment_logs_1.startLogStreamListener)(api, eventLog, 'var/log/web.stdout.log');
203
+ await (0, deployment_logs_1.startLogStreamListener)(api, eventLog, 'var/log/eb-hooks.log');
204
+ }
205
+ }
206
+ await aws_1.beanstalk.updateEnvironment({
207
+ EnvironmentName: environment,
208
+ VersionLabel: nextVersion.toString(),
209
+ OptionSettings: toUpdate,
210
+ OptionsToRemove: toRemove
211
+ });
212
+ await (0, env_ready_1.waitForEnvReady)(config, true, eventLog);
213
+ (0, deployment_logs_1.stopLogStreamListener)();
214
+ // XXX Is this necessary?
215
+ // const {
216
+ // Environments
217
+ // } = await beanstalk.describeEnvironments({
218
+ // ApplicationName: app,
219
+ // EnvironmentNames: [environment]
220
+ // });
221
+ await api.runCommand('beanstalk.clean');
222
+ await api.runCommand('beanstalk.ssl');
223
+ // Check if deploy succeeded
224
+ const { Environments: finalEnvironments } = await aws_1.beanstalk.describeEnvironments({
225
+ ApplicationName: app,
226
+ EnvironmentNames: [environment]
188
227
  });
189
- }
190
- await _aws.beanstalk.updateEnvironment({
191
- EnvironmentName: environment,
192
- VersionLabel: nextVersion.toString(),
193
- OptionSettings: toUpdate,
194
- OptionsToRemove: toRemove
195
- }).promise();
196
- await (0, _envReady.waitForEnvReady)(config, true);
197
- const {
198
- Environments
199
- } = await _aws.beanstalk.describeEnvironments({
200
- ApplicationName: app,
201
- EnvironmentNames: [environment]
202
- }).promise();
203
- await api.runCommand('beanstalk.clean');
204
- await api.runCommand('beanstalk.ssl');
205
-
206
- // Check if deploy succeeded
207
- const {
208
- Environments: finalEnvironments
209
- } = await _aws.beanstalk.describeEnvironments({
210
- ApplicationName: app,
211
- EnvironmentNames: [environment]
212
- }).promise();
213
- if (nextVersion.toString() === finalEnvironments[0].VersionLabel) {
214
- console.log(_chalk.default.green(`App is running at ${Environments[0].CNAME}`));
215
- } else {
216
- console.log(_chalk.default.red`Deploy Failed. Visit the Aws Elastic Beanstalk console to view the logs from the failed deploy.`);
217
- process.exitCode = 1;
218
- }
228
+ const waitSeconds = 31;
229
+ if (nextVersion.toString() === ((_b = finalEnvironments === null || finalEnvironments === void 0 ? void 0 : finalEnvironments[0]) === null || _b === void 0 ? void 0 : _b.VersionLabel)) {
230
+ if (finalEnvironments[0].Health === client_elastic_beanstalk_1.EnvironmentHealth.Red) {
231
+ console.log(`Health status: ${finalEnvironments[0].Health}, waiting ${waitSeconds} seconds to ensure health status is stable`);
232
+ await new Promise((resolve) => {
233
+ setTimeout(resolve, waitSeconds * 1000);
234
+ });
235
+ const { Environments: reCheckedEnvironments } = await aws_1.beanstalk.describeEnvironments({
236
+ ApplicationName: app,
237
+ EnvironmentNames: [environment]
238
+ });
239
+ if ((reCheckedEnvironments === null || reCheckedEnvironments === void 0 ? void 0 : reCheckedEnvironments[0].Health) === client_elastic_beanstalk_1.EnvironmentHealth.Red) {
240
+ console.log(chalk_1.default.red(`Deploy Failed with invalid Health Status. Visit the Aws Elastic Beanstalk console to view the logs from the failed deploy.`));
241
+ process.exitCode = 1;
242
+ }
243
+ }
244
+ if (config.app.envType === "worker") {
245
+ console.log(chalk_1.default.green(`Worker is running.`));
246
+ }
247
+ else {
248
+ console.log(chalk_1.default.green(`App is running at ${finalEnvironments[0].CNAME}`));
249
+ }
250
+ }
251
+ else {
252
+ console.log(chalk_1.default.red(`Deploy Failed. Version expected ${nextVersion.toString()} (found ${(_c = finalEnvironments === null || finalEnvironments === void 0 ? void 0 : finalEnvironments[0]) === null || _c === void 0 ? void 0 : _c.VersionLabel}). Visit the Aws Elastic Beanstalk console to view the logs from the failed deploy.`));
253
+ process.exitCode = 1;
254
+ }
219
255
  }
220
256
  async function logs(api) {
221
- const logsContent = await (0, _utils.getLogs)(api, ['web.stdout.log', 'nodejs/nodejs.log']);
222
- logsContent.forEach(({
223
- instance,
224
- data
225
- }) => {
226
- console.log(`${instance} `, data[0] || data[1]);
227
- });
257
+ const logsContent = await (0, utils_1.getLogs)(api, ['web.stdout.log', 'nodejs/nodejs.log']);
258
+ logsContent.forEach(({ instance, data }) => {
259
+ console.log(`${instance} `, data[0] || data[1]);
260
+ });
261
+ }
262
+ async function fullLogs(api) {
263
+ const logsContent = await (0, utils_1.downloadFullServerLogs)(api);
264
+ (0, utils_1.logStep)(`=> downloadFullServerLogs: ${JSON.stringify(logsContent, null, '\t')}`);
228
265
  }
229
266
  async function logsNginx(api) {
230
- const logsContent = await (0, _utils.getLogs)(api, ['nginx/error.log', 'nginx/access.log']);
231
- logsContent.forEach(({
232
- instance,
233
- data
234
- }) => {
235
- console.log(`${instance} `, data[0]);
236
- console.log(`${instance} `, data[1]);
237
- });
267
+ const logsContent = await (0, utils_1.getLogs)(api, ['nginx/error.log', 'nginx/access.log']);
268
+ logsContent.forEach(({ instance, data }) => {
269
+ console.log(`${instance} `, data[0]);
270
+ console.log(`${instance} `, data[1]);
271
+ });
238
272
  }
239
273
  async function logsEb(api) {
240
- const logsContent = await (0, _utils.getLogs)(api, ['eb-engine.log', 'eb-activity.log']);
241
- logsContent.forEach(({
242
- data,
243
- instance
244
- }) => {
245
- console.log(`${instance} `, data[0] || data[1]);
246
- });
274
+ const logsContent = await (0, utils_1.getLogs)(api, ['eb-engine.log', 'eb-activity.log']);
275
+ logsContent.forEach(({ data, instance }) => {
276
+ console.log(`${instance} `, data[0] || data[1]);
277
+ });
247
278
  }
248
279
  async function start(api) {
249
- const config = api.getConfig();
250
- const {
251
- environment
252
- } = (0, _utils.names)(config);
253
- (0, _utils.logStep)('=> Starting App');
254
- const {
255
- EnvironmentResources
256
- } = await _aws.beanstalk.describeEnvironmentResources({
257
- EnvironmentName: environment
258
- }).promise();
259
- const autoScalingGroup = EnvironmentResources.AutoScalingGroups[0].Name;
260
- const {
261
- minInstances,
262
- maxInstances
263
- } = config.app;
264
- await _aws.autoScaling.updateAutoScalingGroup({
265
- AutoScalingGroupName: autoScalingGroup,
266
- MaxSize: maxInstances,
267
- MinSize: minInstances,
268
- DesiredCapacity: minInstances
269
- }).promise();
270
- await (0, _envReady.waitForHealth)(config);
280
+ const config = api.getConfig();
281
+ const { environment } = (0, utils_1.names)(config);
282
+ (0, utils_1.logStep)('=> Starting App');
283
+ const { EnvironmentResources } = await aws_1.beanstalk.describeEnvironmentResources({
284
+ EnvironmentName: environment
285
+ });
286
+ const autoScalingGroup = EnvironmentResources.AutoScalingGroups[0].Name;
287
+ const { minInstances, maxInstances } = config.app;
288
+ await aws_1.autoScaling.updateAutoScalingGroup({
289
+ AutoScalingGroupName: autoScalingGroup,
290
+ MaxSize: maxInstances,
291
+ MinSize: minInstances,
292
+ DesiredCapacity: minInstances
293
+ });
294
+ await (0, env_ready_1.waitForHealth)(config, undefined, false);
271
295
  }
272
296
  async function stop(api) {
273
- const config = api.getConfig();
274
- const {
275
- environment
276
- } = (0, _utils.names)(config);
277
- (0, _utils.logStep)('=> Stopping App');
278
- const {
279
- EnvironmentResources
280
- } = await _aws.beanstalk.describeEnvironmentResources({
281
- EnvironmentName: environment
282
- }).promise();
283
- const autoScalingGroup = EnvironmentResources.AutoScalingGroups[0].Name;
284
- await _aws.autoScaling.updateAutoScalingGroup({
285
- AutoScalingGroupName: autoScalingGroup,
286
- MaxSize: 0,
287
- MinSize: 0,
288
- DesiredCapacity: 0
289
- }).promise();
290
- await (0, _envReady.waitForHealth)(config, 'Grey');
297
+ const config = api.getConfig();
298
+ const { environment } = (0, utils_1.names)(config);
299
+ (0, utils_1.logStep)('=> Stopping App');
300
+ const { EnvironmentResources } = await aws_1.beanstalk.describeEnvironmentResources({
301
+ EnvironmentName: environment
302
+ });
303
+ const autoScalingGroup = EnvironmentResources.AutoScalingGroups[0].Name;
304
+ await aws_1.autoScaling.updateAutoScalingGroup({
305
+ AutoScalingGroupName: autoScalingGroup,
306
+ MaxSize: 0,
307
+ MinSize: 0,
308
+ DesiredCapacity: 0
309
+ });
310
+ await (0, env_ready_1.waitForHealth)(config, 'Grey', false);
291
311
  }
292
312
  async function restart(api) {
293
- const config = api.getConfig();
294
- const {
295
- environment
296
- } = (0, _utils.names)(config);
297
- (0, _utils.logStep)('=> Restarting App');
298
- await _aws.beanstalk.restartAppServer({
299
- EnvironmentName: environment
300
- }).promise();
301
- await (0, _envReady.waitForEnvReady)(config, false);
313
+ const config = api.getConfig();
314
+ const { environment } = (0, utils_1.names)(config);
315
+ (0, utils_1.logStep)('=> Restarting App');
316
+ await aws_1.beanstalk.restartAppServer({
317
+ EnvironmentName: environment
318
+ });
319
+ await (0, env_ready_1.waitForEnvReady)(config, false);
302
320
  }
303
321
  async function clean(api) {
304
- const config = api.getConfig();
305
- const {
306
- app,
307
- bucket
308
- } = (0, _utils.names)(config);
309
- (0, _utils.logStep)('=> Finding old versions');
310
- const {
311
- versions
312
- } = await (0, _versions.oldVersions)(api);
313
- const envVersions = await (0, _versions.oldEnvVersions)(api);
314
- (0, _utils.logStep)('=> Removing old versions');
315
- const promises = [];
316
- for (let i = 0; i < versions.length; i++) {
317
- promises.push(_aws.beanstalk.deleteApplicationVersion({
318
- ApplicationName: app,
319
- VersionLabel: versions[i].toString(),
320
- DeleteSourceBundle: true
321
- }).promise());
322
- }
323
- for (let i = 0; i < envVersions.length; i++) {
324
- promises.push(_aws.s3.deleteObject({
325
- Bucket: bucket,
326
- Key: `env/${envVersions[i]}.txt`
327
- }).promise());
328
- }
329
-
330
- // TODO: remove bundles
331
-
332
- await Promise.all(promises);
322
+ const config = api.getConfig();
323
+ const { app, bucket } = (0, utils_1.names)(config);
324
+ (0, utils_1.logStep)('=> Finding old versions');
325
+ const { versions } = await (0, versions_1.oldVersions)(api);
326
+ const envVersions = await (0, versions_1.oldEnvVersions)(api);
327
+ (0, utils_1.logStep)('=> Removing old versions');
328
+ const promises = [];
329
+ for (let i = 0; i < versions.length; i++) {
330
+ promises.push(aws_1.beanstalk.deleteApplicationVersion({
331
+ ApplicationName: app,
332
+ VersionLabel: versions[i].toString(),
333
+ DeleteSourceBundle: true
334
+ }));
335
+ console.log(" - ", versions[i].toString());
336
+ }
337
+ for (let i = 0; i < envVersions.length; i++) {
338
+ promises.push(aws_1.s3.deleteObject({
339
+ Bucket: bucket,
340
+ Key: `env/${envVersions[i]}.txt`
341
+ }));
342
+ console.log(" - ", `env/${envVersions[i]}.txt`, bucket);
343
+ }
344
+ // TODO: remove bundles
345
+ await Promise.all(promises);
333
346
  }
334
347
  async function reconfig(api) {
335
- const config = api.getConfig();
336
- const {
337
- app,
338
- environment,
339
- bucket
340
- } = (0, _utils.names)(config);
341
- const deploying = !!api.commandHistory.find(entry => entry.name === 'beanstalk.deploy');
342
- (0, _utils.logStep)('=> @Brunwig/mup-aws-beanstalk');
343
- (0, _utils.logStep)('=> Configuring Beanstalk environment');
344
-
345
- // check if env exists
346
- const {
347
- Environments
348
- } = await _aws.beanstalk.describeEnvironments({
349
- ApplicationName: app,
350
- EnvironmentNames: [environment]
351
- }).promise();
352
- if (!Environments.find(env => env.Status !== 'Terminated')) {
353
- const desiredEbConfig = (0, _ebConfig.createDesiredConfig)(api.getConfig(), api.getSettings(), config.app.longEnvVars ? 1 : false);
354
- if (config.app.longEnvVars) {
355
- const envContent = (0, _envSettings.createEnvFile)(config.app.env, api.getSettings());
356
- await (0, _upload.uploadEnvFile)(bucket, 1, envContent);
348
+ const config = api.getConfig();
349
+ const { app, environment, bucket } = (0, utils_1.names)(config);
350
+ const deploying = !!api.commandHistory.find(entry => entry.name === 'beanstalk.deploy');
351
+ (0, utils_1.logStep)('=> @Brunwig/mup-aws-beanstalk');
352
+ (0, utils_1.logStep)('=> Configuring Beanstalk environment');
353
+ // check if env exists
354
+ const { Environments } = await aws_1.beanstalk.describeEnvironments({
355
+ ApplicationName: app,
356
+ EnvironmentNames: [environment]
357
+ });
358
+ const environmentExists = Environments.find(env => env.Status !== 'Terminated');
359
+ if (!environmentExists) {
360
+ const desiredEbConfig = (0, eb_config_1.createDesiredConfig)(api.getConfig(), api.getSettings(), config.app.longEnvVars ? 1 : false);
361
+ if (config.app.longEnvVars) {
362
+ const envContent = (0, env_settings_1.createEnvFile)(config.app.env, api.getSettings());
363
+ await (0, upload_1.uploadEnvFile)(bucket, 1, envContent);
364
+ }
365
+ const platformArn = await (0, utils_1.selectPlatformArn)(api.getConfig().app.awsPlatformBranchName);
366
+ const [version] = await (0, versions_1.ebVersions)(api);
367
+ // Whether this is a web or worker environment
368
+ const envTierConfig = (0, eb_config_1.getEnvTierConfig)(config.app.envType);
369
+ await aws_1.beanstalk.createEnvironment({
370
+ ApplicationName: app,
371
+ EnvironmentName: environment,
372
+ Description: `Environment for ${config.app.name}, managed by Meteor Up`,
373
+ VersionLabel: version.toString(),
374
+ PlatformArn: platformArn,
375
+ Tier: envTierConfig,
376
+ OptionSettings: desiredEbConfig.OptionSettings
377
+ });
378
+ console.log(' Created Environment');
379
+ await (0, env_ready_1.waitForEnvReady)(config, false);
357
380
  }
358
- const platformArn = await (0, _utils.selectPlatformArn)(api.getConfig().app.awsPlatformBranchName);
359
- const [version] = await (0, _versions.ebVersions)(api);
360
- await _aws.beanstalk.createEnvironment({
361
- ApplicationName: app,
362
- EnvironmentName: environment,
363
- Description: `Environment for ${config.app.name}, managed by Meteor Up`,
364
- VersionLabel: version.toString(),
365
- PlatformArn: platformArn,
366
- OptionSettings: desiredEbConfig.OptionSettings
367
- }).promise();
368
- console.log(' Created Environment');
369
- await (0, _envReady.waitForEnvReady)(config, false);
370
- } else if (!deploying) {
371
- // If we are deploying, the environment will be updated
372
- // at the same time we update the environment version
373
- const {
374
- toRemove,
375
- toUpdate
376
- } = await (0, _ebConfig.prepareUpdateEnvironment)(api);
377
- if (api.verbose) {
378
- console.log('EB Config changes:');
379
- console.dir({
380
- toRemove,
381
- toUpdate
382
- });
381
+ else if (!deploying) {
382
+ // If we are deploying, the environment will be updated
383
+ // at the same time we update the environment version
384
+ const { toRemove, toUpdate } = await (0, eb_config_1.prepareUpdateEnvironment)(api);
385
+ if (api.verbose) {
386
+ console.log('EB Config changes:');
387
+ console.dir({
388
+ toRemove,
389
+ toUpdate
390
+ });
391
+ }
392
+ if (toRemove.length > 0 || toUpdate.length > 0) {
393
+ await (0, env_ready_1.waitForEnvReady)(config, true);
394
+ await aws_1.beanstalk.updateEnvironment({
395
+ EnvironmentName: environment,
396
+ OptionSettings: toUpdate,
397
+ OptionsToRemove: toRemove
398
+ });
399
+ console.log(' Updated Environment');
400
+ await (0, env_ready_1.waitForEnvReady)(config, true);
401
+ }
383
402
  }
384
- if (toRemove.length > 0 || toUpdate.length > 0) {
385
- await (0, _envReady.waitForEnvReady)(config, true);
386
- await _aws.beanstalk.updateEnvironment({
403
+ const { ConfigurationSettings } = await aws_1.beanstalk.describeConfigurationSettings({
387
404
  EnvironmentName: environment,
388
- OptionSettings: toUpdate,
389
- OptionsToRemove: toRemove
390
- }).promise();
391
- console.log(' Updated Environment');
392
- await (0, _envReady.waitForEnvReady)(config, true);
405
+ ApplicationName: app
406
+ });
407
+ if ((0, eb_config_1.scalingConfigChanged)(ConfigurationSettings[0].OptionSettings, config)) {
408
+ (0, utils_1.logStep)('=> Configuring scaling');
409
+ await aws_1.beanstalk.updateEnvironment({
410
+ EnvironmentName: environment,
411
+ OptionSettings: (0, eb_config_1.scalingConfig)(config.app).OptionSettings
412
+ });
413
+ await (0, env_ready_1.waitForEnvReady)(config, true);
393
414
  }
394
- }
395
- const {
396
- ConfigurationSettings
397
- } = await _aws.beanstalk.describeConfigurationSettings({
398
- EnvironmentName: environment,
399
- ApplicationName: app
400
- }).promise();
401
- if ((0, _ebConfig.scalingConfigChanged)(ConfigurationSettings[0].OptionSettings, config)) {
402
- (0, _utils.logStep)('=> Configuring scaling');
403
- await _aws.beanstalk.updateEnvironment({
404
- EnvironmentName: environment,
405
- OptionSettings: (0, _ebConfig.scalingConfig)(config.app).OptionSettings
406
- }).promise();
407
- await (0, _envReady.waitForEnvReady)(config, true);
408
- }
409
415
  }
410
416
  async function events(api) {
411
- const {
412
- environment
413
- } = (0, _utils.names)(api.getConfig());
414
- const {
415
- Events: envEvents
416
- } = await _aws.beanstalk.describeEvents({
417
- EnvironmentName: environment
418
- }).promise();
419
- console.log(envEvents.map(ev => `${ev.EventDate}: ${ev.Message}`).join('\n'));
417
+ const { environment } = (0, utils_1.names)(api.getConfig());
418
+ const { Events: envEvents } = await aws_1.beanstalk.describeEvents({
419
+ EnvironmentName: environment
420
+ });
421
+ console.log(envEvents.map(ev => `${ev.EventDate}: ${ev.Message}`).join('\n'));
420
422
  }
421
423
  async function status(api) {
422
- const {
423
- environment
424
- } = (0, _utils.names)(api.getConfig());
425
- let result;
426
- try {
427
- result = await _aws.beanstalk.describeEnvironmentHealth({
428
- AttributeNames: ['All'],
429
- EnvironmentName: environment
430
- }).promise();
431
- } catch (e) {
432
- if (e.message.includes('No Environment found for EnvironmentName')) {
433
- console.log(' AWS Beanstalk environment does not exist');
434
- return;
424
+ const { environment } = (0, utils_1.names)(api.getConfig());
425
+ let result;
426
+ try {
427
+ result = await aws_1.beanstalk.describeEnvironmentHealth({
428
+ AttributeNames: [
429
+ 'All'
430
+ ],
431
+ EnvironmentName: environment
432
+ });
433
+ }
434
+ catch (e) {
435
+ // @ts-ignore
436
+ if (e.message.includes('No Environment found for EnvironmentName')) {
437
+ console.log(' AWS Beanstalk environment does not exist');
438
+ return;
439
+ }
440
+ throw e;
441
+ }
442
+ const { InstanceHealthList } = await aws_1.beanstalk.describeInstancesHealth({
443
+ AttributeNames: [
444
+ 'All'
445
+ ],
446
+ EnvironmentName: environment
447
+ });
448
+ const { RequestCount, Duration, StatusCodes, Latency } = result.ApplicationMetrics;
449
+ console.log(`Environment Status: ${result.Status}`);
450
+ console.log(`Health Status: ${(0, utils_1.coloredStatusText)(result.Color, result.HealthStatus)}`);
451
+ if (result.Causes.length > 0) {
452
+ console.log('Causes: ');
453
+ result.Causes.forEach(cause => console.log(` ${cause}`));
454
+ }
455
+ console.log('');
456
+ console.log(`=== Metrics For Last ${Duration || 'Unknown'} Minutes ===`);
457
+ console.log(` Requests: ${RequestCount}`);
458
+ if (StatusCodes) {
459
+ console.log(' Status Codes');
460
+ console.log(` 2xx: ${StatusCodes.Status2xx}`);
461
+ console.log(` 3xx: ${StatusCodes.Status3xx}`);
462
+ console.log(` 4xx: ${StatusCodes.Status4xx}`);
463
+ console.log(` 5xx: ${StatusCodes.Status5xx}`);
464
+ }
465
+ if (Latency) {
466
+ console.log(' Latency');
467
+ console.log(` 99.9%: ${Latency.P999}`);
468
+ console.log(` 99% : ${Latency.P99}`);
469
+ console.log(` 95% : ${Latency.P95}`);
470
+ console.log(` 90% : ${Latency.P90}`);
471
+ console.log(` 85% : ${Latency.P85}`);
472
+ console.log(` 75% : ${Latency.P75}`);
473
+ console.log(` 50% : ${Latency.P50}`);
474
+ console.log(` 10% : ${Latency.P10}`);
475
+ }
476
+ console.log('');
477
+ console.log('=== Instances ===');
478
+ InstanceHealthList.forEach((instance) => {
479
+ console.log(` ${instance.InstanceId}: ${(0, utils_1.coloredStatusText)(instance.Color, instance.HealthStatus)}`);
480
+ });
481
+ if (InstanceHealthList.length === 0) {
482
+ console.log(' 0 Instances');
435
483
  }
436
- throw e;
437
- }
438
- const {
439
- InstanceHealthList
440
- } = await _aws.beanstalk.describeInstancesHealth({
441
- AttributeNames: ['All'],
442
- EnvironmentName: environment
443
- }).promise();
444
- const {
445
- RequestCount,
446
- Duration,
447
- StatusCodes,
448
- Latency
449
- } = result.ApplicationMetrics;
450
- console.log(`Environment Status: ${result.Status}`);
451
- console.log(`Health Status: ${(0, _utils.coloredStatusText)(result.Color, result.HealthStatus)}`);
452
- if (result.Causes.length > 0) {
453
- console.log('Causes: ');
454
- result.Causes.forEach(cause => console.log(` ${cause}`));
455
- }
456
- console.log('');
457
- console.log(`=== Metrics For Last ${Duration || 'Unknown'} Minutes ===`);
458
- console.log(` Requests: ${RequestCount}`);
459
- if (StatusCodes) {
460
- console.log(' Status Codes');
461
- console.log(` 2xx: ${StatusCodes.Status2xx}`);
462
- console.log(` 3xx: ${StatusCodes.Status3xx}`);
463
- console.log(` 4xx: ${StatusCodes.Status4xx}`);
464
- console.log(` 5xx: ${StatusCodes.Status5xx}`);
465
- }
466
- if (Latency) {
467
- console.log(' Latency');
468
- console.log(` 99.9%: ${Latency.P999}`);
469
- console.log(` 99% : ${Latency.P99}`);
470
- console.log(` 95% : ${Latency.P95}`);
471
- console.log(` 90% : ${Latency.P90}`);
472
- console.log(` 85% : ${Latency.P85}`);
473
- console.log(` 75% : ${Latency.P75}`);
474
- console.log(` 50% : ${Latency.P50}`);
475
- console.log(` 10% : ${Latency.P10}`);
476
- }
477
- console.log('');
478
- console.log('=== Instances ===');
479
- InstanceHealthList.forEach(instance => {
480
- console.log(` ${instance.InstanceId}: ${(0, _utils.coloredStatusText)(instance.Color, instance.HealthStatus)}`);
481
- });
482
- if (InstanceHealthList.length === 0) {
483
- console.log(' 0 Instances');
484
- }
485
484
  }
486
485
  async function ssl(api) {
487
- const config = api.getConfig();
488
- await (0, _envReady.waitForEnvReady)(config, true);
489
- if (!config.app || !config.app.sslDomains) {
490
- (0, _utils.logStep)('=> Updating Beanstalk SSL Config');
491
- await (0, _certificates.default)(config);
492
- return;
493
- }
494
- (0, _utils.logStep)('=> Checking Certificate Status');
495
- const domains = config.app.sslDomains;
496
- const {
497
- CertificateSummaryList
498
- } = await _aws.acm.listCertificates().promise();
499
- let found = null;
500
- for (let i = 0; i < CertificateSummaryList.length; i++) {
501
- const {
502
- DomainName,
503
- CertificateArn
504
- } = CertificateSummaryList[i];
505
- if (DomainName === domains[0]) {
506
- const {
507
- Certificate
508
- } = await _aws.acm.describeCertificate({
509
- // eslint-disable-line no-await-in-loop
510
- CertificateArn
511
- }).promise();
512
- if (domains.join(',') === Certificate.SubjectAlternativeNames.join(',')) {
513
- found = CertificateSummaryList[i];
514
- }
486
+ const config = api.getConfig();
487
+ // Worker envs don't need ssl
488
+ if (config.app.envType !== 'webserver')
489
+ return;
490
+ await (0, env_ready_1.waitForEnvReady)(config, true);
491
+ if (!config.app || !config.app.sslDomains) {
492
+ (0, utils_1.logStep)('=> Updating Beanstalk SSL Config');
493
+ await (0, certificates_1.ensureSSLConfigured)(config);
494
+ return;
515
495
  }
516
- }
517
- let certificateArn;
518
- if (!found) {
519
- (0, _utils.logStep)('=> Requesting Certificate');
520
- const result = await _aws.acm.requestCertificate({
521
- DomainName: domains.shift(),
522
- SubjectAlternativeNames: domains.length > 0 ? domains : null
523
- }).promise();
524
- certificateArn = result.CertificateArn;
525
- }
526
- if (found) {
527
- certificateArn = found.CertificateArn;
528
- }
529
- let emailsProvided = false;
530
- let checks = 0;
531
- let certificate;
532
-
533
- /* eslint-disable no-await-in-loop */
534
- while (!emailsProvided && checks < 5) {
535
- const {
536
- Certificate
537
- } = await _aws.acm.describeCertificate({
538
- CertificateArn: certificateArn
539
- }).promise();
540
- const validationOptions = Certificate.DomainValidationOptions[0];
541
- if (typeof validationOptions.ValidationEmails === 'undefined') {
542
- emailsProvided = true;
543
- certificate = Certificate;
544
- } else if (validationOptions.ValidationEmails.length > 0 || checks === 6) {
545
- emailsProvided = true;
546
- certificate = Certificate;
547
- } else {
548
- checks += 1;
549
- await new Promise(resolve => {
550
- setTimeout(resolve, 1000 * 10);
551
- });
496
+ (0, utils_1.logStep)('=> Checking Certificate Status');
497
+ const domains = config.app.sslDomains;
498
+ const { CertificateSummaryList } = await aws_1.acm.listCertificates({});
499
+ let found = null;
500
+ for (let i = 0; i < CertificateSummaryList.length; i++) {
501
+ const { DomainName, CertificateArn } = CertificateSummaryList[i];
502
+ if (DomainName === domains[0]) {
503
+ const { Certificate } = await aws_1.acm.describeCertificate({
504
+ CertificateArn
505
+ });
506
+ if (domains.join(',') === Certificate.SubjectAlternativeNames.join(',')) {
507
+ found = CertificateSummaryList[i];
508
+ }
509
+ }
552
510
  }
553
- }
554
- if (certificate.Status === 'PENDING_VALIDATION') {
555
- console.log('Certificate is pending validation.');
556
- certificate.DomainValidationOptions.forEach(({
557
- DomainName,
558
- ValidationEmails,
559
- ValidationDomain,
560
- ValidationStatus
561
- }) => {
562
- if (ValidationStatus === 'SUCCESS') {
563
- console.log(_chalk.default.green(`${ValidationDomain || DomainName} has been verified`));
564
- return;
565
- }
566
- console.log(_chalk.default.yellow(`${ValidationDomain || DomainName} is pending validation`));
567
- if (ValidationEmails) {
568
- console.log('Emails with instructions have been sent to:');
569
- ValidationEmails.forEach(email => {
570
- console.log(` ${email}`);
511
+ let certificateArn;
512
+ if (!found) {
513
+ (0, utils_1.logStep)('=> Requesting Certificate');
514
+ const result = await aws_1.acm.requestCertificate({
515
+ DomainName: domains.shift(),
516
+ SubjectAlternativeNames: domains.length > 0 ? domains : undefined
571
517
  });
572
- }
573
- console.log('Run "mup beanstalk ssl" after you have verified the domains, or to check the verification status');
574
- });
575
- } else if (certificate.Status === 'ISSUED') {
576
- console.log(_chalk.default.green('Certificate has been issued'));
577
- (0, _utils.logStep)('=> Updating Beanstalk SSL config');
578
- await (0, _certificates.default)(config, certificateArn);
579
- }
518
+ certificateArn = result.CertificateArn;
519
+ }
520
+ if (found) {
521
+ certificateArn = found.CertificateArn;
522
+ }
523
+ let emailsProvided = false;
524
+ let checks = 0;
525
+ let certificate;
526
+ /* eslint-disable no-await-in-loop */
527
+ while (!emailsProvided && checks < 5) {
528
+ const certRes = await aws_1.acm.describeCertificate({
529
+ CertificateArn: certificateArn
530
+ });
531
+ const Certificate = certRes.Certificate;
532
+ const validationOptions = Certificate.DomainValidationOptions[0];
533
+ if (typeof validationOptions.ValidationEmails === 'undefined') {
534
+ emailsProvided = true;
535
+ certificate = Certificate;
536
+ }
537
+ else if (validationOptions.ValidationEmails.length > 0 || checks === 6) {
538
+ emailsProvided = true;
539
+ certificate = Certificate;
540
+ }
541
+ else {
542
+ checks += 1;
543
+ await new Promise((resolve) => {
544
+ setTimeout(resolve, 1000 * 10);
545
+ });
546
+ }
547
+ }
548
+ if (certificate && certificate.Status === 'PENDING_VALIDATION') {
549
+ console.log('Certificate is pending validation.');
550
+ certificate.DomainValidationOptions.forEach(({ DomainName, ValidationEmails, ValidationDomain, ValidationStatus }) => {
551
+ if (ValidationStatus === 'SUCCESS') {
552
+ console.log(chalk_1.default.green(`${ValidationDomain || DomainName} has been verified`));
553
+ return;
554
+ }
555
+ console.log(chalk_1.default.yellow(`${ValidationDomain || DomainName} is pending validation`));
556
+ if (ValidationEmails) {
557
+ console.log('Emails with instructions have been sent to:');
558
+ ValidationEmails.forEach((email) => {
559
+ console.log(` ${email}`);
560
+ });
561
+ }
562
+ console.log('Run "mup beanstalk ssl" after you have verified the domains, or to check the verification status');
563
+ });
564
+ }
565
+ else if (certificate && certificate.Status === 'ISSUED') {
566
+ console.log(chalk_1.default.green('Certificate has been issued'));
567
+ (0, utils_1.logStep)('=> Updating Beanstalk SSL config');
568
+ await (0, certificates_1.ensureSSLConfigured)(config, certificateArn);
569
+ }
580
570
  }
581
571
  async function shell(api) {
582
- const {
583
- selected,
584
- description
585
- } = await (0, _utils.pickInstance)(api.getConfig(), api.getArgs()[2]);
586
- if (!selected) {
587
- console.log(description);
588
- console.log('Run "mup beanstalk shell <instance id>"');
589
- process.exitCode = 1;
590
- return;
591
- }
592
- const {
593
- sshOptions,
594
- removeSSHAccess
595
- } = await (0, _utils.connectToInstance)(api, selected, 'mup beanstalk shell');
596
- const conn = new _ssh.Client();
597
- conn.on('ready', () => {
598
- conn.exec('sudo node /home/webapp/meteor-shell.js', {
599
- pty: true
600
- }, (err, stream) => {
601
- if (err) {
602
- throw err;
603
- }
604
- stream.on('close', async () => {
605
- conn.end();
606
- await removeSSHAccess();
607
- process.exit();
608
- });
609
- process.stdin.setRawMode(true);
610
- process.stdin.pipe(stream);
611
- stream.pipe(process.stdout);
612
- stream.stderr.pipe(process.stderr);
613
- stream.setWindow(process.stdout.rows, process.stdout.columns);
614
- process.stdout.on('resize', () => {
615
- stream.setWindow(process.stdout.rows, process.stdout.columns);
616
- });
617
- });
618
- }).connect(sshOptions);
572
+ const { selected, description } = await (0, utils_1.pickInstance)(api.getConfig(), api.getArgs()[2]);
573
+ if (!selected) {
574
+ console.log(description);
575
+ console.log('Run "mup beanstalk shell <instance id>"');
576
+ process.exitCode = 1;
577
+ return;
578
+ }
579
+ const { sshOptions, removeSSHAccess } = await (0, utils_1.connectToInstance)(api, selected, 'mup beanstalk shell');
580
+ const conn = new ssh2_1.Client();
581
+ conn.on('ready', () => {
582
+ conn.exec('sudo node /home/webapp/meteor-shell.js', {
583
+ pty: true
584
+ }, (err, stream) => {
585
+ if (err) {
586
+ throw err;
587
+ }
588
+ stream.on('close', async () => {
589
+ conn.end();
590
+ await removeSSHAccess();
591
+ process.exit();
592
+ });
593
+ process.stdin.setRawMode(true);
594
+ process.stdin.pipe(stream);
595
+ stream.pipe(process.stdout);
596
+ stream.stderr.pipe(process.stderr);
597
+ // @ts-ignore
598
+ stream.setWindow(process.stdout.rows, process.stdout.columns);
599
+ process.stdout.on('resize', () => {
600
+ // @ts-ignore
601
+ stream.setWindow(process.stdout.rows, process.stdout.columns);
602
+ });
603
+ });
604
+ }).connect(sshOptions);
619
605
  }
620
606
  async function debug(api) {
621
- const config = api.getConfig();
622
- const {
623
- selected,
624
- description
625
- } = await (0, _utils.pickInstance)(config, api.getArgs()[2]);
626
- if (!selected) {
627
- console.log(description);
628
- console.log('Run "mup beanstalk debug <instance id>"');
629
- process.exitCode = 1;
630
- return;
631
- }
632
- const {
633
- sshOptions,
634
- removeSSHAccess
635
- } = await (0, _utils.connectToInstance)(api, selected, 'mup beanstalk debug');
636
- const conn = new _ssh.Client();
637
- conn.on('ready', async () => {
638
- const result = await (0, _utils.executeSSHCommand)(conn, 'sudo pkill -USR1 -u webapp -n node || sudo pkill -USR1 -u nodejs -n node');
639
- if (api.verbose) {
640
- console.log(result.output);
607
+ const config = api.getConfig();
608
+ const { selected, description } = await (0, utils_1.pickInstance)(config, api.getArgs()[2]);
609
+ if (!selected) {
610
+ console.log(description);
611
+ console.log('Run "mup beanstalk debug <instance id>"');
612
+ process.exitCode = 1;
613
+ return;
641
614
  }
642
- const server = _objectSpread(_objectSpread({}, sshOptions), {}, {
643
- pem: api.resolvePath(config.app.sshKey.privateKey)
644
- });
645
- let loggedConnection = false;
646
- api.forwardPort({
647
- server,
648
- localAddress: '0.0.0.0',
649
- localPort: 9229,
650
- remoteAddress: '127.0.0.1',
651
- remotePort: 9229,
652
- onError(error) {
653
- console.error(error);
654
- },
655
- onReady() {
656
- console.log('Connected to server');
657
- console.log('');
658
- console.log('Debugger listening on ws://127.0.0.1:9229');
659
- console.log('');
660
- console.log('To debug:');
661
- console.log('1. Open chrome://inspect in Chrome');
662
- console.log('2. Select "Open dedicated DevTools for Node"');
663
- console.log('3. Wait a minute while it connects and loads the app.');
664
- console.log(' When it is ready, the app\'s files will appear in the Sources tab');
665
- console.log('');
666
- console.log('Warning: Do not use breakpoints when debugging a production server.');
667
- console.log('They will pause your server when hit, causing it to not handle methods or subscriptions.');
668
- console.log('Use logpoints or something else that does not pause the server');
669
- console.log('');
670
- console.log('The debugger will be enabled until the next time the app is restarted,');
671
- console.log('though only accessible while this command is running');
672
- },
673
- onConnection() {
674
- if (!loggedConnection) {
675
- // It isn't guaranteed the debugger is connected, but not many
676
- // other tools will try to connect to port 9229.
677
- console.log('');
678
- console.log('Detected by debugger');
679
- loggedConnection = true;
615
+ const { sshOptions, removeSSHAccess } = await (0, utils_1.connectToInstance)(api, selected, 'mup beanstalk debug');
616
+ const conn = new ssh2_1.Client();
617
+ conn.on('ready', async () => {
618
+ const result = await (0, utils_1.executeSSHCommand)(conn, 'sudo pkill -USR1 -u webapp -n node || sudo pkill -USR1 -u nodejs -n node');
619
+ if (api.verbose) {
620
+ console.log(result.output);
680
621
  }
681
- }
622
+ const server = {
623
+ ...sshOptions,
624
+ pem: api.resolvePath(config.app.sshKey.privateKey)
625
+ };
626
+ let loggedConnection = false;
627
+ api.forwardPort({
628
+ server,
629
+ localAddress: '0.0.0.0',
630
+ localPort: 9229,
631
+ remoteAddress: '127.0.0.1',
632
+ remotePort: 9229,
633
+ onError(error) {
634
+ console.error(error);
635
+ },
636
+ onReady() {
637
+ console.log('Connected to server');
638
+ console.log('');
639
+ console.log('Debugger listening on ws://127.0.0.1:9229');
640
+ console.log('');
641
+ console.log('To debug:');
642
+ console.log('1. Open chrome://inspect in Chrome');
643
+ console.log('2. Select "Open dedicated DevTools for Node"');
644
+ console.log('3. Wait a minute while it connects and loads the app.');
645
+ console.log(' When it is ready, the app\'s files will appear in the Sources tab');
646
+ console.log('');
647
+ console.log('Warning: Do not use breakpoints when debugging a production server.');
648
+ console.log('They will pause your server when hit, causing it to not handle methods or subscriptions.');
649
+ console.log('Use logpoints or something else that does not pause the server');
650
+ console.log('');
651
+ console.log('The debugger will be enabled until the next time the app is restarted,');
652
+ console.log('though only accessible while this command is running');
653
+ },
654
+ onConnection() {
655
+ if (!loggedConnection) {
656
+ // It isn't guaranteed the debugger is connected, but not many
657
+ // other tools will try to connect to port 9229.
658
+ console.log('');
659
+ console.log('Detected by debugger');
660
+ loggedConnection = true;
661
+ }
662
+ }
663
+ });
664
+ }).connect(sshOptions);
665
+ process.on('SIGINT', async () => {
666
+ await removeSSHAccess();
667
+ process.exit();
682
668
  });
683
- }).connect(sshOptions);
684
- process.on('SIGINT', async () => {
685
- await removeSSHAccess();
686
- process.exit();
687
- });
688
669
  }
689
670
  //# sourceMappingURL=command-handlers.js.map