Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(CLI Onboarding): Add deploy step #9536

Merged
merged 1 commit into from
Jun 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
47 changes: 8 additions & 39 deletions lib/cli/interactive-setup/aws-credentials.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,20 @@ const chalk = require('chalk');
const _ = require('lodash');
const inquirer = require('@serverless/utils/inquirer');
const memoizee = require('memoizee');
medikoo marked this conversation as resolved.
Show resolved Hide resolved
const configUtils = require('@serverless/utils/config');

const AWS = require('aws-sdk');

const awsCredentials = require('../../plugins/aws/utils/credentials');
const { confirm } = require('./utils');
const { confirm, doesServiceInstanceHaveLinkedProvider } = require('./utils');
const openBrowser = require('../../utils/openBrowser');
const ServerlessError = require('../../serverless-error');
const resolveStage = require('../../utils/resolve-stage');
const resolveRegion = require('../../utils/resolve-region');

const isValidAwsAccessKeyId = RegExp.prototype.test.bind(/^[A-Z0-9]{10,}$/);
const isValidAwsSecretAccessKey = RegExp.prototype.test.bind(/^[a-zA-Z0-9/+]{10,}$/);
const { getPlatformClientWithAccessKey } = require('@serverless/dashboard-plugin/lib/clientUtils');
const resolveProviderCredentials = require('@serverless/dashboard-plugin/lib/resolveProviderCredentials');
const resolveStage = require('../../utils/resolve-stage');
const resolveRegion = require('../../utils/resolve-region');
const isAuthenticated = require('@serverless/dashboard-plugin/lib/isAuthenticated');

