public synchronized String associateAddress(IaasProvider iaasInfo,
NodeMetadata node) {
ComputeServiceContext context = iaasInfo.getComputeService()
.getContext();
AWSEC2Client ec2Client = context.unwrap(AWSEC2ApiMetadata.CONTEXT_TOKEN).getApi();
String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
String ip = null;
// first try to find an unassigned IP.
ArrayList<PublicIpInstanceIdPair> unassignedIps = Lists
.newArrayList(Iterables.filter(ec2Client
.getElasticIPAddressServices()
.describeAddressesInRegion(region, new String[0]),
new Predicate<PublicIpInstanceIdPair>() {
@Override
public boolean apply(PublicIpInstanceIdPair arg0) {
return arg0.getInstanceId() == null;
}
}));
if (!unassignedIps.isEmpty()) {
// try to prevent multiple parallel launches from choosing the same
// ip.
Collections.shuffle(unassignedIps);
ip = Iterables.getLast(unassignedIps).getPublicIp();
}
// if no unassigned IP is available, we'll try to allocate an IP.
if (ip == null || ip.isEmpty()) {
try {
ip = ec2Client.getElasticIPAddressServices()
.allocateAddressInRegion(region);
log.info("Assigned ip [" + ip + "]");
} catch (Exception e) {
String msg = "Failed to allocate an IP address. All IP addresses are in use.";