/** * Override this method to app specific rules. * * @return returns the serverId as the id of the instance that the worker is running. */ default String getIdentity() { String serverId; try { serverId = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { serverId = System.getenv("HOSTNAME"); } if (serverId == null) { serverId = (EC2MetadataUtils.getInstanceId() == null) ? System.getProperty("user.name") : EC2MetadataUtils.getInstanceId(); } LoggerHolder.logger.debug("Setting worker id to {}", serverId); return serverId; }
private String tryDetectRegion() { try { return EC2MetadataUtils.getEC2InstanceRegion(); } catch (AmazonClientException sce) { LOG.debug("Ignoring failure to retrieve the region: " + sce.getMessage()); return null; } } }
private static String getTaskRunnerId() { return EC2MetadataUtils.getNetworkInterfaces().get(0).getPublicIPv4s().get(0); }
/** * Returns the current region of this running EC2 instance; or null if * it is unable to do so. The method avoids interpreting other parts of the * instance info JSON document to minimize potential failure. * <p> * The instance info is only guaranteed to be a JSON document per * http://docs * .aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html */ public static String getEC2InstanceRegion() { return doGetEC2InstanceRegion(getData( EC2_DYNAMICDATA_ROOT + INSTANCE_IDENTITY_DOCUMENT)); }
/** * The instance info is only guaranteed to be a JSON document per * http://docs * .aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html * <p> * This method is only a best attempt to capture the instance info as a * typed object. * <p> * Get an InstanceInfo object with dynamic information about this instance. */ public static InstanceInfo getInstanceInfo() { return doGetInstanceInfo(getData( EC2_DYNAMICDATA_ROOT + INSTANCE_IDENTITY_DOCUMENT)); }
/** * Get the virtual devices associated with the ami, root, ebs, and swap. */ public static Map<String, String> getBlockDeviceMapping() { Map<String, String> blockDeviceMapping = new HashMap<String, String>(); List<String> devices = getItems(EC2_METADATA_ROOT + "/block-device-mapping"); if (devices != null) { for (String device : devices) { blockDeviceMapping.put(device, getData(EC2_METADATA_ROOT + "/block-device-mapping/" + device)); } } return blockDeviceMapping; }
/** This will attempt to retrieve metadata about the instance this code is running on. */ public void fetchMetadata() { HttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).build(); HttpUriRequest get = RequestBuilder.get().setUri(EC2MetadataUtils.getHostAddressForEC2MetadataService()) .setConfig(requestConfig).build(); try { httpClient.execute(get); machineImage = EC2MetadataUtils.getAmiId(); instanceType = EC2MetadataUtils.getInstanceType(); instanceId = EC2MetadataUtils.getInstanceId(); // There is a method to get a Region object, but stick to strings for deserialization simplicity. region = EC2MetadataUtils.getEC2InstanceRegion(); // IP address fetching should really not be tied to EC2 but for now this lets us get a useable IP. privateIp = EC2MetadataUtils.getPrivateIpAddress(); //EC2MetadataUtils.getInstanceInfo(); } catch (IOException ex) { LOG.warn("Connection to metadata URL failed, probably not running on EC2."); } }
public void populateRuntimeContext() { if (null != EC2MetadataUtils.getInstanceId()) { runtimeContext.put("instance_id", EC2MetadataUtils.getInstanceId()); } if (null != EC2MetadataUtils.getAvailabilityZone()) { runtimeContext.put("availability_zone", EC2MetadataUtils.getAvailabilityZone()); } }
/** * Get the metadata sent to the instance */ public static String getUserData() { return getData(EC2_USERDATA_ROOT); }
private static List<String> getItems(String path, int tries, boolean slurp) { if (tries == 0) throw new SdkClientException( "Unable to contact EC2 metadata service."); List<String> items; try { String hostAddress = getHostAddressForEC2MetadataService(); String response = EC2CredentialsUtils.getInstance().readResource(new URI(hostAddress + path)); if (slurp) items = Collections.singletonList(response); else items = Arrays.asList(response.split("\n")); return items; } catch (AmazonClientException ace) { log.warn("Unable to retrieve the requested metadata (" + path + "). " + ace.getMessage(), ace); return null; } catch (Exception e) { // Retry on any other exceptions int pause = (int) (Math.pow(2, DEFAULT_QUERY_RETRIES - tries) * MINIMUM_RETRY_WAIT_TIME_MILLISECONDS); try { Thread.sleep(pause < MINIMUM_RETRY_WAIT_TIME_MILLISECONDS ? MINIMUM_RETRY_WAIT_TIME_MILLISECONDS : pause); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } return getItems(path, tries - 1, slurp); } }
@Override public String getPrivateIpAddress() { return EC2MetadataUtils.getPrivateIpAddress(); }
@Override public URI getCredentialsEndpoint() throws URISyntaxException, IOException { String host = EC2MetadataUtils.getHostAddressForEC2MetadataService(); String securityCredentialsList = EC2CredentialsUtils.getInstance().readResource(new URI(host + EC2MetadataUtils.SECURITY_CREDENTIALS_RESOURCE)); String[] securityCredentials = securityCredentialsList.trim().split("\n"); if (securityCredentials.length == 0) { throw new SdkClientException("Unable to load credentials path"); } return new URI(host + EC2MetadataUtils.SECURITY_CREDENTIALS_RESOURCE + securityCredentials[0]); } }
@Override public String getAvailabilityZone() { return EC2MetadataUtils.getAvailabilityZone(); }
/** This will attempt to retrieve metadata about the instance this code is running on. */ public void fetchMetadata() { HttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).build(); HttpUriRequest get = RequestBuilder.get().setUri(EC2MetadataUtils.getHostAddressForEC2MetadataService()) .setConfig(requestConfig).build(); try { httpClient.execute(get); machineImage = EC2MetadataUtils.getAmiId(); instanceType = EC2MetadataUtils.getInstanceType(); instanceId = EC2MetadataUtils.getInstanceId(); // There is a method to get a Region object, but stick to strings for deserialization simplicity. region = EC2MetadataUtils.getEC2InstanceRegion(); // IP address fetching should really not be tied to EC2 but for now this lets us get a useable IP. privateIp = EC2MetadataUtils.getPrivateIpAddress(); //EC2MetadataUtils.getInstanceInfo(); } catch (IOException ex) { LOG.warn("Connection to metadata URL failed, probably not running on EC2."); } }
public void populateRuntimeContext() { if (null != EC2MetadataUtils.getInstanceId()) { runtimeContext.put("instance_id", EC2MetadataUtils.getInstanceId()); } if (null != EC2MetadataUtils.getAvailabilityZone()) { runtimeContext.put("availability_zone", EC2MetadataUtils.getAvailabilityZone()); } }
private String getData(String key) { if (data.containsKey(key)) return data.get(key); // Since the keys are variable, cache a list of which ones are available to prevent unnecessary trips to the service. if (null == availableKeys) { availableKeys = EC2MetadataUtils.getItems(EC2_METADATA_ROOT + path); } if (availableKeys != null && availableKeys.contains(key)) { data.put(key, EC2MetadataUtils.getData(EC2_METADATA_ROOT + path + key)); return data.get(key); } else { return null; } }
public static String getData(String path) { return getData(path, DEFAULT_QUERY_RETRIES); }
/** * Returns the current region of this running EC2 instance; or null if * it is unable to do so. The method avoids interpreting other parts of the * instance info JSON document to minimize potential failure. * <p> * The instance info is only guaranteed to be a JSON document per * http://docs * .aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html */ public static String getEC2InstanceRegion() { return doGetEC2InstanceRegion(getData( EC2_DYNAMICDATA_ROOT + INSTANCE_IDENTITY_DOCUMENT)); }
/** * The instance info is only guaranteed to be a JSON document per * http://docs * .aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html * <p> * This method is only a best attempt to capture the instance info as a * typed object. * <p> * Get an InstanceInfo object with dynamic information about this instance. */ public static InstanceInfo getInstanceInfo() { return doGetInstanceInfo(getData( EC2_DYNAMICDATA_ROOT + INSTANCE_IDENTITY_DOCUMENT)); }
private static List<String> getItems(String path, int tries, boolean slurp) { if (tries == 0) throw new SdkClientException( "Unable to contact EC2 metadata service."); List<String> items; try { String hostAddress = getHostAddressForEC2MetadataService(); String response = EC2CredentialsUtils.getInstance().readResource(new URI(hostAddress + path)); if (slurp) items = Collections.singletonList(response); else items = Arrays.asList(response.split("\n")); return items; } catch (AmazonClientException ace) { log.warn("Unable to retrieve the requested metadata (" + path + "). " + ace.getMessage(), ace); return null; } catch (Exception e) { // Retry on any other exceptions int pause = (int) (Math.pow(2, DEFAULT_QUERY_RETRIES - tries) * MINIMUM_RETRY_WAIT_TIME_MILLISECONDS); try { Thread.sleep(pause < MINIMUM_RETRY_WAIT_TIME_MILLISECONDS ? MINIMUM_RETRY_WAIT_TIME_MILLISECONDS : pause); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } return getItems(path, tries - 1, slurp); } }