1 /*
2 * Copyright 2011-2020 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 package com.amazonaws.regions;
16
17 import com.amazonaws.AmazonClientException;
18 import com.amazonaws.SDKGlobalConfiguration;
19 import com.amazonaws.util.EC2MetadataUtils;
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22
23 /**
24 * Attempts to load region information from the EC2 Metadata service. If the application is not
25 * running on EC2 or {@link SDKGlobalConfiguration#isEc2MetadataDisabled()} returns true,
26 * this provider will return null.
27 */
28 public class InstanceMetadataRegionProvider extends AwsRegionProvider {
29
30 private static final Log LOG = LogFactory.getLog(InstanceMetadataRegionProvider.class);
31
32 /**
33 * Cache region as it will not change during the lifetime of the JVM.
34 */
35 private volatile String region;
36
37 /**
38 * @throws AmazonClientException if {@link SDKGlobalConfiguration#isEc2MetadataDisabled()} is true
39 */
40 @Override
41 public String getRegion() {
42 if (SDKGlobalConfiguration.isEc2MetadataDisabled()) {
43 throw new AmazonClientException("AWS_EC2_METADATA_DISABLED is set to true, not loading region from EC2 Instance "
44 + "Metadata service");
45 }
46
47 if (region == null) {
48 synchronized (this) {
49 if (region == null) {
50 this.region = tryDetectRegion();
51 }
52 }
53 }
54 return region;
55 }
56
57 private String tryDetectRegion() {
58 try {
59 return EC2MetadataUtils.getEC2InstanceRegion();
60 } catch (AmazonClientException sce) {
61 LOG.debug("Ignoring failure to retrieve the region: " + sce.getMessage());
62 return null;
63 }
64 }
65 }
66