Skip to content

Commit 78a94d6

Browse files
authored
docs(compute-samples): adding machine type update and regional disk samples (GoogleCloudPlatform#7707)
* docs(compute-samples): adding region disk samples * lint fix * refactor diskBuilder setting * fix acc to review comments * remove matcher and simplify * fix zone in test
1 parent 9203e00 commit 78a94d6

File tree

9 files changed

+453
-17
lines changed

9 files changed

+453
-17
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* Copyright 2023 Google LLC
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+
package compute;
18+
19+
// [START compute_change_machine_type]
20+
21+
import com.google.cloud.compute.v1.Instance;
22+
import com.google.cloud.compute.v1.Instance.Status;
23+
import com.google.cloud.compute.v1.InstancesClient;
24+
import com.google.cloud.compute.v1.InstancesSetMachineTypeRequest;
25+
import com.google.cloud.compute.v1.Operation;
26+
import java.io.IOException;
27+
import java.util.concurrent.ExecutionException;
28+
import java.util.concurrent.TimeUnit;
29+
import java.util.concurrent.TimeoutException;
30+
31+
public class ChangeInstanceMachineType {
32+
33+
public static void main(String[] args)
34+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
35+
// TODO(developer): Replace these variables before running the sample.
36+
// Project ID or project number of the Cloud project you want to use.
37+
String projectId = "your-project-id";
38+
// Name of the zone your instance belongs to.
39+
String zone = "zone-name";
40+
// Name of the VM you want to modify.
41+
String instanceName = "instance-name";
42+
// The new machine type you want to use for the VM.
43+
// For example: "e2-standard-8", "e2-custom-4-2048" or "m1-ultramem-40"
44+
// More about machine types: https://cloud.google.com/compute/docs/machine-resource
45+
String newMachineType = "e2-standard-8";
46+
changeMachineType(projectId, zone, instanceName, newMachineType);
47+
}
48+
49+
// Changes the machine type of VM.
50+
// The VM needs to be in the 'TERMINATED' state for this operation to be successful.
51+
public static void changeMachineType(String projectId, String zone, String instanceName,
52+
String newMachineType)
53+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
54+
// Initialize client that will be used to send requests. This client only needs to be created
55+
// once, and can be reused for multiple requests. After completing all of your requests, call
56+
// the `instancesClient.close()` method on the client to safely
57+
// clean up any remaining background resources.
58+
try (InstancesClient instancesClient = InstancesClient.create()) {
59+
60+
Instance instance = instancesClient.get(projectId, zone, instanceName);
61+
if (!instance.getStatus().equals(Status.TERMINATED.name())) {
62+
throw new Error(String.format(
63+
"Only machines in TERMINATED state can have their machine type changed. "
64+
+ "%s is in %s state.", instance.getName(), instance.getStatus()));
65+
}
66+
67+
InstancesSetMachineTypeRequest machineTypeRequest =
68+
InstancesSetMachineTypeRequest.newBuilder()
69+
.setMachineType(String.format("projects/%s/zones/%s/machineTypes/%s",
70+
projectId, zone, newMachineType))
71+
.build();
72+
73+
Operation response = instancesClient
74+
.setMachineTypeAsync(projectId, zone, instanceName, machineTypeRequest)
75+
.get(3, TimeUnit.MINUTES);
76+
77+
if (response.hasError()) {
78+
System.out.println("Machine type update failed! " + response);
79+
return;
80+
}
81+
System.out.println("Machine type update - operation status: " + response.getStatus());
82+
}
83+
}
84+
}
85+
// [END compute_change_machine_type]
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/*
2+
* Copyright 2023 Google LLC
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+
package compute.disks;
18+
19+
// [START compute_regional_disk_attach]
20+
// [START compute_disk_attach]
21+
22+
import com.google.cloud.compute.v1.AttachDiskInstanceRequest;
23+
import com.google.cloud.compute.v1.AttachedDisk;
24+
import com.google.cloud.compute.v1.InstancesClient;
25+
import com.google.cloud.compute.v1.Operation;
26+
import java.io.IOException;
27+
import java.util.concurrent.ExecutionException;
28+
import java.util.concurrent.TimeUnit;
29+
import java.util.concurrent.TimeoutException;
30+
31+
public class AttachDisk {
32+
33+
public static void main(String[] args)
34+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
35+
// TODO(developer): Replace these variables before running the sample.
36+
// Project ID or project number of the Cloud project you want to use.
37+
String projectId = "your-project-id";
38+
39+
// Name of the zone in which the instance you want to use resides.
40+
String zone = "zone-name";
41+
42+
// Name of the compute instance you want to attach a disk to.
43+
String instanceName = "instance-name";
44+
45+
// Full or partial URL of a persistent disk that you want to attach. This can be either
46+
// be a regional or zonal disk.
47+
// Valid formats:
48+
// * https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/disks/{disk_name}
49+
// * /projects/{project}/zones/{zone}/disks/{disk_name}
50+
// * /projects/{project}/regions/{region}/disks/{disk_name}
51+
String diskLink = String.format("/projects/%s/zones/%s/disks/%s",
52+
"project", "zone", "disk_name");
53+
54+
// Specifies in what mode the disk will be attached to the instance. Available options are
55+
// `READ_ONLY` and `READ_WRITE`. Disk in `READ_ONLY` mode can be attached to
56+
// multiple instances at once.
57+
String mode = "READ_ONLY";
58+
59+
attachDisk(projectId, zone, instanceName, diskLink, mode);
60+
}
61+
62+
// Attaches a non-boot persistent disk to a specified compute instance.
63+
// The disk might be zonal or regional.
64+
// You need following permissions to execute this action:
65+
// https://cloud.google.com/compute/docs/disks/regional-persistent-disk#expandable-1
66+
public static void attachDisk(String projectId, String zone, String instanceName, String diskLink,
67+
String mode)
68+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
69+
// Initialize client that will be used to send requests. This client only needs to be created
70+
// once, and can be reused for multiple requests. After completing all of your requests, call
71+
// the `instancesClient.close()` method on the client to safely
72+
// clean up any remaining background resources.
73+
try (InstancesClient instancesClient = InstancesClient.create()) {
74+
75+
AttachDiskInstanceRequest attachDiskInstanceRequest = AttachDiskInstanceRequest.newBuilder()
76+
.setProject(projectId)
77+
.setZone(zone)
78+
.setInstance(instanceName)
79+
.setAttachedDiskResource(AttachedDisk.newBuilder()
80+
.setSource(diskLink)
81+
.setMode(mode)
82+
.build())
83+
.build();
84+
85+
Operation response = instancesClient.attachDiskAsync(attachDiskInstanceRequest)
86+
.get(3, TimeUnit.MINUTES);
87+
88+
if (response.hasError()) {
89+
System.out.println("Attach disk failed! " + response);
90+
return;
91+
}
92+
System.out.println("Attach disk - operation status: " + response.getStatus());
93+
}
94+
}
95+
}
96+
// [END compute_regional_disk_attach]
97+
// [END compute_disk_attach]

compute/cloud-client/src/main/java/compute/disks/RegionalCreateFromSource.java

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import java.io.IOException;
2323
import java.util.ArrayList;
2424
import java.util.List;
25+
import java.util.Optional;
2526
import java.util.concurrent.ExecutionException;
2627
import java.util.concurrent.TimeUnit;
2728
import java.util.concurrent.TimeoutException;
@@ -65,14 +66,14 @@ public static void main(String[] args)
6566
String snapshotLink = String.format("projects/%s/global/snapshots/%s", "PROJECT_NAME",
6667
"SNAPSHOT_NAME");
6768

68-
createRegionalDisk(project, region, replicaZones, diskName, diskType, diskSizeGb, diskLink,
69-
snapshotLink);
69+
createRegionalDisk(project, region, replicaZones, diskName, diskType, diskSizeGb,
70+
Optional.ofNullable(diskLink), Optional.ofNullable(snapshotLink));
7071
}
7172

7273
// Creates a regional disk from an existing zonal disk in a given project.
7374
public static void createRegionalDisk(
7475
String project, String region, List<String> replicaZones, String diskName, String diskType,
75-
int diskSizeGb, String diskLink, String snapshotLink)
76+
int diskSizeGb, Optional<String> diskLink, Optional<String> snapshotLink)
7677
throws IOException, ExecutionException, InterruptedException, TimeoutException {
7778
// Initialize client that will be used to send requests. This client only needs to be created
7879
// once, and can be reused for multiple requests. After completing all of your requests, call
@@ -88,14 +89,10 @@ public static void createRegionalDisk(
8889
.setRegion(region);
8990

9091
// Set source disk if diskLink is not empty.
91-
if (!diskLink.isEmpty()) {
92-
diskBuilder.setSourceDisk(diskLink);
93-
}
92+
diskLink.ifPresent(diskBuilder::setSourceDisk);
9493

9594
// Set source snapshot if the snapshot link is not empty.
96-
if (!snapshotLink.isEmpty()) {
97-
diskBuilder.setSourceSnapshot(snapshotLink);
98-
}
95+
snapshotLink.ifPresent(diskBuilder::setSourceSnapshot);
9996

10097
// Wait for the operation to complete.
10198
Operation operation = regionDisksClient.insertAsync(project, region, diskBuilder.build())
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
* Copyright 2023 Google LLC
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+
package compute.disks;
18+
19+
// [START compute_disk_resize]
20+
21+
import com.google.cloud.compute.v1.DisksClient;
22+
import com.google.cloud.compute.v1.DisksResizeRequest;
23+
import com.google.cloud.compute.v1.Operation;
24+
import com.google.cloud.compute.v1.ResizeDiskRequest;
25+
import java.io.IOException;
26+
import java.util.concurrent.ExecutionException;
27+
import java.util.concurrent.TimeUnit;
28+
import java.util.concurrent.TimeoutException;
29+
30+
public class ResizeDisk {
31+
32+
public static void main(String[] args)
33+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
34+
// TODO(developer): Replace these variables before running the sample.
35+
// Project ID or project number of the Cloud project you want to use.
36+
String projectId = "your-project-id";
37+
38+
// Zone of the disk to be resized.
39+
String diskZone = "us-central1-a";
40+
41+
// Name of the disk that you want to resize.
42+
String diskName = "DISK_NAME";
43+
44+
// The new size you want to set for the disk in gigabytes.
45+
int newSizeGb = 23;
46+
47+
resizeDisk(projectId, diskZone, diskName, newSizeGb);
48+
}
49+
50+
// Resizes a persistent disk to a specified size in GB. After you resize the disk, you must
51+
// also resize the file system so that the operating system can access the additional space.
52+
public static void resizeDisk(String projectId, String diskZone, String diskName, int newSizeGb)
53+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
54+
// Initialize client that will be used to send requests. This client only needs to be created
55+
// once, and can be reused for multiple requests. After completing all of your requests, call
56+
// the `disksClient.close()` method on the client to safely
57+
// clean up any remaining background resources.
58+
try (DisksClient disksClient = DisksClient.create()) {
59+
60+
ResizeDiskRequest resizeDiskRequest = ResizeDiskRequest.newBuilder()
61+
.setZone(diskZone)
62+
.setDisksResizeRequestResource(DisksResizeRequest.newBuilder()
63+
.setSizeGb(newSizeGb)
64+
.build())
65+
.setDisk(diskName)
66+
.setProject(projectId)
67+
.build();
68+
69+
Operation response = disksClient.resizeAsync(resizeDiskRequest)
70+
.get(3, TimeUnit.MINUTES);
71+
72+
if (response.hasError()) {
73+
System.out.println("Resize disk failed! " + response);
74+
return;
75+
}
76+
System.out.println("Resize disk - operation status: " + response.getStatus());
77+
}
78+
}
79+
}
80+
// [END compute_disk_resize]
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/*
2+
* Copyright 2023 Google LLC
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+
package compute.disks;
18+
19+
// [START compute_regional_disk_resize]
20+
21+
import com.google.cloud.compute.v1.Operation;
22+
import com.google.cloud.compute.v1.RegionDisksClient;
23+
import com.google.cloud.compute.v1.RegionDisksResizeRequest;
24+
import com.google.cloud.compute.v1.ResizeRegionDiskRequest;
25+
import java.io.IOException;
26+
import java.util.concurrent.ExecutionException;
27+
import java.util.concurrent.TimeUnit;
28+
import java.util.concurrent.TimeoutException;
29+
30+
public class ResizeRegionalDisk {
31+
32+
public static void main(String[] args)
33+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
34+
// TODO(developer): Replace these variables before running the sample.
35+
// Project ID or project number of the Cloud project you want to use.
36+
String projectId = "your-project-id";
37+
38+
// Region of the disk to be resized.
39+
String diskRegion = "us-central1";
40+
41+
// Name of the disk that you want to resize.
42+
String diskName = "DISK_NAME";
43+
44+
// The new size you want to set for the disk in gigabytes.
45+
int newSizeGb = 23;
46+
47+
resizeRegionalDisk(projectId, diskRegion, diskName, newSizeGb);
48+
}
49+
50+
// Resizes a regional persistent disk to a specified size in GB. After you resize the disk, you
51+
// must also resize the file system so that the operating system can access the additional space.
52+
public static void resizeRegionalDisk(String projectId, String diskRegion, String diskName,
53+
int newSizeGb)
54+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
55+
// Initialize client that will be used to send requests. This client only needs to be created
56+
// once, and can be reused for multiple requests. After completing all of your requests, call
57+
// the `regionDisksClient.close()` method on the client to safely
58+
// clean up any remaining background resources.
59+
try (RegionDisksClient regionDisksClient = RegionDisksClient.create()) {
60+
61+
ResizeRegionDiskRequest resizeRegionDiskRequest = ResizeRegionDiskRequest.newBuilder()
62+
.setRegion(diskRegion)
63+
.setRegionDisksResizeRequestResource(RegionDisksResizeRequest.newBuilder()
64+
.setSizeGb(newSizeGb)
65+
.build())
66+
.setDisk(diskName)
67+
.setProject(projectId)
68+
.build();
69+
70+
Operation response = regionDisksClient.resizeAsync(resizeRegionDiskRequest)
71+
.get(3, TimeUnit.MINUTES);
72+
73+
if (response.hasError()) {
74+
System.out.println("Resize region disk failed! " + response);
75+
return;
76+
}
77+
System.out.println("Resize region disk - operation status: " + response.getStatus());
78+
}
79+
}
80+
}
81+
// [END compute_regional_disk_resize]

0 commit comments

Comments
 (0)