-
Notifications
You must be signed in to change notification settings - Fork 53
feat(gcp): current region methods #399
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
prefanatic
wants to merge
1
commit into
GoogleCloudPlatform:main
Choose a base branch
from
prefanatic:feat/region
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
// Copyright 2022 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. | ||
|
||
import 'dart:io'; | ||
|
||
import 'package:http/http.dart' as http; | ||
|
||
import 'bad_configuration_exception.dart'; | ||
|
||
/// A convenience wrapper that first tries [regionFromEnvironment] | ||
/// then (if the value is `null`) tries [regionFromMetadataServer] | ||
/// | ||
/// Like [regionFromMetadataServer], if no value is found, a | ||
/// [BadConfigurationException] is thrown. | ||
Future<String> computeRegion() async { | ||
final localValue = regionFromEnvironment(); | ||
if (localValue != null) { | ||
return localValue; | ||
} | ||
final result = await regionFromMetadataServer(); | ||
|
||
return result; | ||
} | ||
|
||
/// Returns the | ||
/// [Region](https://cloud.google.com/compute/docs/regions-zones#identifying_a_region_or_zone) | ||
/// for the current instance by checking the environment variables | ||
/// in [gcpRegionEnvironmentVariables]. | ||
/// | ||
/// The list is checked in order. This is useful for local development. | ||
/// | ||
/// If no matching variable is found, `null` is returned. | ||
String? regionFromEnvironment() { | ||
for (var envKey in gcpRegionEnvironmentVariables) { | ||
final value = Platform.environment[envKey]; | ||
if (value != null) return value; | ||
} | ||
|
||
return null; | ||
} | ||
|
||
/// Returns a [Future] that completes with the | ||
/// [Region](https://cloud.google.com/compute/docs/regions-zones#identifying_a_region_or_zone) | ||
/// for the current instance by checking | ||
/// [instance metadata](https://cloud.google.com/compute/docs/metadata/default-metadata-values#vm_instance_metadata). | ||
/// | ||
/// If the metadata server cannot be contacted, a [BadConfigurationException] is | ||
/// thrown. | ||
Future<String> regionFromMetadataServer() async { | ||
const host = 'http://metadata.google.internal/'; | ||
final url = Uri.parse('$host/computeMetadata/v1/instance/region'); | ||
|
||
try { | ||
final response = await http.get( | ||
url, | ||
headers: {'Metadata-Flavor': 'Google'}, | ||
); | ||
|
||
if (response.statusCode != 200) { | ||
throw HttpException( | ||
'${response.body} (${response.statusCode})', | ||
uri: url, | ||
); | ||
} | ||
|
||
return response.body; | ||
} on SocketException catch (e) { | ||
throw BadConfigurationException( | ||
''' | ||
Could not connect to $host. | ||
If not running on Google Cloud, one of these environment variables must be set | ||
to the target region: | ||
${gcpRegionEnvironmentVariables.join('\n')} | ||
''', | ||
details: e.toString(), | ||
); | ||
} | ||
} | ||
|
||
/// A set of typical environment variables that are likely to represent the | ||
/// current Google Cloud instance region. | ||
/// | ||
/// For context, see: | ||
/// * https://cloud.google.com/functions/docs/env-var | ||
/// * https://cloud.google.com/compute/docs/gcloud-compute#default_project | ||
/// * https://github.com/GoogleContainerTools/gcp-auth-webhook/blob/08136ca171fe5713cc70ef822c911fbd3a1707f5/server.go#L38-L44 | ||
/// | ||
/// Note: these are ordered starting from the most current/canonical to least. | ||
/// (At least as could be determined at the time of writing.) | ||
const gcpRegionEnvironmentVariables = { | ||
'FUNCTION_REGION', | ||
'CLOUDSDK_COMPUTE_REGION', | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
// Copyright 2022 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. | ||
import 'package:gcp/gcp.dart'; | ||
|
||
Future<void> main() async { | ||
print(await computeRegion()); | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should DRY up this logic. Maybe add a
metadata_server.dart
file and share the logic withgcp_project.dart
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@prefanatic thoughts on my thoughts?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@kevmoo Sorry about the delay - I took a few stabs at drying up this implementation, but didn't like the direction I found myself in.
One attempt at buttoning this up included defining
MetadataServerClient
(name withstanding) which exposed these region and project endpoints. However, I was unhappy with aspects related to error handling; we disclose some nice resolution regarding which environment variables to provide in leu of the metadata server. It felt weird to me to move that into such ametadata_server.dart
.In an attempt with leaving the error handling out, I ended up with an implementation that's slightly analogous to http.read, where
computeRegion
andcomputeProject
would open up a client, try and return the metadata result, or catch into statement about environment variables needed. This slimmed up the original methods a little bit, but now introduced some arguably duplicativewithClient
semantics to retain backwards compatibility in those methods.I think this approach is worth taking? Let me know if I'm on the right track.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think of this? #421
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah, looks much nicer. I wish I thought of using enhanced enums!
I left some small documentation nits over there for the generalization, in the review.