const CREDENTIALS_SETUP_CHOICE = {
LOCAL: '_local_',
Expand All @@ -36,25 +35,6 @@ const getSdkInstance = memoizee(
{ promise: true }
);

const doesServiceInstanceHaveLinkedProvider = async ({ configuration, options }) => {
const region = resolveRegion({ configuration, options });
const stage = resolveStage({ configuration, options });
let result;
try {
result = await resolveProviderCredentials({ configuration, region, stage });
} catch (err) {
if (err.statusCode && err.statusCode >= 500) {
throw new ServerlessError(
'Dashboard service is currently unavailable, please try again later',
'DASHBOARD_UNAVAILABLE'
);
}
throw err;
}

return Boolean(result);
};

const getOrgUidByName = memoizee(
async (orgName) => {
const sdk = await getSdkInstance(orgName);
Expand Down Expand Up @@ -321,18 +301,6 @@ const steps = {
},
};

const isUserLoggedIn = () => {
if (process.env.SERVERLESS_ACCESS_KEY) {
return true;
}

if (configUtils.getLoggedInUser()) {
return true;
}

return false;
};

module.exports = {
async isApplicable(context) {
const { configuration, history, options } = context;
Expand All @@ -346,7 +314,7 @@ module.exports = {
if ((await awsCredentials.resolveFileProfiles()).size) return false;

const orgName = configuration.org;
if (orgName && isUserLoggedIn()) {
if (orgName && isAuthenticated()) {
let providers;
try {
providers = await getProviders(orgName);
Expand Down Expand Up @@ -379,7 +347,7 @@ module.exports = {

// It is possible that user decides to not configure org for his service and
// we still should allow setup of local credentials in such case
if (context.configuration.org && isUserLoggedIn()) {
if (context.configuration.org && isAuthenticated()) {
try {
providers = await getProviders(context.configuration.org);
} catch (err) {
Expand All @@ -396,7 +364,8 @@ module.exports = {
try {
const createdProviderUid = await steps.handleProviderCreation(context);
const hadExistingProviders = Boolean(providers.length);
if (createdProviderUid && hadExistingProviders) {
const shouldLinkProvider = createdProviderUid && hadExistingProviders;
if (shouldLinkProvider) {
// This is situation where user decided to create a new provider and already had previous providers setup
// In this case, we want to setup an explicit link between provider and service as the newly created provider
// might not be the default one.
Expand Down
36 changes: 36 additions & 0 deletions lib/cli/interactive-setup/deploy-progress-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

const cliProgressFooter = require('cli-progress-footer');
const chalk = require('chalk');

class InteractiveDeployProgress {
constructor(serverless) {
this.serverless = serverless;
this.progress = cliProgressFooter({ overrideStdout: false });
this.progress.shouldAddProgressAnimationPrefix = true;

this.hooks = {
'before:deploy:deploy': async () => {
this.progress.updateProgress('Deploying your project...\n');
},
'deploy:finalize': async () => {
this.progress.updateProgress('');
this.progress.writeStdout(chalk.green('\nDeployment succesful\n'));
},

'package:initialize': async () => {
this.progress.updateProgress('Packaging your project...\n');
},
'package:finalize': async () => {
this.progress.updateProgress('');
this.progress.writeStdout(chalk.green('\nPackaging succesful\n'));
},
};
}

handleError() {
this.progress.updateProgress('');
}
}

module.exports = InteractiveDeployProgress;
177 changes: 177 additions & 0 deletions lib/cli/interactive-setup/deploy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
'use strict';

const Serverless = require('../../Serverless');
const chalk = require('chalk');
const { confirm, doesServiceInstanceHaveLinkedProvider } = require('./utils');
const _ = require('lodash');
const overrideStdoutWrite = require('process-utils/override-stdout-write');
const { getDashboardInteractUrl } = require('@serverless/dashboard-plugin/lib/dashboard');
const AWS = require('aws-sdk');
const isAuthenticated = require('@serverless/dashboard-plugin/lib/isAuthenticated');

const printMessage = ({
serviceName,
hasBeenDeployed,
dashboardPlugin,
isConfiguredWithDashboard,
}) => {
if (isConfiguredWithDashboard) {
if (hasBeenDeployed) {
process.stdout.write(
[
`\n${chalk.green('Your project is live and available in ')}${chalk.white.bold(
`./${serviceName}`
)}`,
`\n Run ${chalk.bold('serverless info')} in the project directory`,
' View your endpoints and services',
`\n Open ${chalk.bold(getDashboardInteractUrl(dashboardPlugin))}`,
' Invoke your functions and view logs in the dashboard',
`\n Run ${chalk.bold('serverless deploy')} in the project directory`,
" Redeploy your service after you've updated your service code or configuration\n\n",
].join('\n')
);

return;
}

process.stdout.write(
[
`\n${chalk.green(
'Your project is ready for deployment and available in '
)}${chalk.white.bold(`./${serviceName}`)}`,
`\n Run ${chalk.bold('serverless deploy')} in the project directory`,
' Deploy your newly created service',
`\n Run ${chalk.bold('serverless info')} in the project directory after deployment`,
' View your endpoints and services',
'\n Open Serverless Dashboard after deployment',
' Invoke your functions and view logs in the dashboard\n\n',
].join('\n')
);
return;
}

if (hasBeenDeployed) {
process.stdout.write(
[
`\n${chalk.green('Your project is live and available in ')}${chalk.white.bold(
`./${serviceName}`
)}`,
`\n Run ${chalk.bold('serverless info')} in the project directory`,
' View your endpoints and services',
`\n Run ${chalk.bold('serverless deploy')} in the directory`,
" Redeploy your service after you've updated your service code or configuration",
`\n Run ${chalk.bold('serverless invoke')} and ${chalk.bold(
'serverless logs'
)} in the project directory`,
' Invoke your functions directly and view the logs',
`\n Run ${chalk.bold('serverless')} in the project directory`,
' Add metrics, alerts, and a log explorer, by enabling the dashboard functionality\n\n',
].join('\n')
);
return;
}

process.stdout.write(
[
`\n${chalk.green('Your project is ready for deployment and available in ')}${chalk.white.bold(
`./${serviceName}`
)}`,
`\n Run ${chalk.bold('serverless deploy')} in the project directory`,
' Deploy your newly created service',
`\n Run ${chalk.bold('serverless info')} in the project directory after deployment`,
' View your endpoints and services',
`\n Run ${chalk.bold('serverless invoke')} and ${chalk.bold(
'serverless logs'
)} in the project directory after deployment`,
' Invoke your functions directly and view the logs',
`\n Run ${chalk.bold('serverless')} in the project directory`,
' Add metrics, alerts, and a log explorer, by enabling the dashboard functionality\n\n',
].join('\n')
);
};

const configurePlugin = (serverless, originalStdWrite) => {
serverless.pluginManager.addPlugin(require('./deploy-progress-plugin'));
const interactivePlugin = serverless.pluginManager.plugins.find(
(plugin) => plugin.constructor.name === 'InteractiveDeployProgress'
);
interactivePlugin.progress._writeOriginalStdout = (data) => originalStdWrite(data);
return interactivePlugin;
};

module.exports = {
async isApplicable({ configuration, serviceDir, history, options }) {
if (!serviceDir) {
return false;
}

if (
_.get(configuration, 'provider') !== 'aws' &&
_.get(configuration, 'provider.name') !== 'aws'
) {
return false;
}

// If `awsCredentials` step was not executed, we should proceed as it means that user has available credentials
if (!history.has('awsCredentials')) return true;

// We want to proceed if the service instance has a linked provider
if (
configuration.org &&
isAuthenticated() &&
(await doesServiceInstanceHaveLinkedProvider({ configuration, options }))
medikoo marked this conversation as resolved.
Show resolved Hide resolved
) {
return true;
}

// We want to proceed if local credentials are available
if (new AWS.Config().credentials) return true;

return false;
},
async run({ configuration, configurationFilename, serviceDir }) {
const serviceName = configuration.service;
if (!(await confirm('Do you want to deploy your project?', { name: 'shouldDeploy' }))) {
printMessage({
serviceName,
hasBeenDeployed: false,
isConfiguredWithDashboard: Boolean(configuration.org),
});
return;
}

const serverless = new Serverless({
configuration,
serviceDir,
configurationFilename,
isConfigurationResolved: true,
hasResolvedCommandsExternally: true,
isTelemetryReportedExternally: true,
commands: ['deploy'],
options: {},
});

let interactiveOutputPlugin;

try {
await overrideStdoutWrite(
() => {},
async (originalStdWrite) => {
await serverless.init();
interactiveOutputPlugin = configurePlugin(serverless, originalStdWrite);
await serverless.run();
}
);
} catch (err) {
interactiveOutputPlugin.handleError();
throw err;
}

printMessage({
serviceName,
hasBeenDeployed: true,
isConfiguredWithDashboard: Boolean(configuration.org),
dashboardPlugin: serverless.pluginManager.dashboardPlugin,
});
},
};
1 change: 1 addition & 0 deletions lib/cli/interactive-setup/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const steps = {
dashboardLogin: require('@serverless/dashboard-plugin/lib/cli/interactive-setup/dashboard-login'),
dashboardSetOrg: require('@serverless/dashboard-plugin/lib/cli/interactive-setup/dashboard-set-org'),
awsCredentials: require('./aws-credentials'),
deploy: require('./deploy'),
};

module.exports = async (context) => {
Expand Down
6 changes: 4 additions & 2 deletions lib/cli/interactive-setup/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ module.exports = {
}

if (hasPackageJson) {
process.stdout.write(`\nInstalling dependencies with "npm" in "${projectName}" folder.\n`);
process.stdout.write(`\nInstalling dependencies with "npm" in "${projectName}" folder\n`);
const npmCommand = await npmCommandDeferred;
try {
await spawn(npmCommand, ['install'], { cwd: projectDir });
Expand Down Expand Up @@ -228,7 +228,9 @@ module.exports = {
}

process.stdout.write(
`\n${chalk.green(`Project successfully created in '${projectName}' folder.`)}\n`
`\n${chalk.green(
`Project successfully created in ${chalk.white.bold(projectName)} folder`
)}\n`
);
context.serviceDir = projectDir;
const configurationPath = await resolveConfigurationPath({ cwd: projectDir, options: {} });
Expand Down
22 changes: 22 additions & 0 deletions lib/cli/interactive-setup/utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
'use strict';

const inquirer = require('@serverless/utils/inquirer');
const ServerlessError = require('../../serverless-error');
const resolveProviderCredentials = require('@serverless/dashboard-plugin/lib/resolveProviderCredentials');
const resolveStage = require('../../utils/resolve-stage');
const resolveRegion = require('../../utils/resolve-region');

module.exports = {
confirm: async (message, options = {}) => {
Expand All @@ -13,4 +17,22 @@ module.exports = {
})
)[name];
},
doesServiceInstanceHaveLinkedProvider: async ({ configuration, options }) => {
const region = resolveRegion({ configuration, options });
const stage = resolveStage({ configuration, options });
let result;
try {
result = await resolveProviderCredentials({ configuration, region, stage });
} catch (err) {
if (err.statusCode && err.statusCode >= 500) {
throw new ServerlessError(
'Dashboard service is currently unavailable, please try again later',
'DASHBOARD_UNAVAILABLE'
);
}
throw err;
}

return Boolean(result);
},
};
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"chalk": "^4.1.1",
"child-process-ext": "^2.1.1",
"ci-info": "^3.2.0",
"cli-progress-footer": "^1.1.1",
"d": "^1.0.1",
"dayjs": "^1.10.5",
"decompress": "^4.2.1",
Expand All @@ -61,6 +62,7 @@
"node-fetch": "^2.6.1",
"object-hash": "^2.2.0",
"path2": "^0.1.0",
"process-utils": "^4.0.0",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's also remove it from devDependencies

"promise-queue": "^2.2.5",
"replaceall": "^0.1.6",
"semver": "^7.3.5",
Expand Down Expand Up @@ -93,7 +95,6 @@
"nyc": "^15.1.0",
"pkg": "^4.5.1",
"prettier": "^2.3.1",
"process-utils": "^4.0.0",
"proxyquire": "^2.1.3",
"semver-regex": "^3.1.2",
"sinon": "^11.1.1",
Expand Down