Skip to content

Commit 517e092

Browse files
committed
Add Compute examples and snippets. Add them to READMEs.
1 parent 88fea35 commit 517e092

File tree

8 files changed

+3067
-5
lines changed

8 files changed

+3067
-5
lines changed

README.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Java idiomatic client for [Google Cloud Platform][cloud-platform] services.
1515
This client supports the following Google Cloud Platform services:
1616

1717
- [Google Cloud BigQuery] (#google-cloud-bigquery-alpha) (Alpha)
18+
- [Google Cloud Compute] (#google-cloud-compute-alpha) (Alpha)
1819
- [Google Cloud Datastore] (#google-cloud-datastore)
1920
- [Google Cloud Resource Manager] (#google-cloud-resource-manager-alpha) (Alpha)
2021
- [Google Cloud Storage] (#google-cloud-storage)
@@ -46,6 +47,8 @@ Example Applications
4647

4748
- [`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
4849
- 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).
50+
- [`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
51+
- 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).
4952
- [`Bookshelf`](https://github.com/GoogleCloudPlatform/getting-started-java/tree/master/bookshelf) - An App Engine app that manages a virtual bookshelf.
5053
- This app uses `gcloud-java` to interface with Cloud Datastore and Cloud Storage. It also uses Cloud SQL, another Google Cloud Platform service.
5154
- [`DatastoreExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/DatastoreExample.java) - A simple command line interface for the Cloud Datastore
@@ -161,6 +164,78 @@ if (loadJob.status().error() != null) {
161164
}
162165
```
163166
167+
Google Cloud Compute (Alpha)
168+
----------------------
169+
170+
- [API Documentation][compute-api]
171+
- [Official Documentation][cloud-compute-docs]
172+
173+
#### Preview
174+
175+
Here are two code snippets showing simple usage examples from within Compute/App Engine. Note that
176+
you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere.
177+
178+
The first snippet shows how to create a snapshot from an existing disk. Complete source code can be
179+
found at
180+
[CreateSnapshot.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/snippets/CreateSnapshot.java).
181+
182+
```java
183+
import com.google.gcloud.compute.Compute;
184+
import com.google.gcloud.compute.ComputeOptions;
185+
import com.google.gcloud.compute.Disk;
186+
import com.google.gcloud.compute.DiskId;
187+
import com.google.gcloud.compute.Operation;
188+
import com.google.gcloud.compute.Snapshot;
189+
190+
Compute compute = ComputeOptions.defaultInstance().service();
191+
DiskId diskId = DiskId.of("us-central1-a", "disk-name");
192+
Disk disk = compute.get(diskId, Compute.DiskOption.fields());
193+
if (disk != null) {
194+
String snapshotName = "disk-name-snapshot";
195+
Operation operation = disk.createSnapshot(snapshotName);
196+
while (!operation.isDone()) {
197+
Thread.sleep(1000L);
198+
}
199+
if (operation.errors() == null) {
200+
// use snapshot
201+
Snapshot snapshot = compute.getSnapshot("disk-name-snapshot");
202+
}
203+
}
204+
```
205+
The second snippet shows how to create a virtual machine instance. Complete source code can be found
206+
at
207+
[CreateInstance.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/snippets/CreateInstance.java).
208+
```java
209+
import com.google.gcloud.compute.AttachedDisk;
210+
import com.google.gcloud.compute.Compute;
211+
import com.google.gcloud.compute.ComputeOptions;
212+
import com.google.gcloud.compute.ImageId;
213+
import com.google.gcloud.compute.Instance;
214+
import com.google.gcloud.compute.InstanceId;
215+
import com.google.gcloud.compute.InstanceInfo;
216+
import com.google.gcloud.compute.MachineTypeId;
217+
import com.google.gcloud.compute.NetworkId;
218+
import com.google.gcloud.compute.NetworkInterface;
219+
import com.google.gcloud.compute.Operation;
220+
221+
Compute compute = ComputeOptions.defaultInstance().service();
222+
ImageId imageId = ImageId.of("debian-cloud", "debian-8-jessie-v20160329");
223+
NetworkId networkId = NetworkId.of("default");
224+
AttachedDisk attachedDisk = AttachedDisk.of(AttachedDisk.CreateDiskConfiguration.of(imageId));
225+
NetworkInterface networkInterface = NetworkInterface.of(networkId);
226+
InstanceId instanceId = InstanceId.of("us-central1-a", "instance-name");
227+
MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1");
228+
Operation operation =
229+
compute.create(InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface));
230+
while (!operation.isDone()) {
231+
Thread.sleep(1000L);
232+
}
233+
if (operation.errors() == null) {
234+
// use instance
235+
Instance instance = compute.get(instanceId);
236+
}
237+
```
238+
164239
Google Cloud Datastore
165240
----------------------
166241
@@ -374,3 +449,7 @@ Apache 2.0 - See [LICENSE] for more information.
374449
[cloud-bigquery]: https://cloud.google.com/bigquery/
375450
[cloud-bigquery-docs]: https://cloud.google.com/bigquery/docs/overview
376451
[bigquery-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/bigquery/package-summary.html
452+
453+
[cloud-compute]: https://cloud.google.com/compute/
454+
[cloud-compute-docs]: https://cloud.google.com/compute/docs/overview
455+
[compute-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/compute/package-summary.html

gcloud-java-compute/README.md

Lines changed: 161 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,12 @@ Java idiomatic client for [Google Cloud Compute] (https://cloud.google.com/compu
55

66
[![Build Status](https://travis-ci.org/GoogleCloudPlatform/gcloud-java.svg?branch=master)](https://travis-ci.org/GoogleCloudPlatform/gcloud-java)
77
[![Coverage Status](https://coveralls.io/repos/GoogleCloudPlatform/gcloud-java/badge.svg?branch=master)](https://coveralls.io/r/GoogleCloudPlatform/gcloud-java?branch=master)
8-
<!-- TODO(mziccard): add in the maven shield once the artifact is pushed to maven -->
8+
[![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)
99
[![Codacy Badge](https://api.codacy.com/project/badge/grade/9da006ad7c3a4fe1abd142e77c003917)](https://www.codacy.com/app/mziccard/gcloud-java)
1010
[![Dependency Status](https://www.versioneye.com/user/projects/56bd8ee72a29ed002d2b0969/badge.svg?style=flat)](https://www.versioneye.com/user/projects/56bd8ee72a29ed002d2b0969)
1111

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

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

2827
Example Application
2928
-------------------
30-
<!-- TODO(mziccard): add example application -->
29+
30+
[`ComputeExample`](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/ComputeExample.java)
31+
is a simple command line interface that provides some of Google Cloud Compute Engine's
32+
functionality. Read more about using the application on the
33+
[`ComputeExample` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/compute/ComputeExample.html).
3134

3235
Authentication
3336
--------------
@@ -51,7 +54,160 @@ with Google Cloud Compute using this Client Library.
5154

5255
Getting Started
5356
---------------
54-
<!-- TODO(mziccard): add code snippet -->
57+
58+
#### Prerequisites
59+
For this tutorial, you will need a [Google Developers Console](https://console.developers.google.com/)
60+
project with the Compute Engine API enabled. You will need to [enable billing](https://support.google.com/cloud/answer/6158867?hl=en)
61+
to use Google Cloud DNS. [Follow these instructions](https://cloud.google.com/docs/authentication#preparation)
62+
to get your project set up. You will also need to set up the local development environment by
63+
[installing the Google Cloud SDK](https://cloud.google.com/sdk/) and running the following commands
64+
in command line: `gcloud auth login` and `gcloud config set project [YOUR PROJECT ID]`.
65+
66+
#### Installation and setup
67+
You'll need to obtain the `gcloud-java-compute` library. See the [Quickstart](#quickstart) section
68+
to add `gcloud-java-compute` as a dependency in your code.
69+
70+
#### Creating an authorized service object
71+
To make authenticated requests to Google Cloud Compute Engine, you must create a service object with
72+
credentials. You can then make API calls by calling methods on the Compute service object. The
73+
simplest way to authenticate is to use [Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials).
74+
These credentials are automatically inferred from your environment, so you only need the following
75+
code to create your service object:
76+
77+
```java
78+
import com.google.gcloud.compute.Compute;
79+
import com.google.gcloud.compute.ComputeOptions;
80+
81+
Compute compute = ComputeOptions.defaultInstance().service();
82+
```
83+
84+
For other authentication options, see the [Authentication](https://github.com/GoogleCloudPlatform/gcloud-java#authentication)
85+
page.
86+
87+
#### Creating a region IP address
88+
An external region IP address can be associated to a Google Compute Engine instance to communicate
89+
with instances in different regions or to communicate with the instance from ouside of Compute
90+
Engine. In this code snippet, we will create a new external region address.
91+
92+
Add the following imports at the top of your file:
93+
94+
```java
95+
import com.google.gcloud.compute.AddressInfo;
96+
import com.google.gcloud.compute.Operation;
97+
import com.google.gcloud.compute.RegionAddressId;
98+
```
99+
100+
Then add the following code to create an address. Most Compute Engine calls return an `Operation`
101+
object that can be used to wait for operation completion and to check whether operation failed or
102+
succeeded:
103+
104+
```java
105+
RegionAddressId addressId = RegionAddressId.of("us-central1", "test-address");
106+
Operation operation = compute.create(AddressInfo.of(addressId));
107+
while (!operation.isDone()) {
108+
Thread.sleep(1000L);
109+
}
110+
operation = operation.reload();
111+
if (operation.errors() == null) {
112+
System.out.println("Address " + addressId + " was successfully created");
113+
} else {
114+
// inspect operation.errors()
115+
throw new RuntimeException("Address creation failed");
116+
}
117+
```
118+
119+
#### Creating a persistent disk
120+
A persistent disk can be used as primary storage for your virtual machine instances. Persistent
121+
disks can be created empty, from a disk image or from a disk snapshot. Compute Engine offers
122+
[publicly-available images](https://cloud.google.com/compute/docs/operating-systems/) of certain
123+
operating systems that you can use. In this code snippet, we will create a new persistent disk from
124+
a publicly-available image.
125+
126+
Add the following imports at the top of your file:
127+
128+
```java
129+
import com.google.gcloud.compute.DiskInfo;
130+
import com.google.gcloud.compute.DiskId;
131+
import com.google.gcloud.compute.ImageDiskConfiguration;
132+
import com.google.gcloud.compute.ImageId;
133+
```
134+
135+
Then add the following code to create a disk and wait for disk creation to terminate.
136+
137+
```java
138+
ImageId imageId = ImageId.of("debian-cloud", "debian-8-jessie-v20160329");
139+
DiskId diskId = DiskId.of("us-central1-a", "test-disk");
140+
ImageDiskConfiguration diskConfiguration = ImageDiskConfiguration.of(imageId);
141+
DiskInfo disk = DiskInfo.of(diskId, diskConfiguration);
142+
Operation operation = compute.create(disk);
143+
while (!operation.isDone()) {
144+
Thread.sleep(1000L);
145+
}
146+
operation = operation.reload();
147+
if (operation.errors() == null) {
148+
System.out.println("Disk " + diskId + " was successfully created");
149+
} else {
150+
// inspect operation.errors()
151+
throw new RuntimeException("Disk creation failed");
152+
}
153+
```
154+
155+
#### Creating a virtual machine instance
156+
An Google Compute Engine instance is a virtual machine (VM) hosted on Google's infrastructure. An
157+
instance can be created given it's identity, a machine type, one boot disk and a network interface.
158+
In this code snippet, we will create a virtual machine instance in the default network using as a
159+
boot disk the disk we have just created and assigning to it the just created IP address.
160+
161+
Add the following imports at the top of your file:
162+
163+
```java
164+
import com.google.gcloud.compute.AttachedDisk;
165+
import com.google.gcloud.compute.AttachedDisk.PersistentDiskConfiguration;
166+
import com.google.gcloud.compute.InstanceId;
167+
import com.google.gcloud.compute.InstanceInfo;
168+
import com.google.gcloud.compute.MachineTypeId;
169+
import com.google.gcloud.compute.NetworkConfiguration;
170+
import com.google.gcloud.compute.NetworkConfiguration.AccessConfig;
171+
import com.google.gcloud.compute.NetworkId;
172+
import com.google.gcloud.compute.NetworkInterface;
173+
```
174+
175+
Then add the following code to create an instance and wait for instance creation to terminate.
176+
177+
```java
178+
Address externalIp = compute.get(addressId);
179+
InstanceId instanceId = InstanceId.of("us-central1-a", "test-instance");
180+
NetworkId networkId = NetworkId.of("default");
181+
PersistentDiskConfiguration attachConfiguration =
182+
PersistentDiskConfiguration.builder(diskId).boot(true).build();
183+
AttachedDisk attachedDisk = AttachedDisk.of("dev0", attachConfiguration);
184+
NetworkInterface networkInterface = NetworkInterface.builder(networkId)
185+
.accessConfigurations(AccessConfig.of(externalIp.address()))
186+
.build();
187+
MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1");
188+
InstanceInfo instance =
189+
InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface);
190+
Operation operation = compute.create(instance);
191+
while (!operation.isDone()) {
192+
Thread.sleep(1000L);
193+
}
194+
operation = operation.reload();
195+
if (operation.errors() == null) {
196+
System.out.println("Instance " + instanceId + " was successfully created");
197+
} else {
198+
// inspect operation.errors()
199+
throw new RuntimeException("Instance creation failed");
200+
}
201+
```
202+
203+
#### Complete source code
204+
205+
In
206+
[CreateAddressDiskAndInstance.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/snippets/CreateAddressDiskAndInstance.java)
207+
we put together all the code shown above into one program. The program assumes that you are
208+
running on Compute Engine or from your own desktop. To run the example on App Engine, simply move
209+
the code from the main method to your application's servlet class and change the print statements to
210+
display on your webpage.
55211

56212
Troubleshooting
57213
---------------
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
* Copyright 2016 Google Inc. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
/**
18+
* A client to Google Cloud Compute.
19+
*
20+
* <p>Here's a simple usage example for using gcloud-java from App/Compute Engine. This example
21+
* shows how to create a snapshot from an existing disk. For the complete source code see
22+
* <a href="https://github.com/GoogleCloudPlatform/gcloud-java/tree/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/snippets/CreateSnapshot.java">
23+
* CreateSnapshot.java</a>.
24+
* <pre> {@code
25+
* Compute compute = ComputeOptions.defaultInstance().service();
26+
* DiskId diskId = DiskId.of("us-central1-a", "disk-name");
27+
* Disk disk = compute.get(diskId, Compute.DiskOption.fields());
28+
* if (disk != null) {
29+
* String snapshotName = "disk-name-snapshot";
30+
* Operation operation = disk.createSnapshot(snapshotName);
31+
* while (!operation.isDone()) {
32+
* Thread.sleep(1000L);
33+
* }
34+
* if (operation.errors() == null) {
35+
* // use snapshot
36+
* Snapshot snapshot = compute.getSnapshot("disk-name-snapshot");
37+
* }
38+
* }}</pre>
39+
* <p>This second example shows how to create a virtual machine instance. Complete source code can
40+
* be found at
41+
* <a href="https://github.com/GoogleCloudPlatform/gcloud-java/tree/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/compute/snippets/CreateInstance.java">
42+
* CreateInstance.java</a>.
43+
* <pre> {@code
44+
* Compute compute = ComputeOptions.defaultInstance().service();
45+
* ImageId imageId = ImageId.of("debian-cloud", "debian-8-jessie-v20160329");
46+
* NetworkId networkId = NetworkId.of("default");
47+
* AttachedDisk attachedDisk = AttachedDisk.of(AttachedDisk.CreateDiskConfiguration.of(imageId));
48+
* NetworkInterface networkInterface = NetworkInterface.of(networkId);
49+
* InstanceId instanceId = InstanceId.of("us-central1-a", "instance-name");
50+
* MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1");
51+
* Operation operation =
52+
* compute.create(InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface));
53+
* while (!operation.isDone()) {
54+
* Thread.sleep(1000L);
55+
* }
56+
* if (operation.errors() == null) {
57+
* // use instance
58+
* Instance instance = compute.get(instanceId);
59+
* }}</pre>
60+
*
61+
* @see <a href="https://cloud.google.com/compute/">Google Cloud Compute</a>
62+
*/
63+
package com.google.gcloud.compute;

gcloud-java-examples/README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,18 @@ To run examples from your command line:
6262
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.bigquery.BigQueryExample" -Dexec.args="query 'select * from new_dataset_id.new_table_id'"
6363
```
6464
65+
* Here's an example run of `ComputeExample`.
66+
67+
Before running the example, go to the [Google Developers Console][developers-console] to ensure
68+
that Compute API is enabled.
69+
```
70+
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"
71+
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"
72+
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.compute.ComputeExample" -Dexec.args="add-access-config us-central1-a test-instance nic0 NAT"
73+
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.compute.ComputeExample" -Dexec.args="delete instance us-central1-a test-instance"
74+
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.compute.ComputeExample" -Dexec.args="delete disk us-central1-a test-disk"
75+
```
76+
6577
* Here's an example run of `DatastoreExample`.
6678
6779
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.

0 commit comments

Comments
 (0)