/
dashboard-set-org.js
398 lines (366 loc) · 12.5 KB
/
dashboard-set-org.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
'use strict';
const _ = require('lodash');
const chalk = require('chalk');
const { log } = require('@serverless/utils/log');
const accountUtils = require('@serverless/utils/account');
const configUtils = require('@serverless/utils/config');
const { ServerlessSDK } = require('@serverless/platform-client');
const promptWithHistory = require('@serverless/utils/inquirer/prompt-with-history');
const { writeOrgAndApp, showOnboardingWelcome } = require('./utils');
const {
getPlatformClientWithAccessKey,
getOrCreateAccessKeyForOrg,
} = require('@serverless/dashboard-plugin/lib/client-utils');
const isValidAppName = RegExp.prototype.test.bind(/^[a-z0-9](?:[a-z0-9-]{0,126}[a-z0-9])?$/);
const orgUpdateConfirm = async (stepHistory) => {
log.notice(
'Service has monitoring enabled, but it is configured with the "org" to which you do not have access'
);
log.notice();
const shouldUpdateOrg = await promptWithHistory({
message: 'Would you like to update it?',
type: 'confirm',
name: 'shouldUpdateOrg',
stepHistory,
});
return shouldUpdateOrg;
};
const appUpdateConfirm = async (appName, orgName, stepHistory) => {
log.notice('The "app" used in this Service does not yet exist in your Organization.');
log.notice();
const appUpdateType = await promptWithHistory({
message: 'What would you like to do?',
type: 'list',
name: 'appUpdateType',
stepHistory,
choices: [
{ name: `Create '${appName}' app in '${orgName}' org`, value: '_create_' },
{
name: 'Switch to one of the existing apps (or create new one with different name)',
value: '_choose_existing_',
},
{ name: "Skip, I'll sort this out manually", value: '_skip_' },
],
});
return appUpdateType;
};
const orgsChoice = async (orgNames, stepHistory) => {
const orgName = await promptWithHistory({
message: 'What org do you want to add this service to?',
type: 'list',
name: 'orgName',
choices: [...orgNames, { name: '[Skip]', value: '_skip_' }],
stepHistory,
});
return orgName;
};
const appNameChoice = async (appNames, stepHistory) => {
const appName = await promptWithHistory({
message: 'What application do you want to add this to?',
type: 'list',
name: 'appName',
choices: Array.from(appNames).concat({ name: '[create a new app]', value: '_create_' }),
stepHistory,
});
return appName;
};
const appNameInput = async (appNames, stepHistory) => {
const appName = await promptWithHistory({
message: 'What do you want to name this application?',
type: 'input',
name: 'newAppName',
stepHistory,
validate: (input) => {
input = input.trim();
if (!isValidAppName(input)) {
return (
'App name is not valid.\n' +
' - It should only contain lowercase alphanumeric and hyphens.\n' +
' - It should start and end with an alphanumeric character.\n' +
" - Shouldn't exceed 128 characters"
);
}
if (appNames.includes(input)) return 'App of this name already exists';
return true;
},
});
return appName;
};
const steps = {
resolveOrgNames: async (user) => {
if (process.env.SERVERLESS_ACCESS_KEY) {
const sdk = new ServerlessSDK({ accessKey: process.env.SERVERLESS_ACCESS_KEY });
const { orgName } = await sdk.accessKeys.get();
return new Set([orgName]);
}
let orgs = new Set();
if (!user.idToken) {
// User registered over CLI hence idToken is not stored.
// Still to resolve organizations from platform idToken is needed.
// Handling it gently by assuming that orgs listed in config file
// make a valid representation
for (const org of Object.keys(user.accessKeys)) orgs.add(org);
} else {
const sdk = new ServerlessSDK();
await accountUtils.refreshToken(sdk);
user = configUtils.getLoggedInUser();
sdk.config({ accessKey: user.idToken });
orgs = new Set(
(await sdk.organizations.list({ username: user.username })).map((org) => org.tenantName)
);
}
return orgs;
},
setOrgAndApp: async (context, stepData) => {
const { history, stepHistory } = context;
const { orgNames, isFullyPreconfigured, isMonitoringOverridenByCli } = stepData;
let { orgName, apps, newAppName, appName } = stepData;
if (!orgName) {
orgName = await (async () => {
// We only want to automatically select the single available org in situations where user explicitly
// logged in/registered during the process and created new service, for existing services we want to always ask
// that question. It will also be always asked if `SERVERLESS_ACCESS_KEY` was provided
if (
orgNames.size === 1 &&
history &&
history.has('dashboardLogin') &&
history.has('service')
) {
return orgNames.values().next().value;
}
return orgsChoice(orgNames, stepHistory);
})();
}
if (orgName === '_skip_') {
return;
}
const sdk = await getPlatformClientWithAccessKey(orgName);
if (!newAppName && !appName) {
if (!apps) apps = await sdk.apps.list({ orgName });
const appNames = apps.map((app) => app.appName);
if (!apps.length) {
newAppName = context.configuration.service;
} else {
appName = await appNameChoice(appNames, stepHistory);
if (appName === '_create_') {
newAppName = await appNameInput(appNames, stepHistory);
}
}
}
if (newAppName) {
({ appName } = await sdk.apps.create({ orgName, app: { name: newAppName } }));
}
if (isMonitoringOverridenByCli && isFullyPreconfigured) {
const shouldOverrideDashboardConfig = await promptWithHistory({
message:
'Are you sure you want to update monitoring settings ' +
`to ${chalk.bold(`org: ${orgName}, app: ${appName}`)}`,
type: 'confirm',
name: 'shouldOverrideDashboardConfig',
stepHistory,
});
if (!shouldOverrideDashboardConfig) {
delete context.configuration.app;
delete context.configuration.org;
return;
}
}
log.notice();
log.notice.success(
`Your project is ready to be deployed to Serverless Dashboard (org: "${orgName}", app: "${appName}")`
);
await writeOrgAndApp(orgName, appName, context);
return;
},
};
module.exports = {
async isApplicable(context) {
const { configuration, options, serviceDir } = context;
if (!serviceDir) {
context.inapplicabilityReasonCode = 'NOT_IN_SERVICE_DIRECTORY';
return false;
}
if (options.console) {
context.inapplicabilityReasonCode = 'CONSOLE_CONTEXT';
return false;
}
if (
_.get(configuration, 'provider') !== 'aws' &&
_.get(configuration, 'provider.name') !== 'aws'
) {
context.inapplicabilityReasonCode = 'NON_AWS_PROVIDER';
return false;
}
const sdk = new ServerlessSDK();
const { supportedRegions, supportedRuntimes } = await sdk.metadata.get();
// We want to still allow onboarding from Dashboard (idenfitied by explicit `--org` passed)
if (
!options.org &&
!supportedRuntimes.includes(_.get(configuration.provider, 'runtime') || 'nodejs12.x')
) {
context.inapplicabilityReasonCode = 'UNSUPPORTED_RUNTIME';
return false;
}
if (
!supportedRegions.includes(options.region || configuration.provider.region || 'us-east-1')
) {
context.inapplicabilityReasonCode = 'UNSUPPORTED_REGION';
return false;
}
const usesServerlessAccessKey = Boolean(process.env.SERVERLESS_ACCESS_KEY);
let user = configUtils.getLoggedInUser();
if (!user && !usesServerlessAccessKey) {
context.inapplicabilityReasonCode = 'NOT_LOGGED_IN';
return false;
}
const orgNames = await steps.resolveOrgNames(user);
if (!orgNames.size) {
context.inapplicabilityReasonCode = 'NO_ORGS_AVAILABLE';
return false;
}
if (!usesServerlessAccessKey) {
user = configUtils.getLoggedInUser(); // Refreshed, as new token might have been generated
}
const isMonitoringPreconfigured = Boolean(configuration.org);
const orgName = options.org || configuration.org;
const appName = options.app || configuration.app;
const isDashboardAppPreconfigured = Boolean(configuration.app);
const isMonitoringOverridenByCli =
isMonitoringPreconfigured &&
((options.org && options.org !== configuration.org) ||
(options.app && options.app !== configuration.app));
const isFullyPreconfigured = isMonitoringPreconfigured && isDashboardAppPreconfigured;
if (orgName && orgNames.has(orgName)) {
if (!isValidAppName(appName)) {
return {
user,
orgName,
isFullyPreconfigured,
isMonitoringPreconfigured,
isDashboardAppPreconfigured,
isMonitoringOverridenByCli,
};
}
const accessKey = await getOrCreateAccessKeyForOrg(orgName);
sdk.config({ accessKey });
const apps = await sdk.apps.list({ orgName });
if (options.org || options.app) {
if (apps.some((app) => app.appName === appName)) {
if (
isMonitoringPreconfigured &&
isDashboardAppPreconfigured &&
!isMonitoringOverridenByCli
) {
context.inapplicabilityReasonCode = 'MONITORING_NOT_OVERRIDEN_BY_CLI';
return false;
}
return {
user,
orgName,
appName,
isFullyPreconfigured,
isMonitoringPreconfigured,
isDashboardAppPreconfigured,
isMonitoringOverridenByCli,
};
}
if (options.app) {
log.error();
log.error('Passed value for "--app" doesn\'t seem to correspond to chosen organization.');
}
return {
user,
orgName,
isFullyPreconfigured,
isMonitoringPreconfigured,
isDashboardAppPreconfigured,
isMonitoringOverridenByCli,
};
} else if (apps.some((app) => app.appName === appName)) {
if (!isMonitoringOverridenByCli) {
context.inapplicabilityReasonCode = 'HAS_MONITORING_SETUP';
return false;
}
return {
user,
orgName,
appName,
isFullyPreconfigured,
isMonitoringPreconfigured,
isDashboardAppPreconfigured,
isMonitoringOverridenByCli,
};
}
return {
user,
orgName,
apps,
newAppName: appName,
isFullyPreconfigured,
isMonitoringPreconfigured,
isDashboardAppPreconfigured,
isMonitoringOverridenByCli,
};
} else if (orgName) {
if (options.org) {
log.error();
log.error(
'Passed value for "--org" doesn\'t seem to correspond to account with which you\'re logged in with.'
);
} else {
log.error();
log.error(`Configured org "${orgName}" is not available in your account.`);
}
}
return {
user,
orgNames,
isFullyPreconfigured,
isMonitoringPreconfigured,
isDashboardAppPreconfigured,
isMonitoringOverridenByCli,
};
},
async run(context, stepData) {
const { configuration, options, stepHistory } = context;
if (context.initial.isInServiceContext && !context.initial.isDashboardEnabled) {
showOnboardingWelcome(context);
}
if (!stepData.orgName) delete configuration.org;
if (!stepData.appName && !stepData.newAppName) delete configuration.app;
if (!options.org && !options.app) {
if (stepData.isMonitoringPreconfigured) {
if (!stepData.orgName) {
if (!(await orgUpdateConfirm(stepHistory))) return;
} else if (stepData.newAppName && stepData.isMonitoringPreconfigured) {
const appUpdateTypeChoice = await appUpdateConfirm(
stepData.newAppName,
stepData.orgName,
stepHistory
);
switch (appUpdateTypeChoice) {
case '_create_':
break;
case '_choose_existing_':
delete stepData.newAppName;
break;
case '_skip_':
return;
default:
throw new Error('Unexpected app update type');
}
}
}
}
await steps.setOrgAndApp(context, stepData);
},
steps,
configuredQuestions: [
'orgName',
'appName',
'newAppName',
'shouldUpdateOrg',
'appUpdateType',
'shouldOverrideDashboardConfig',
],
};