Skip to content

Commit

Permalink
Add Compute examples and snippets. Add them to READMEs.
Browse files Browse the repository at this point in the history
  • Loading branch information
mziccard committed Apr 28, 2016
1 parent 88fea35 commit 517e092
Show file tree
Hide file tree
Showing 8 changed files with 3,067 additions and 5 deletions.
79 changes: 79 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Java idiomatic client for [Google Cloud Platform][cloud-platform] services.
This client supports the following Google Cloud Platform services:

- [Google Cloud BigQuery] (#google-cloud-bigquery-alpha) (Alpha)
- [Google Cloud Compute] (#google-cloud-compute-alpha) (Alpha)
- [Google Cloud Datastore] (#google-cloud-datastore)
- [Google Cloud Resource Manager] (#google-cloud-resource-manager-alpha) (Alpha)
- [Google Cloud Storage] (#google-cloud-storage)
Expand Down Expand Up @@ -46,6 +47,8 @@ Example Applications

- [`BigQueryExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/bigquery/BigQueryExample.java) - A simple command line interface providing some of Cloud BigQuery's functionality
- Read more about using this application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/BigQueryExample.html).
- [`ComputeExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/ComputeExample.java) - A simple command line interface providing some of Cloud Compute's functionality
- Read more about using this application on the [`gcloud-java-examples` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/ComputeExample.html).
- [`Bookshelf`](https://github.com/GoogleCloudPlatform/getting-started-java/tree/master/bookshelf) - An App Engine app that manages a virtual bookshelf.
- This app uses `gcloud-java` to interface with Cloud Datastore and Cloud Storage. It also uses Cloud SQL, another Google Cloud Platform service.
- [`DatastoreExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/DatastoreExample.java) - A simple command line interface for the Cloud Datastore
Expand Down Expand Up @@ -161,6 +164,78 @@ if (loadJob.status().error() != null) {
}
```
Google Cloud Compute (Alpha)
----------------------
- [API Documentation][compute-api]
- [Official Documentation][cloud-compute-docs]
#### Preview
Here are two code snippets showing simple usage examples from within Compute/App Engine. Note that
you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere.
The first snippet shows how to create a snapshot from an existing disk. Complete source code can be
found at
[CreateSnapshot.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/snippets/CreateSnapshot.java).
```java
import com.google.gcloud.compute.Compute;
import com.google.gcloud.compute.ComputeOptions;
import com.google.gcloud.compute.Disk;
import com.google.gcloud.compute.DiskId;
import com.google.gcloud.compute.Operation;
import com.google.gcloud.compute.Snapshot;
Compute compute = ComputeOptions.defaultInstance().service();
DiskId diskId = DiskId.of("us-central1-a", "disk-name");
Disk disk = compute.get(diskId, Compute.DiskOption.fields());
if (disk != null) {
String snapshotName = "disk-name-snapshot";
Operation operation = disk.createSnapshot(snapshotName);
while (!operation.isDone()) {
Thread.sleep(1000L);
}
if (operation.errors() == null) {
// use snapshot
Snapshot snapshot = compute.getSnapshot("disk-name-snapshot");
}
}
```
The second snippet shows how to create a virtual machine instance. Complete source code can be found
at
[CreateInstance.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/snippets/CreateInstance.java).
```java
import com.google.gcloud.compute.AttachedDisk;
import com.google.gcloud.compute.Compute;
import com.google.gcloud.compute.ComputeOptions;
import com.google.gcloud.compute.ImageId;
import com.google.gcloud.compute.Instance;
import com.google.gcloud.compute.InstanceId;
import com.google.gcloud.compute.InstanceInfo;
import com.google.gcloud.compute.MachineTypeId;
import com.google.gcloud.compute.NetworkId;
import com.google.gcloud.compute.NetworkInterface;
import com.google.gcloud.compute.Operation;
Compute compute = ComputeOptions.defaultInstance().service();
ImageId imageId = ImageId.of("debian-cloud", "debian-8-jessie-v20160329");
NetworkId networkId = NetworkId.of("default");
AttachedDisk attachedDisk = AttachedDisk.of(AttachedDisk.CreateDiskConfiguration.of(imageId));
NetworkInterface networkInterface = NetworkInterface.of(networkId);
InstanceId instanceId = InstanceId.of("us-central1-a", "instance-name");
MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1");
Operation operation =
compute.create(InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface));
while (!operation.isDone()) {
Thread.sleep(1000L);
}
if (operation.errors() == null) {
// use instance
Instance instance = compute.get(instanceId);
}
```
Google Cloud Datastore
----------------------
Expand Down Expand Up @@ -374,3 +449,7 @@ Apache 2.0 - See [LICENSE] for more information.
[cloud-bigquery]: https://cloud.google.com/bigquery/
[cloud-bigquery-docs]: https://cloud.google.com/bigquery/docs/overview
[bigquery-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/bigquery/package-summary.html
[cloud-compute]: https://cloud.google.com/compute/
[cloud-compute-docs]: https://cloud.google.com/compute/docs/overview
[compute-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/compute/package-summary.html
166 changes: 161 additions & 5 deletions gcloud-java-compute/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ Java idiomatic client for [Google Cloud Compute] (https://cloud.google.com/compu

[![Build Status](https://travis-ci.org/GoogleCloudPlatform/gcloud-java.svg?branch=master)](https://travis-ci.org/GoogleCloudPlatform/gcloud-java)
[![Coverage Status](https://coveralls.io/repos/GoogleCloudPlatform/gcloud-java/badge.svg?branch=master)](https://coveralls.io/r/GoogleCloudPlatform/gcloud-java?branch=master)
<!-- TODO(mziccard): add in the maven shield once the artifact is pushed to maven -->
[![Maven](https://img.shields.io/maven-central/v/com.google.cloud/gcloud-java-compute.svg)]( https://img.shields.io/maven-central/v/com.google.cloud/gcloud-java-compute.svg)
[![Codacy Badge](https://api.codacy.com/project/badge/grade/9da006ad7c3a4fe1abd142e77c003917)](https://www.codacy.com/app/mziccard/gcloud-java)
[![Dependency Status](https://www.versioneye.com/user/projects/56bd8ee72a29ed002d2b0969/badge.svg?style=flat)](https://www.versioneye.com/user/projects/56bd8ee72a29ed002d2b0969)

- [Homepage] (https://googlecloudplatform.github.io/gcloud-java/)

<!-- TODO(mziccard): add link to API documentation -->
- [API Documentation] (http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/compute/package-summary.html)

> Note: This client is a work-in-progress, and may occasionally
> make backwards-incompatible changes.
Expand All @@ -27,7 +26,11 @@ If you are using SBT, add this to your dependencies

Example Application
-------------------
<!-- TODO(mziccard): add example application -->

[`ComputeExample`](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/ComputeExample.java)
is a simple command line interface that provides some of Google Cloud Compute Engine's
functionality. Read more about using the application on the
[`ComputeExample` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/compute/ComputeExample.html).

Authentication
--------------
Expand All @@ -51,7 +54,160 @@ with Google Cloud Compute using this Client Library.

Getting Started
---------------
<!-- TODO(mziccard): add code snippet -->

#### Prerequisites
For this tutorial, you will need a [Google Developers Console](https://console.developers.google.com/)
project with the Compute Engine API enabled. You will need to [enable billing](https://support.google.com/cloud/answer/6158867?hl=en)
to use Google Cloud DNS. [Follow these instructions](https://cloud.google.com/docs/authentication#preparation)
to get your project set up. You will also need to set up the local development environment by
[installing the Google Cloud SDK](https://cloud.google.com/sdk/) and running the following commands
in command line: `gcloud auth login` and `gcloud config set project [YOUR PROJECT ID]`.

#### Installation and setup
You'll need to obtain the `gcloud-java-compute` library. See the [Quickstart](#quickstart) section
to add `gcloud-java-compute` as a dependency in your code.

#### Creating an authorized service object
To make authenticated requests to Google Cloud Compute Engine, you must create a service object with
credentials. You can then make API calls by calling methods on the Compute service object. The
simplest way to authenticate is to use [Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials).
These credentials are automatically inferred from your environment, so you only need the following
code to create your service object:

```java
import com.google.gcloud.compute.Compute;
import com.google.gcloud.compute.ComputeOptions;

Compute compute = ComputeOptions.defaultInstance().service();
```

For other authentication options, see the [Authentication](https://github.com/GoogleCloudPlatform/gcloud-java#authentication)
page.

#### Creating a region IP address
An external region IP address can be associated to a Google Compute Engine instance to communicate
with instances in different regions or to communicate with the instance from ouside of Compute
Engine. In this code snippet, we will create a new external region address.

Add the following imports at the top of your file:

```java
import com.google.gcloud.compute.AddressInfo;
import com.google.gcloud.compute.Operation;
import com.google.gcloud.compute.RegionAddressId;
```

Then add the following code to create an address. Most Compute Engine calls return an `Operation`
object that can be used to wait for operation completion and to check whether operation failed or
succeeded:

```java
RegionAddressId addressId = RegionAddressId.of("us-central1", "test-address");
Operation operation = compute.create(AddressInfo.of(addressId));
while (!operation.isDone()) {
Thread.sleep(1000L);
}
operation = operation.reload();
if (operation.errors() == null) {
System.out.println("Address " + addressId + " was successfully created");
} else {
// inspect operation.errors()
throw new RuntimeException("Address creation failed");
}
```

#### Creating a persistent disk
A persistent disk can be used as primary storage for your virtual machine instances. Persistent
disks can be created empty, from a disk image or from a disk snapshot. Compute Engine offers
[publicly-available images](https://cloud.google.com/compute/docs/operating-systems/) of certain
operating systems that you can use. In this code snippet, we will create a new persistent disk from
a publicly-available image.

Add the following imports at the top of your file:

```java
import com.google.gcloud.compute.DiskInfo;
import com.google.gcloud.compute.DiskId;
import com.google.gcloud.compute.ImageDiskConfiguration;
import com.google.gcloud.compute.ImageId;
```

Then add the following code to create a disk and wait for disk creation to terminate.

```java
ImageId imageId = ImageId.of("debian-cloud", "debian-8-jessie-v20160329");
DiskId diskId = DiskId.of("us-central1-a", "test-disk");
ImageDiskConfiguration diskConfiguration = ImageDiskConfiguration.of(imageId);
DiskInfo disk = DiskInfo.of(diskId, diskConfiguration);
Operation operation = compute.create(disk);
while (!operation.isDone()) {
Thread.sleep(1000L);
}
operation = operation.reload();
if (operation.errors() == null) {
System.out.println("Disk " + diskId + " was successfully created");
} else {
// inspect operation.errors()
throw new RuntimeException("Disk creation failed");
}
```

#### Creating a virtual machine instance
An Google Compute Engine instance is a virtual machine (VM) hosted on Google's infrastructure. An
instance can be created given it's identity, a machine type, one boot disk and a network interface.
In this code snippet, we will create a virtual machine instance in the default network using as a
boot disk the disk we have just created and assigning to it the just created IP address.

Add the following imports at the top of your file:

```java
import com.google.gcloud.compute.AttachedDisk;
import com.google.gcloud.compute.AttachedDisk.PersistentDiskConfiguration;
import com.google.gcloud.compute.InstanceId;
import com.google.gcloud.compute.InstanceInfo;
import com.google.gcloud.compute.MachineTypeId;
import com.google.gcloud.compute.NetworkConfiguration;
import com.google.gcloud.compute.NetworkConfiguration.AccessConfig;
import com.google.gcloud.compute.NetworkId;
import com.google.gcloud.compute.NetworkInterface;
```

Then add the following code to create an instance and wait for instance creation to terminate.

```java
Address externalIp = compute.get(addressId);
InstanceId instanceId = InstanceId.of("us-central1-a", "test-instance");
NetworkId networkId = NetworkId.of("default");
PersistentDiskConfiguration attachConfiguration =
PersistentDiskConfiguration.builder(diskId).boot(true).build();
AttachedDisk attachedDisk = AttachedDisk.of("dev0", attachConfiguration);
NetworkInterface networkInterface = NetworkInterface.builder(networkId)
.accessConfigurations(AccessConfig.of(externalIp.address()))
.build();
MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1");
InstanceInfo instance =
InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface);
Operation operation = compute.create(instance);
while (!operation.isDone()) {
Thread.sleep(1000L);
}
operation = operation.reload();
if (operation.errors() == null) {
System.out.println("Instance " + instanceId + " was successfully created");
} else {
// inspect operation.errors()
throw new RuntimeException("Instance creation failed");
}
```

#### Complete source code

In
[CreateAddressDiskAndInstance.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/snippets/CreateAddressDiskAndInstance.java)
we put together all the code shown above into one program. The program assumes that you are
running on Compute Engine or from your own desktop. To run the example on App Engine, simply move
the code from the main method to your application's servlet class and change the print statements to
display on your webpage.

Troubleshooting
---------------
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
*/

/**
* A client to Google Cloud Compute.
*
* <p>Here's a simple usage example for using gcloud-java from App/Compute Engine. This example
* shows how to create a snapshot from an existing disk. For the complete source code see
* <a href="https://github.com/GoogleCloudPlatform/gcloud-java/tree/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/snippets/CreateSnapshot.java">
* CreateSnapshot.java</a>.
* <pre> {@code
* Compute compute = ComputeOptions.defaultInstance().service();
* DiskId diskId = DiskId.of("us-central1-a", "disk-name");
* Disk disk = compute.get(diskId, Compute.DiskOption.fields());
* if (disk != null) {
* String snapshotName = "disk-name-snapshot";
* Operation operation = disk.createSnapshot(snapshotName);
* while (!operation.isDone()) {
* Thread.sleep(1000L);
* }
* if (operation.errors() == null) {
* // use snapshot
* Snapshot snapshot = compute.getSnapshot("disk-name-snapshot");
* }
* }}</pre>
* <p>This second example shows how to create a virtual machine instance. Complete source code can
* be found at
* <a href="https://github.com/GoogleCloudPlatform/gcloud-java/tree/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/snippets/CreateInstance.java">
* CreateInstance.java</a>.
* <pre> {@code
* Compute compute = ComputeOptions.defaultInstance().service();
* ImageId imageId = ImageId.of("debian-cloud", "debian-8-jessie-v20160329");
* NetworkId networkId = NetworkId.of("default");
* AttachedDisk attachedDisk = AttachedDisk.of(AttachedDisk.CreateDiskConfiguration.of(imageId));
* NetworkInterface networkInterface = NetworkInterface.of(networkId);
* InstanceId instanceId = InstanceId.of("us-central1-a", "instance-name");
* MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1");
* Operation operation =
* compute.create(InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface));
* while (!operation.isDone()) {
* Thread.sleep(1000L);
* }
* if (operation.errors() == null) {
* // use instance
* Instance instance = compute.get(instanceId);
* }}</pre>
*
* @see <a href="https://cloud.google.com/compute/">Google Cloud Compute</a>
*/
package com.google.gcloud.compute;
12 changes: 12 additions & 0 deletions gcloud-java-examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,18 @@ To run examples from your command line:
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.bigquery.BigQueryExample" -Dexec.args="query 'select * from new_dataset_id.new_table_id'"
```
* Here's an example run of `ComputeExample`.
Before running the example, go to the [Google Developers Console][developers-console] to ensure
that Compute API is enabled.
```
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.compute.ComputeExample" -Dexec.args="create image-disk us-central1-a test-disk debian-cloud debian-8-jessie-v20160329"
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.compute.ComputeExample" -Dexec.args="create instance us-central1-a test-instance n1-standard-1 test-disk default"
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.compute.ComputeExample" -Dexec.args="add-access-config us-central1-a test-instance nic0 NAT"
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.compute.ComputeExample" -Dexec.args="delete instance us-central1-a test-instance"
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.compute.ComputeExample" -Dexec.args="delete disk us-central1-a test-disk"
```
* Here's an example run of `DatastoreExample`.
Be sure to change the placeholder project ID "your-project-id" with your own project ID. Also note that you have to enable the Google Cloud Datastore API on the [Google Developers Console][developers-console] before running the following commands.
Expand Down
Loading

0 comments on commit 517e092

Please sign in to comment.