Skip to content

Commit f969df5

Browse files
authored
feat: Compute Engine sample to present default values behaviour (GoogleCloudPlatform#1383)
Compute Engine sample showcasing how to set usage reports bucket which presents the default values behaviour.
1 parent 0b0d5dc commit f969df5

File tree

5 files changed

+250
-1
lines changed

5 files changed

+250
-1
lines changed

CODEOWNERS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,6 @@
3030
/texttospeech/ @bshaffer
3131
/vision/ @bshaffer
3232
/video/ @bshaffer
33+
34+
# Compute samples owned by Remik
35+
/compute/cloud-client/ @rsamborski
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
{
22
"require": {
3-
"google/cloud-compute": "^0.3.0"
3+
"google/cloud-compute": "^0.3.1",
4+
"google/cloud-storage": "^1.23"
45
}
56
}
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
2+
/**
3+
* Copyright 2021 Google Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
/**
19+
* For instructions on how to run the full sample:
20+
*
21+
* @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/compute/cloud-client/README.md
22+
*/
23+
24+
namespace Google\Cloud\Samples\Compute;
25+
26+
# [START compute_instances_verify_default_value]
27+
# [START compute_usage_report_set]
28+
# [START compute_usage_report_get]
29+
# [START compute_usage_report_disable]
30+
use Google\Cloud\Compute\V1\ProjectsClient;
31+
use Google\Cloud\Compute\V1\UsageExportLocation;
32+
33+
# [END compute_usage_report_disable]
34+
# [END compute_usage_report_get]
35+
# [END compute_usage_report_set]
36+
37+
# [START compute_usage_report_set]
38+
/**
39+
* Set Compute Engine usage export bucket for the Cloud Project.
40+
* This sample presents how to interpret the default value for the report name prefix parameter.
41+
* Example:
42+
* ```
43+
* set_usage_export_bucket($projectId, $bucketName, $reportPrefixName);
44+
* ```
45+
*
46+
* @param string $projectId Your Google Cloud project ID.
47+
* @param string $bucketName Google Cloud Storage Bucket used to store Compute Engine usage reports.
48+
* An existing Google Cloud Storage bucket is required.
49+
* @param string $reportPrefixName Prefix of the usage report name which defaults to an empty string
50+
* to showcase default values behavior.
51+
*
52+
* @return \Google\Cloud\Compute\V1\Operation
53+
*
54+
* @throws \Google\ApiCore\ApiException if the remote call fails.
55+
*/
56+
function set_usage_export_bucket(
57+
string $projectId,
58+
string $bucketName,
59+
string $reportPrefixName = ''
60+
) {
61+
// Initialize UsageExportLocation object with provided bucket name and no report name prefix.
62+
$usageExportLocation = new UsageExportLocation(array(
63+
"bucket_name" => $bucketName,
64+
"report_name_prefix" => $reportPrefixName
65+
));
66+
67+
if (strlen($reportPrefixName) == 0) {
68+
// Sending empty value for report_name_prefix results in the next usage report
69+
// being generated with the default prefix value "usage_gce".
70+
// See https://cloud.google.com/compute/docs/reference/rest/v1/projects/setUsageExportBucket
71+
print("Setting report_name_prefix to empty value causes the " .
72+
"report to have the default value of `usage_gce`.");
73+
}
74+
75+
// Set the usage export location.
76+
$projectsClient = new ProjectsClient();
77+
return $projectsClient->setUsageExportBucket($projectId, $usageExportLocation);
78+
}
79+
# [END compute_usage_report_set]
80+
81+
# [START compute_usage_report_get]
82+
/**
83+
* Retrieve Compute Engine usage export bucket for the Cloud Project.
84+
* Replaces the empty value returned by the API with the default value used
85+
* to generate report file names.
86+
* Example:
87+
* ```
88+
* get_usage_export_bucket($projectId);
89+
* ```
90+
*
91+
* @param string $projectId Your Google Cloud project ID.
92+
* @return UsageExportLocation|null UsageExportLocation object describing the current usage
93+
* export settings for project $projectId.
94+
*
95+
* @throws \Google\ApiCore\ApiException if the remote call fails.
96+
*/
97+
function get_usage_export_bucket(string $projectId)
98+
{
99+
// Get the usage setting for the project from the server.
100+
$projectsClient = new ProjectsClient();
101+
$projectResponse = $projectsClient->get($projectId);
102+
103+
// Construct proper values to be displayed, taking into account default values behavior.
104+
if ($projectResponse->hasUsageExportLocation()) {
105+
$responseUsageExportLocation = $projectResponse->getUsageExportLocation();
106+
107+
// Verify that the server explicitly sent the optional field.
108+
if ($responseUsageExportLocation->hasReportNamePrefix()) {
109+
if ($responseUsageExportLocation->getReportNamePrefix() == '') {
110+
// Although the server explicitly sent the empty string value, the next usage
111+
// report generated with these settings still has the default prefix value "usage_gce".
112+
// See https://cloud.google.com/compute/docs/reference/rest/v1/projects/get
113+
print("Report name prefix not set, replacing with default value of `usage_gce`.");
114+
$responseUsageExportLocation->setReportNamePrefix('usage_gce');
115+
}
116+
}
117+
118+
return $responseUsageExportLocation;
119+
} else {
120+
// The usage reports are disabled.
121+
return null;
122+
}
123+
}
124+
# [END compute_usage_report_get]
125+
# [END compute_instances_verify_default_value]
126+
127+
# [START compute_usage_report_disable]
128+
/**
129+
* Disable Compute Engine usage export bucket for the Cloud Project.
130+
* Example:
131+
* ```
132+
* disable_usage_export_bucket($projectId);
133+
* ```
134+
*
135+
* @param string $projectId Your Google Cloud project ID.
136+
*
137+
* @return \Google\Cloud\Compute\V1\Operation
138+
*
139+
* @throws \Google\ApiCore\ApiException if the remote call fails.
140+
*/
141+
function disable_usage_export_bucket(string $projectId)
142+
{
143+
// Disable the usage export location by sending null as usageExportLocationResource.
144+
$projectsClient = new ProjectsClient();
145+
return $projectsClient->setUsageExportBucket($projectId, null);
146+
}
147+
# [END compute_usage_report_disable]
148+
149+
require_once __DIR__ . '/../../../../testing/sample_helpers.php';
150+
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

compute/cloud-client/instances/test/instancesTest.php

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717

1818
namespace Google\Cloud\Samples\Compute;
1919

20+
use Google\Cloud\Compute\V1\Operation;
21+
use Google\Cloud\Compute\V1\GlobalOperationsClient;
22+
use Google\Cloud\Storage\StorageClient;
2023
use Google\Cloud\TestUtils\TestTrait;
2124
use PHPUnit\Framework\TestCase;
2225

@@ -25,12 +28,30 @@ class instancesTest extends TestCase
2528
use TestTrait;
2629

2730
private static $instanceName;
31+
private static $bucketName;
32+
private static $bucket;
2833

2934
private const DEFAULT_ZONE = 'us-central1-a';
3035

3136
public static function setUpBeforeClass(): void
3237
{
3338
self::$instanceName = sprintf('test-compute-instance-%s', rand());
39+
40+
// Generate bucket name
41+
self::$bucketName = sprintf('test-compute-usage-export-bucket-%s', rand());
42+
43+
// Setup new bucket for UsageReports
44+
$storage = new StorageClient([
45+
'projectId' => self::$projectId
46+
]);
47+
48+
self::$bucket = $storage->createBucket(self::$bucketName);
49+
}
50+
51+
public static function tearDownAfterClass(): void
52+
{
53+
// Remove the bucket
54+
self::$bucket->delete();
3455
}
3556

3657
public function testCreateInstance()
@@ -79,4 +100,77 @@ public function testDeleteInstance()
79100
]);
80101
$this->assertStringContainsString('Deleted instance ' . self::$instanceName, $output);
81102
}
103+
104+
public function testSetUsageExportBucketDefaultPrefix()
105+
{
106+
$output = $this->runFunctionSnippet('set_usage_export_bucket', [
107+
'projectId' => self::$projectId,
108+
'bucketName' => self::$bucketName
109+
]);
110+
ob_start();
111+
$operation = set_usage_export_bucket(self::$projectId, self::$bucketName);
112+
$this->assertStringContainsString('default value of `usage_gce`', ob_get_clean());
113+
114+
// Wait for the settings to take place
115+
if ($operation->getStatus() === Operation\Status::RUNNING) {
116+
// Wait until operation completes
117+
$operationClient = new GlobalOperationsClient();
118+
$operationClient->wait($operation->getName(), self::$projectId);
119+
}
120+
121+
ob_start();
122+
$usageExportLocation = get_usage_export_bucket(self::$projectId);
123+
$this->assertStringContainsString('default value of `usage_gce`', ob_get_clean());
124+
$this->assertEquals($usageExportLocation->getBucketName(), self::$bucketName);
125+
$this->assertEquals($usageExportLocation->getReportNamePrefix(), 'usage_gce');
126+
127+
// Disable usage exports
128+
$operation = disable_usage_export_bucket(self::$projectId);
129+
130+
// Wait for the settings to take place
131+
if ($operation->getStatus() === Operation\Status::RUNNING) {
132+
// Wait until operation completes
133+
$operationClient = new GlobalOperationsClient();
134+
$operationClient->wait($operation->getName(), self::$projectId);
135+
}
136+
137+
$usageExportLocation = get_usage_export_bucket(self::$projectId);
138+
$this->assertNull($usageExportLocation);
139+
}
140+
141+
public function testSetUsageExportBucketCustomPrefix()
142+
{
143+
// Set custom prefix
144+
$customPrefix = "my-custom-prefix";
145+
146+
ob_start();
147+
$operation = set_usage_export_bucket(self::$projectId, self::$bucketName, $customPrefix);
148+
$this->assertStringNotContainsString('default value of `usage_gce`', ob_get_clean());
149+
150+
// Wait for the settings to take place
151+
if ($operation->getStatus() === Operation\Status::RUNNING) {
152+
// Wait until operation completes
153+
$operationClient = new GlobalOperationsClient();
154+
$operationClient->wait($operation->getName(), self::$projectId);
155+
}
156+
157+
ob_start();
158+
$usageExportLocation = get_usage_export_bucket(self::$projectId);
159+
$this->assertStringNotContainsString('default value of `usage_gce`', ob_get_clean());
160+
$this->assertEquals($usageExportLocation->getBucketName(), self::$bucketName);
161+
$this->assertEquals($usageExportLocation->getReportNamePrefix(), $customPrefix);
162+
163+
// Disable usage exports
164+
$operation = disable_usage_export_bucket(self::$projectId);
165+
166+
// Wait for the settings to take place
167+
if ($operation->getStatus() === Operation\Status::RUNNING) {
168+
// Wait until operation completes
169+
$operationClient = new GlobalOperationsClient();
170+
$operationClient->wait($operation->getName(), self::$projectId);
171+
}
172+
173+
$usageExportLocation = get_usage_export_bucket(self::$projectId);
174+
$this->assertNull($usageExportLocation);
175+
}
82176
}

testing/run_test_suite.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ ALT_PROJECT_TESTS=(
6666
spanner
6767
video
6868
vision
69+
compute/cloud-client/instances
6970
)
7071

7172
TMP_REPORT_DIR=$(mktemp -d)

0 commit comments

Comments
 (0)