Skip to content

Commit

Permalink
feat!: new generated version of compute API (#537)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-fenster authored Aug 11, 2021
1 parent f75c2e7 commit 2dd1d37
Show file tree
Hide file tree
Showing 23 changed files with 742 additions and 386 deletions.
4 changes: 0 additions & 4 deletions compute/.eslintrc.yml

This file was deleted.

112 changes: 112 additions & 0 deletions compute/createInstance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Copyright 2021 Google LLC
//
// 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.

/**
* Sends an instance creation request to GCP and waits for it to complete.
*
* @param {string} projectId - ID or number of the project you want to use.
* @param {string} zone - Name of the zone you want to check, for example: us-west3-b
* @param {string} instanceName - Name of the new machine.
* @param {string} machineType - Machine type you want to create in following format:
* "zones/{zone}/machineTypes/{type_name}". For example:
* "zones/europe-west3-c/machineTypes/f1-micro"
* You can find the list of available machine types using:
* https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/list
* @param {string} sourceImage - Path the the disk image you want to use for your boot
* disk. This can be one of the public images
* (e.g. "projects/debian-cloud/global/images/family/debian-10")
* or a private image you have access to.
* You can check the list of available public images using:
* $ gcloud compute images list
* @param {string} networkName - Name of the network you want the new instance to use.
* For example: global/networks/default - if you want to use the default network.
*/
function main(
projectId,
zone,
instanceName,
machineType = 'n1-standard-1',
sourceImage = 'projects/debian-cloud/global/images/family/debian-10',
networkName = 'global/networks/default'
) {
// [START compute_instances_create]
/**
* TODO(developer): Uncomment and replace these variables before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'europe-central2-b'
// const instanceName = 'YOUR_INSTANCE_NAME'
// const machineType = 'n1-standard-1';
// const sourceImage = 'projects/debian-cloud/global/images/family/debian-10';
// const networkName = 'global/networks/default';

const compute = require('@google-cloud/compute');
const compute_protos = compute.protos.google.cloud.compute.v1;

// Create a new instance with the values provided above in the specified project and zone.
async function createInstance() {
const instancesClient = new compute.InstancesClient({fallback: 'rest'});

// Describe the size and source image of the boot disk to attach to the instance.
const attachedDisk = new compute_protos.AttachedDisk();
const initializeParams = new compute_protos.AttachedDiskInitializeParams();

initializeParams.diskSizeGb = '10';
initializeParams.sourceImage = sourceImage;

attachedDisk.initializeParams = initializeParams;
attachedDisk.autoDelete = true;
attachedDisk.boot = true;
attachedDisk.type = compute_protos.AttachedDisk.Type.PERSISTENT;

// Use the network interface provided in the networkName argument.
const networkInterface = new compute_protos.NetworkInterface();
networkInterface.name = networkName;

// Collect information into the Instance object.
const instance = new compute_protos.Instance();
instance.name = instanceName;
instance.disks = [attachedDisk];
instance.machineType = `zones/${zone}/machineTypes/${machineType}`;
instance.networkInterfaces = [networkInterface];

console.log(`Creating the ${instanceName} instance in ${zone}...`);

// Wait for the create operation to complete.
const [operation] = await instancesClient.insert({
instanceResource: instance,
project: projectId,
zone,
});

if (operation.status === 'RUNNING') {
const operationsClient = new compute.ZoneOperationsClient({
fallback: 'rest',
});

await operationsClient.wait({
operation: operation.name,
project: projectId,
zone: operation.zone.split('/').pop(),
});
}

console.log('Instance created.');
}

createInstance();
// [END compute_instances_create]
}

main(...process.argv.slice(2));
40 changes: 0 additions & 40 deletions compute/createVM.js

This file was deleted.

65 changes: 65 additions & 0 deletions compute/deleteInstance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2021 Google LLC
//
// 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.

/**
* Sends a delete request to GCP and waits for it to complete.
*
* @param {string} projectId - ID or number of the project you want to use.
* @param {string} zone - Name of the zone you want to check, for example: us-west3-b
* @param {string} instanceName - Name of the instance you want to delete.
*/
function main(projectId, zone, instanceName) {
// [START compute_instances_delete]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'europe-central2-b'
// const instanceName = 'YOUR_INSTANCE_NAME';

const compute = require('@google-cloud/compute');

// Delete the instance specified by `instanceName` if it's present in the given project and zone.
async function deleteInstance() {
const instancesClient = new compute.InstancesClient({fallback: 'rest'});

console.log(`Deleting ${instanceName} from ${zone}...`);

// Wait for the delete operation to complete.
const [operation] = await instancesClient.delete({
project: projectId,
zone,
instance: instanceName,
});

if (operation.status === 'RUNNING') {
const operationsClient = new compute.ZoneOperationsClient({
fallback: 'rest',
});

await operationsClient.wait({
operation: operation.name,
project: projectId,
zone: operation.zone.split('/').pop(),
});
}

console.log('Instance deleted.');
}

deleteInstance();
// [END compute_instances_delete]
}

main(...process.argv.slice(2));
40 changes: 0 additions & 40 deletions compute/deleteVM.js

This file was deleted.

61 changes: 61 additions & 0 deletions compute/getUsageExportBucket.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Copyright 2021 Google LLC
//
// 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.

/**
* Retrieve Compute Engine usage export bucket for the Cloud project. Replaces the empty value returned by the API with the default value used to generate report file names.
*
* @param {string} projectId - ID or number of the project you want to use.
*/
function main(projectId) {
// [START compute_usage_report_get]
/**
* TODO(developer): Uncomment and replace these variables before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';

const compute = require('@google-cloud/compute');

async function getUsageExportBucket() {
// Get the usage export location for the project from the server.
const projectsClient = new compute.ProjectsClient({fallback: 'rest'});
const [project] = await projectsClient.get({
project: projectId,
});

const usageExportLocation = project.usageExportLocation;

if (!usageExportLocation || !usageExportLocation.bucketName) {
// The usage reports are disabled.
return;
}

if (!usageExportLocation.reportNamePrefix) {
// Although the server explicitly sent the empty string value, the next usage report generated with these settings still has the default prefix value `usage_gce`. (see https://cloud.google.com/compute/docs/reference/rest/v1/projects/get)
console.log(
'Report name prefix not set, replacing with default value of `usage_gce`.'
);
usageExportLocation.reportNamePrefix = 'usage_gce';
}

console.log(
'Returned reportNamePrefix:',
usageExportLocation.reportNamePrefix
);
}

getUsageExportBucket();
// [END compute_usage_report_get]
}

main(...process.argv.slice(2));
60 changes: 60 additions & 0 deletions compute/listAllInstances.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright 2021 Google LLC
//
// 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.

/**
* Gets all instances present in a project, grouped by their zone.
*
* @param {string} projectId - ID or number of the project you want to use.
*/
function main(projectId) {
// [START compute_instances_list_all]
/**
* TODO(developer): Uncomment and replace these variables before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';

const compute = require('@google-cloud/compute');

// List all instances in the specified project.
async function listAllInstances() {
const instancesClient = new compute.InstancesClient({fallback: 'rest'});

//Use the `maxResults` parameter to limit the number of results that the API returns per response page.
const aggListRequest = instancesClient.aggregatedListAsync({
project: projectId,
maxResults: 5,
});

console.log('Instances found:');

// Despite using the `maxResults` parameter, you don't need to handle the pagination
// yourself. The returned object handles pagination automatically,
// requesting next pages as you iterate over the results.
for await (const [zone, instancesObject] of aggListRequest) {
const instances = instancesObject.instances;

if (instances && instances.length > 0) {
console.log(` ${zone}`);
for (const instance of instances) {
console.log(` - ${instance.name} (${instance.machineType})`);
}
}
}
}

listAllInstances();
// [END compute_instances_list_all]
}

main(...process.argv.slice(2));
Loading

0 comments on commit 2dd1d37

Please sign in to comment.