1 /*
2 * Copyright Amazon.com, Inc. or its affiliates. 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 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15
16 package software.amazon.awssdk.regions.providers;
17
18 import software.amazon.awssdk.annotations.SdkProtectedApi;
19 import software.amazon.awssdk.core.SdkSystemSetting;
20 import software.amazon.awssdk.core.exception.SdkClientException;
21 import software.amazon.awssdk.regions.Region;
22 import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils;
23
24 /**
25 * Attempts to load region information from the EC2 Metadata service. If the application is not
26 * running on EC2 this provider will thrown an exception.
27 *
28 * <P>
29 * If {@link SdkSystemSetting#AWS_EC2_METADATA_DISABLED} is set to true, it will not try to load
30 * region from EC2 metadata service and will return null.
31 */
32 @SdkProtectedApi
33 public final class InstanceProfileRegionProvider implements AwsRegionProvider {
34
35 /**
36 * Cache region as it will not change during the lifetime of the JVM.
37 */
38 private volatile String region;
39
40 @Override
41 public Region getRegion() throws SdkClientException {
42 if (SdkSystemSetting.AWS_EC2_METADATA_DISABLED.getBooleanValueOrThrow()) {
43 throw SdkClientException.builder()
44 .message("EC2 Metadata is disabled. Unable to retrieve region information from " +
45 "EC2 Metadata service.")
46 .build();
47 }
48
49 if (region == null) {
50 synchronized (this) {
51 if (region == null) {
52 this.region = tryDetectRegion();
53 }
54 }
55 }
56
57 if (region == null) {
58 throw SdkClientException.builder()
59 .message("Unable to retrieve region information from EC2 Metadata service. "
60 + "Please make sure the application is running on EC2.")
61 .build();
62 }
63
64 return Region.of(region);
65 }
66
67 private String tryDetectRegion() {
68 return EC2MetadataUtils.getEC2InstanceRegion();
69 }
70 }
71