diff --git a/package.json b/package.json index d10fe9a3..fdf2c80d 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,7 @@ "docs": "jsdoc -c .jsdoc.js", "generate-scaffolding": "repo-tools generate all && repo-tools generate lib_samples_readme -l samples/ --config ../.cloud-repo-tools.json", "lint": "eslint '**/*.js'", - "samples-test": "cd samples/ && npm link ../ && cd startup-script && npm link ../../ && cd ../ && npm test && cd ../", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", "system-test": "mocha system-test/*.js --timeout 600000", "test": "nyc mocha", "fix": "eslint --fix '**/*.js'" diff --git a/samples/createVM.js b/samples/createVM.js new file mode 100644 index 00000000..788e301e --- /dev/null +++ b/samples/createVM.js @@ -0,0 +1,28 @@ +// Copyright 2017, Google, Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function createVM( + vmName = 'new_virtual_machine' // VM name of your choice +) { + const Compute = require('@google-cloud/compute'); + const compute = new Compute(); + const zone = compute.zone('us-central1-c'); + const [vm, operation] = await zone.createVM(vmName, {os: 'ubuntu'}); + console.log(vm); + await operation.promise(); + console.log('Virtual machine created!'); +} + +createVM(...process.argv.slice(2)).catch(console.error); diff --git a/samples/deleteVM.js b/samples/deleteVM.js new file mode 100644 index 00000000..fe88f0dc --- /dev/null +++ b/samples/deleteVM.js @@ -0,0 +1,28 @@ +// Copyright 2017, Google, Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +async function deleteVM( + name = 'virtual_machine_name' // VM name of your choice +) { + const Compute = require('@google-cloud/compute'); + const compute = new Compute(); + const zone = compute.zone('us-central1-c'); + const vm = zone.vm(name); + const [operation] = await vm.delete(); + await operation.promise(); + console.log(`VM deleted!`); +} + +deleteVM(...process.argv.slice(2)).catch(console.error); diff --git a/samples/system-test/vms.test.js b/samples/listVMs.js similarity index 64% rename from samples/system-test/vms.test.js rename to samples/listVMs.js index ff6a6d85..b2375a41 100644 --- a/samples/system-test/vms.test.js +++ b/samples/listVMs.js @@ -15,16 +15,16 @@ 'use strict'; -const execa = require('execa'); -const path = require(`path`); -const {assert} = require('chai'); - -const cmd = `node vms.js`; -const cwd = path.join(__dirname, `..`); - -describe('should retrieve list of vms', () => { - it('vms_inspect_string', async () => { - const {stdout} = await execa.shell(cmd, {cwd}); - assert.match(stdout, /^VMs:/); +// [START list] +async function listVMs() { + const Compute = require('@google-cloud/compute'); + const compute = new Compute(); + const vms = await compute.getVMs({ + maxResults: 10, }); -}); + console.log(`Found ${vms.length} VMs!`); + vms.forEach(vm => console.log(vm)); +} +// [END list] + +listVMs().catch(console.error); diff --git a/samples/mailjet.js b/samples/mailjet.js index 3adf5b61..f0e559f3 100644 --- a/samples/mailjet.js +++ b/samples/mailjet.js @@ -39,6 +39,6 @@ async function mailjet() { }); console.log(json); } -mailjet().catch(console.error); - // [END send] + +mailjet().catch(console.error); diff --git a/samples/package.json b/samples/package.json index b04cc1fd..59033459 100644 --- a/samples/package.json +++ b/samples/package.json @@ -11,22 +11,20 @@ "node": ">=8" }, "scripts": { - "system-test": "mocha system-test/*.js --timeout 600000", - "startup-test": "mocha startup-script/system-test/*.test.js --timeout 600000", - "test": "npm run system-test && npm run startup-test" + "test": "mocha --timeout 1200000" }, "dependencies": { + "node-fetch": "^2.3.0", "@google-cloud/compute": "^0.11.0", - "googleapis": "^36.0.0", "nodemailer": "^4.3.1", "nodemailer-smtp-transport": "^2.7.4", - "sendgrid": "^5.2.3", - "uuid": "^3.2.1" + "sendgrid": "^5.2.3" }, "devDependencies": { "chai": "^4.2.0", "execa": "^1.0.0", "mocha": "^5.0.0", - "proxyquire": "^2.0.1" + "proxyquire": "^2.0.1", + "uuid": "^3.2.1" } } diff --git a/samples/quickstart.js b/samples/quickstart.js index a65c414f..522d26c4 100644 --- a/samples/quickstart.js +++ b/samples/quickstart.js @@ -11,32 +11,31 @@ // See the License for the specific language governing permissions and // limitations under the License. -/* eslint-disable no-unused-vars */ - 'use strict'; // [START compute_engine_quickstart] -// Imports the Google Cloud client library -const Compute = require('@google-cloud/compute'); -const uuid = require('uuid'); -// Creates a client -const compute = new Compute(); +async function createVM( + vmName = 'new_virtual_machine' // VM name of your choice +) { + // Imports the Google Cloud client library + const Compute = require('@google-cloud/compute'); -// Create a new VM using the latest OS image of your choice. -const zone = compute.zone('us-central1-a'); -const name = `ubuntu-http-${uuid().split('-')[0]}`; + // Creates a client + const compute = new Compute(); -async function createVM() { - const data = await zone.createVM(name, {os: 'ubuntu'}); + // Create a new VM using the latest OS image of your choice. + const zone = compute.zone('us-central1-c'); - // `operation` lets you check the status of long-running tasks. - const vm = data[0]; - const operation = data[1]; + // Start the VM create task + const [vm, operation] = await zone.createVM(vmName, {os: 'ubuntu'}); + console.log(vm); + // `operation` lets you check the status of long-running tasks. await operation.promise(); - // Virtual machine created! -} - -createVM().catch(console.error); + // Complete! + console.log('Virtual machine created!'); +} // [END compute_engine_quickstart] + +createVM(...process.argv.slice(2)).catch(console.error); diff --git a/samples/startup-script/README.md b/samples/startup-script/README.md deleted file mode 100644 index dbf327f5..00000000 --- a/samples/startup-script/README.md +++ /dev/null @@ -1,70 +0,0 @@ -Google Cloud Platform logo - -# Create VM with Apache and Custom Homepage - -[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-compute&page=editor&open_in_editor=samples/startup-script/index.js,samples/startup-script/README.md) - -This example shows how to create a VM with Apache and a custom homepage. On creation, the -VM runs the startup script. The startup script installs -Apache and a custom homepage. You can change to script to fit your needs, for example -run a Node.js server on the VM. - -### Before you begin - -Before running the samples, make sure you've followed the steps in the -[Before you begin section](../../README.md#before-you-begin) of the client -library's README and that your environment variable -`GOOGLE_APPLICATION_CREDENTIALS` is set. - -### Run the sample - -``` -git clone git@github.com:googleapis/nodejs-compute.git -cd nodejs-compute/samples/startup-script -npm install -npm start -``` - -On success, you should see output like this: - -``` -npm start - -> compute-sample-startup-script@1.0.0 start nodejs-compute/samples/startup-script -> node -e 'require("./index.js").create("vm-with-apache", console.log)' - -Booting new VM with IP http://35.202.127.163... -................................. Ready! -null '35.202.127.163' -``` - -You can test the new VM in your browser by navigating to its IP address. - -![Screenshot of homepage][homepage_img] - -### Cleanup - -Delete the VM you just created by running the following: - -``` -npm run delete -``` - -To see all the VMs currently running in your project, run `npm run list` or use the [Cloud Console](https://console.cloud.google.com/compute/instances). - - -### Troubleshooting - -It takes about two minutes to install Apache. If you cannot access the homepage, -connect to the VM and check the log files in `/var/log/syslog`. You can use the [Cloud Console](https://console.cloud.google.com/compute/instance) to connect to a VM or use -the following command: - -`gcloud compute --project "YOUR PROJECT ID" ssh --zone "us-central1-a" "vm-with-apache"` - -Keep in -mind that the startup script is run as root with a different -home directory than your default user. - -[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png -[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-compute&page=editor&open_in_editor=samples/startup-script/README.md -[homepage_img]: ./apache.png \ No newline at end of file diff --git a/samples/startup-script/apache.png b/samples/startup-script/apache.png deleted file mode 100644 index 2aebdd83..00000000 Binary files a/samples/startup-script/apache.png and /dev/null differ diff --git a/samples/startup-script/package.json b/samples/startup-script/package.json deleted file mode 100644 index 1f06ebaf..00000000 --- a/samples/startup-script/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "compute-sample-startup-script", - "version": "1.0.0", - "description": "Start a Google Compute Engine and run the startup script.", - "main": "index.js", - "files": [ - "*.js" - ], - "dependencies": { - "@google-cloud/compute": "0.10.0", - "node-fetch": "^2.2.0" - }, - "engines": { - "node": ">=8" - }, - "devDependencies": { - "mocha": "^5.0.0", - "uuid": "^3.2.1" - }, - "scripts": { - "test": "mocha system-test/*.js --timeout 600000", - "start": "node -e 'require(\"./index.js\").createVM(\"vm-with-apache\", console.log)'", - "delete": "node -e 'require(\"./index.js\").deleteVM(\"vm-with-apache\", console.log)'", - "list": "node -e 'require(\"./index.js\").listVMs(console.log)'" - }, - "author": "Google, LLC", - "license": "Apache-2.0" -} diff --git a/samples/startup-script/system-test/.eslintrc.yml b/samples/startup-script/system-test/.eslintrc.yml deleted file mode 100644 index 6db2a46c..00000000 --- a/samples/startup-script/system-test/.eslintrc.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- -env: - mocha: true diff --git a/samples/startup-script/system-test/index.test.js b/samples/startup-script/system-test/index.test.js deleted file mode 100644 index e6eadacb..00000000 --- a/samples/startup-script/system-test/index.test.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2018, Google, Inc. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const uuid = require('uuid'); -const assert = require('assert'); - -const example = require('../index'); -const name = `gcloud-apache-${uuid.v4().split('-')[0]}`; - -describe('start-up script', async () => { - it('should create vm', async () => { - const ip = await example.createVM(name); - assert.ok(ip); - }); - - it('should list vms', async () => { - const vms = await example.listVMs(); - assert.ok(vms); - assert.ok(Array.isArray(vms)); - }); - - it('should delete vm', async () => { - const result = await example.deleteVM(name); - assert.strictEqual(result, name); - }); -}); diff --git a/samples/startup-script/index.js b/samples/startupScript.js similarity index 62% rename from samples/startup-script/index.js rename to samples/startupScript.js index 4f09b3d8..e09af659 100644 --- a/samples/startup-script/index.js +++ b/samples/startupScript.js @@ -19,16 +19,15 @@ const Compute = require('@google-cloud/compute'); const fetch = require('node-fetch'); const compute = new Compute(); -const zone = compute.zone('us-central1-a'); +const zone = compute.zone('us-central1-c'); /** * Create a new virtual machine with Ubuntu and Apache * @param {string} name Name of the virtual machine */ -async function createVM(name) { +async function createVMWithStartupScript(name) { // Create a new VM, using default ubuntu image. The startup script // installs apache and a custom homepage. - const config = { os: 'ubuntu', http: true, @@ -60,18 +59,16 @@ async function createVM(name) { console.log('Acquiring VM metadata...'); const [metadata] = await vm.getMetadata(); - console.log(metadata); // External IP of the VM. const ip = metadata.networkInterfaces[0].accessConfigs[0].natIP; console.log(`Booting new VM with IP http://${ip}...`); // Ping the VM to determine when the HTTP server is ready. - console.log(`Operation complete. Waiting for IP ...`); + console.log('Operation complete. Waiting for IP'); await pingVM(ip); - console.log(`${name} created succesfully`); - return ip; + console.log(`\n${name} created succesfully`); } /** @@ -79,60 +76,20 @@ async function createVM(name) { * @param {string} ip IP address to poll */ async function pingVM(ip) { - let waiting = true; - while (waiting) { + let exit = false; + while (!exit) { await new Promise(r => setTimeout(r, 2000)); try { const res = await fetch(`http://${ip}`); - const statusCode = res.status; - if (statusCode === 200) { - waiting = false; - console.log('Ready!'); - return; - } else { - process.stdout.write('.'); + if (res.status !== 200) { + throw new Error(res.status); } + exit = true; } catch (err) { process.stdout.write('.'); } } } -/** - * List all VMs and their external IPs in a given zone. - */ -async function listVMs() { - const [vms] = await zone.getVMs(); - const results = await Promise.all( - vms.map(async vm => { - const [metadata] = await vm.getMetadata(); - return { - ip: metadata['networkInterfaces'][0]['accessConfigs'] - ? metadata['networkInterfaces'][0]['accessConfigs'][0]['natIP'] - : 'no external ip', - name: metadata.name, - }; - }) - ); - console.log(results); - return results; -} - -/** - * Delete a VM with a given name. - * @param {string} name - */ -async function deleteVM(name) { - const vm = zone.vm(name); - console.log(`Deleting ${name} ...`); - const [operation] = await vm.delete(); - console.log(`Polling operation ${operation.id} ...`); - await operation.promise(); - console.log(`${name} deleted succesfully!`); - return name; -} -module.exports = { - createVM, - deleteVM, - listVMs, -}; +const args = process.argv.slice(2); +createVMWithStartupScript(...args).catch(console.error); diff --git a/samples/system-test/.eslintrc.yml b/samples/system-test/.eslintrc.yml deleted file mode 100644 index 6db2a46c..00000000 --- a/samples/system-test/.eslintrc.yml +++ /dev/null @@ -1,3 +0,0 @@ ---- -env: - mocha: true diff --git a/samples/system-test/vms_api.test.js b/samples/system-test/vms_api.test.js deleted file mode 100644 index b53e60af..00000000 --- a/samples/system-test/vms_api.test.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2017, Google, Inc. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const execa = require(`execa`); -const path = require(`path`); -const {assert} = require('chai'); - -const cmd = `node vms_api.js`; -const cwd = path.join(__dirname, `..`); - -describe('should retrieve list of vms via api', () => { - it('vms_api_inspect_string', async () => { - const {stdout} = await execa.shell(cmd, {cwd}); - assert.match(stdout, /^VMs:/); - }); -}); diff --git a/samples/test/samples.test.js b/samples/test/samples.test.js new file mode 100644 index 00000000..9c76232e --- /dev/null +++ b/samples/test/samples.test.js @@ -0,0 +1,72 @@ +/** + * Copyright 2018, Google, Inc. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +const uuid = require('uuid'); +const execa = require('execa'); +const {assert} = require('chai'); +const Compute = require('@google-cloud/compute'); + +const exec = async cmd => (await execa.shell(cmd)).stdout; +const compute = new Compute(); + +describe('quickstart', () => { + const name = `gcloud-ubuntu-${uuid.v4().split('-')[0]}`; + after(async () => deleteVM(name)); + it('should run the quickstart', async () => { + const output = await exec(`node quickstart ${name}`); + assert.match(output, /Virtual machine created!/); + }); +}); + +describe('lifecycle', async () => { + const name = `gcloud-ubuntu-${uuid.v4().split('-')[0]}`; + + it('should create a VM', async () => { + const output = await exec(`node createVM ${name}`); + assert.match(output, /Virtual machine created!/); + }); + + it('should list the VMs', async () => { + const output = await exec('node listVMs'); + assert.match(output, /Found \d+ VMs!/); + }); + + it('should delete the VM', async () => { + const output = await exec(`node deleteVM ${name}`); + assert.match(output, /VM deleted!/); + }); +}); + +describe('start-up script', async () => { + const name = `gcloud-apache-${uuid.v4().split('-')[0]}`; + after(async () => deleteVM(name)); + it('should create vm with startup script', async () => { + const output = await exec(`node startupScript ${name}`); + assert.match(output, /created succesfully$/); + }); +}); + +/** + * Utility function to delete a VM. + * @param {string} name + */ +async function deleteVM(name) { + const zone = compute.zone('us-central1-c'); + const vm = zone.vm(name); + const [operation] = await vm.delete(); + await operation.promise(); +} diff --git a/samples/vms_api.js b/samples/vms_api.js deleted file mode 100644 index ea9ab7fe..00000000 --- a/samples/vms_api.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright 2017, Google, Inc. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -// [START complete] -// [START initialize] -const {google} = require('googleapis'); -const compute = google.compute('v1'); -// [END initialize] - -// [START list] -/** - * @param {Function} callback Callback function. - */ -async function getVmsExample() { - const authClient = await google.auth.getClient({ - scopes: [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/compute', - 'https://www.googleapis.com/auth/compute.readonly', - ], - }); - const projectId = await google.auth.getProjectId(); - - // Retrieve the vms - const result = await compute.instances.aggregatedList({ - auth: authClient, - project: projectId, - // In this example we only want one VM per page - maxResults: 1, - }); - const vms = result.data; - console.log('VMs:', vms); - return vms; -} -// [END list] -// [END complete] - -// Run the examples -getVmsExample().catch(console.error);