Java Code Examples for org.jclouds.compute.ComputeServiceContext#unwrapApi()

The following examples show how to use org.jclouds.compute.ComputeServiceContext#unwrapApi() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OpenstackIaas.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized boolean createKeyPairFromPublicKey(String region, String keyPairName, String publicKey) {
    IaasProvider iaasInfo = getIaasProvider();
    String openstackNovaMsg = " Openstack-nova. Region: " + region + " - Name: ";
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    NovaApi novaApi = context.unwrapApi(NovaApi.class);
    KeyPairApi api = novaApi.getKeyPairExtensionForZone(region).get();
    KeyPair keyPair = api.createWithPublicKey(keyPairName, publicKey);
    if (keyPair != null) {
        iaasInfo.getTemplate().getOptions().as(NovaTemplateOptions.class).keyPairName(keyPair.getName());
        log.info(SUCCESSFUL_LOG_LINE + openstackNovaMsg + keyPair.getName());
        return true;
    }
    log.error(FAILED_LOG_LINE + openstackNovaMsg);
    return false;
}
 
Example 2
Source File: CloudStackIaas.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Override
public boolean createKeyPairFromPublicKey(String region, String keyPairName, String publicKey) {

    IaasProvider iaasInfo = getIaasProvider();
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);
    SshKeyPair sshKeyPair = cloudStackApi.getSSHKeyPairApi().createSSHKeyPair(keyPairName);

    if (sshKeyPair != null) {

        iaasInfo.getTemplate().getOptions().as(CloudStackTemplateOptions.class)
                .keyPair(sshKeyPair.getName());

        log.info("A key-pair is created successfully - Key Pair Name: " + sshKeyPair.getName());
        return true;
    }
    log.error("Key-pair is unable to create");
    return false;
}
 
Example 3
Source File: CloudStackIaas.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValidZone(String region, String zone) throws InvalidZoneException {

    IaasProvider iaasInfo = getIaasProvider();
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);
    ListZonesOptions listZonesOptions = new ListZonesOptions();
    listZonesOptions.available(true);
    Set<Zone> zoneSet = cloudStackApi.getZoneApi().listZones(listZonesOptions);

    for (org.jclouds.cloudstack.domain.Zone configuredZone : zoneSet) {
        if (configuredZone.getName().equalsIgnoreCase(zone)) {
            return true;
        }
    }
    String msg = "Invalid zone: " + zone + " in the iaas: " + iaasInfo.getType();
    log.error(msg);
    throw new InvalidZoneException(msg);
}
 
Example 4
Source File: CreateVolumeAndAttach.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
public CreateVolumeAndAttach(String username, String apiKey) {
   // The provider configures jclouds To use the Rackspace Cloud (US)
   // To use the Rackspace Cloud (UK) set the system property or default value to "rackspace-cloudservers-uk"
   String provider = System.getProperty("provider.cs", "rackspace-cloudservers-us");

   // These properties control how often jclouds polls for a status udpate
   Properties overrides = new Properties();
   overrides.setProperty(POLL_INITIAL_PERIOD, POLL_PERIOD_TWENTY_SECONDS);
   overrides.setProperty(POLL_MAX_PERIOD, POLL_PERIOD_TWENTY_SECONDS);

   Iterable<Module> modules = ImmutableSet.<Module> of(new SshjSshClientModule());

   ComputeServiceContext context = ContextBuilder.newBuilder(provider)
         .credentials(username, apiKey)
         .modules(modules)
         .overrides(overrides)
         .buildView(ComputeServiceContext.class);
   computeService = context.getComputeService();
   novaApi = context.unwrapApi(NovaApi.class);
   volumeAttachmentApi = novaApi.getVolumeAttachmentApi(REGION).get();

   cinderApi = ContextBuilder.newBuilder(PROVIDER)
         .credentials(username, apiKey)
         .buildApi(CinderApi.class);
   volumeApi = cinderApi.getVolumeApi(REGION);
}
 
Example 5
Source File: DetachVolume.java    From jclouds-examples with Apache License 2.0 6 votes vote down vote up
public DetachVolume(String username, String apiKey) {
   // The provider configures jclouds To use the Rackspace Cloud (US)
   // To use the Rackspace Cloud (UK) set the system property or default value to "rackspace-cloudservers-uk"
   String provider = System.getProperty("provider.cs", "rackspace-cloudservers-us");

   Iterable<Module> modules = ImmutableSet.<Module> of(new SshjSshClientModule());

   ComputeServiceContext context = ContextBuilder.newBuilder(provider)
         .credentials(username, apiKey)
         .modules(modules)
         .buildView(ComputeServiceContext.class);
   computeService = context.getComputeService();
   NovaApi novaApi = context.unwrapApi(NovaApi.class);
   serverApi = novaApi.getServerApi(REGION);
   volumeAttachmentApi = novaApi.getVolumeAttachmentApi(REGION).get();

   cinderApi = ContextBuilder.newBuilder(PROVIDER)
         .credentials(username, apiKey)
         .buildApi(CinderApi.class);
   volumeApi = cinderApi.getVolumeApi(REGION);
}
 
Example 6
Source File: CloudStackIaas.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
private boolean waitForStatus(String volumeId, Volume.State expectedStatus, int timeoutInMilliseconds) throws TimeoutException {
    int timeout = 1000 * 60 * timeoutInMilliseconds;
    long timout = System.currentTimeMillis() + timeout;

    IaasProvider iaasInfo = getIaasProvider();
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);

    //get volume
    org.jclouds.cloudstack.domain.Volume volume = cloudStackApi.getVolumeApi().getVolume(volumeId);

    Volume.State volumeState = volume.getState();

    while (volumeState != expectedStatus) {
        try {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Volume %s is still NOT in %s. Current State=%s", volumeId, expectedStatus, volumeState));
            }
            if (volumeState == Volume.State.FAILED || volumeState == Volume.State.DESTROYED || volumeState == Volume.State.UNRECOGNIZED) {
                log.error("Volume " + volumeId + " is in state" + volumeState);
                return false;
            }

            Thread.sleep(1000);
            volumeState = volume.getState();
            if (System.currentTimeMillis() > timout) {
                throw new TimeoutException();
            }
        } catch (InterruptedException e) {
            // Ignoring the exception
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(String.format("Volume %s status became %s", volumeId, expectedStatus));
    }

    return true;
}
 
Example 7
Source File: ServerMetadata.java    From jclouds-examples with Apache License 2.0 5 votes vote down vote up
public ServerMetadata(String username, String apiKey) {
   ComputeServiceContext context = ContextBuilder.newBuilder(PROVIDER)
         .credentials(username, apiKey)
         .buildView(ComputeServiceContext.class);
   computeService = context.getComputeService();
   NovaApi novaApi = context.unwrapApi(NovaApi.class);
   serverApi = novaApi.getServerApi(REGION);
}
 
Example 8
Source File: GCEIaas.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
private GoogleComputeEngineApi getGCEApi() {
    IaasProvider iaasInfo = getIaasProvider();
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    GoogleComputeEngineApi api = context.unwrapApi(GoogleComputeEngineApi.class);

    return api;
}
 
Example 9
Source File: OpenstackIaas.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public void detachVolume(String instanceId, String volumeId) {
    IaasProvider iaasInfo = getIaasProvider();
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
    //NovaApi novaApi = context.unwrapApi(NovaApi.class);
    //VolumeApi api = novaApi.getVolumeExtensionForZone(region).get();

    if (region == null) {
        log.fatal(String.format(
                "Cannot detach the volume [id]: %s from the instance [id]: %s. Extracted region is null for Iaas "
                        + ": %s", volumeId, instanceId, iaasInfo));
        return;
    }
    if (log.isDebugEnabled()) {
        log.debug(String.format("Starting to detach volume %s from the instance %s", volumeId, instanceId));
    }

    NovaApi novaApi = context.unwrapApi(NovaApi.class);
    VolumeAttachmentApi attachmentApiapi = novaApi.getVolumeAttachmentExtensionForZone(region).get();
    VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get();

    if (attachmentApiapi.detachVolumeFromServer(volumeId, removeRegionPrefix(instanceId))) {
        log.info(String.format(
                "Detachment of Volume [id]: %s from instance [id]: %s was successful. [region] : %s of Iaas : %s",
                volumeId, instanceId, region, iaasInfo));
    } else {
        log.error(String.format(
                "Detachment of Volume [id]: %s from instance [id]: %s was unsuccessful. [region] : %s [volume "
                        + "Status] : %s", volumeId, instanceId, region, getVolumeStatus(volumeApi, volumeId)));
    }
}
 
Example 10
Source File: OpenstackIaas.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
private boolean waitForStatus(String volumeId, Volume.Status expectedStatus, int timeoutInMins)
        throws TimeoutException {
    int timeout = 1000 * 60 * timeoutInMins;
    long timout = System.currentTimeMillis() + timeout;

    IaasProvider iaasInfo = getIaasProvider();
    String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    NovaApi novaApi = context.unwrapApi(NovaApi.class);
    VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get();
    Volume.Status volumeStatus = this.getVolumeStatus(volumeApi, volumeId);

    while (volumeStatus != expectedStatus) {
        try {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Volume %s is still NOT in %s. Current State=%s", volumeId, expectedStatus,
                        volumeStatus));
            }
            if (volumeStatus == Volume.Status.ERROR) {
                log.error("Volume " + volumeId + " is in state ERROR");
                return false;
            }
            Thread.sleep(1000);
            volumeStatus = this.getVolumeStatus(volumeApi, volumeId);
            if (System.currentTimeMillis() > timout) {
                throw new TimeoutException();
            }
        } catch (InterruptedException e) {
            // Ignoring the exception
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(String.format("Volume %s status became %s", volumeId, expectedStatus));
    }
    return true;
}
 
Example 11
Source File: CloudStackIaas.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteVolume(String volumeId) {
    IaasProvider iaasInfo = getIaasProvider();
    ComputeServiceContext context = iaasInfo.getComputeService()
            .getContext();
    CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);
    cloudStackApi.getVolumeApi().deleteVolume(volumeId);
    log.info("Deletion of Volume [id]: " + volumeId + " was successful. "
            + " of Iaas : " + iaasInfo);
}
 
Example 12
Source File: CloudStackIaas.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public void detachVolume(String instanceId, String volumeId) {


    IaasProvider iaasInfo = getIaasProvider();

    ComputeServiceContext context = iaasInfo.getComputeService()
            .getContext();

    if (log.isDebugEnabled()) {
        log.debug(String.format("Starting to detach volume %s from the instance %s", volumeId, instanceId));
    }

    CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);

    cloudStackApi.getVolumeApi().detachVolume(volumeId);

    try {
        //TODO this is true only for newly created volumes
        if (waitForStatus(volumeId, Volume.State.ALLOCATED, 5)) {
            log.info(String.format("Detachment of Volume [id]: %s from instance [id]: %s was successful of Iaas : %s", volumeId, instanceId, iaasInfo));
        }
    } catch (TimeoutException e) {
        log.error(String.format("Detachment of Volume [id]: %s from instance [id]: %s was unsuccessful. [volume Status] : %s", volumeId, instanceId, iaasInfo));
    }

}
 
Example 13
Source File: CloudStackIaas.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseAddress(String ip) {
    IaasProvider iaasInfo = getIaasProvider();
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);
    cloudStackApi.getAddressApi().disassociateIPAddress(ip);
}
 
Example 14
Source File: JcloudsUtil.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static Map<Integer, Integer> dockerPortMappingsFor(JcloudsLocation docker, String containerId) {
    ComputeServiceContext context = null;
    try {
        Properties properties = new Properties();
        properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, Boolean.toString(true));
        properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, Boolean.toString(true));
        context = ContextBuilder.newBuilder("docker")
                .endpoint(docker.getEndpoint())
                .credentials(docker.getIdentity(), docker.getCredential())
                .overrides(properties)
                .modules(ImmutableSet.<Module>of(new SLF4JLoggingModule(), new SshjSshClientModule()))
                .build(ComputeServiceContext.class);
        DockerApi api = context.unwrapApi(DockerApi.class);
        Container container = api.getContainerApi().inspectContainer(containerId);
        Map<Integer, Integer> portMappings = Maps.newLinkedHashMap();
        Map<String, List<Map<String, String>>> ports = container.networkSettings().ports();
        if (ports == null) ports = ImmutableMap.<String, List<Map<String,String>>>of();

        LOG.debug("Docker will forward these ports {}", ports);
        for (Map.Entry<String, List<Map<String, String>>> entrySet : ports.entrySet()) {
            String containerPort = Iterables.get(Splitter.on("/").split(entrySet.getKey()), 0);
            String hostPort = Iterables.getOnlyElement(Iterables.transform(entrySet.getValue(),
                    new Function<Map<String, String>, String>() {
                        @Override
                        public String apply(Map<String, String> hostIpAndPort) {
                            return hostIpAndPort.get("HostPort");
                        }
                    }));
            portMappings.put(Integer.parseInt(containerPort), Integer.parseInt(hostPort));
        }
        return portMappings;
    } finally {
        if (context != null) {
            context.close();
        }
    }
}
 
Example 15
Source File: JcloudsUtil.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static String waitForPasswordOnAws(ComputeService computeService, final NodeMetadata node, long timeout, TimeUnit timeUnit) throws TimeoutException {
    ComputeServiceContext computeServiceContext = computeService.getContext();
    AWSEC2Api ec2Client = computeServiceContext.unwrapApi(AWSEC2Api.class);
    final WindowsApi client = ec2Client.getWindowsApi().get();
    final String region = node.getLocation().getParent().getId();

    // The Administrator password will take some time before it is ready - Amazon says sometimes 15 minutes.
    // So we create a predicate that tests if the password is ready, and wrap it in a retryable predicate.
    Predicate<String> passwordReady = new Predicate<String>() {
        @Override public boolean apply(String s) {
            if (Strings.isNullOrEmpty(s)) return false;
            PasswordData data = client.getPasswordDataInRegion(region, s);
            if (data == null) return false;
            return !Strings.isNullOrEmpty(data.getPasswordData());
        }
    };

    LOG.info("Waiting for password, for "+node.getProviderId()+":"+node.getId());
    Predicate<String> passwordReadyRetryable = Predicates2.retry(passwordReady, timeUnit.toMillis(timeout), 10*1000, TimeUnit.MILLISECONDS);
    boolean ready = passwordReadyRetryable.apply(node.getProviderId());
    if (!ready) throw new TimeoutException("Password not available for "+node+" in region "+region+" after "+timeout+" "+timeUnit.name());

    // Now pull together Amazon's encrypted password blob, and the private key that jclouds generated
    PasswordDataAndPrivateKey dataAndKey = new PasswordDataAndPrivateKey(
            client.getPasswordDataInRegion(region, node.getProviderId()),
            node.getCredentials().getPrivateKey());

    // And apply it to the decryption function
    WindowsLoginCredentialsFromEncryptedData f = computeServiceContext.utils().injector().getInstance(WindowsLoginCredentialsFromEncryptedData.class);
    LoginCredentials credentials = f.apply(dataAndKey);

    return credentials.getPassword();
}
 
Example 16
Source File: NovaNetworkingApi.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public List<String> associateAddresses(NodeMetadata node) {

    ComputeServiceContext context = iaasProvider.getComputeService().getContext();
    String region = ComputeServiceBuilderUtil.extractRegion(iaasProvider);

    if (StringUtils.isEmpty(region)) {
        throw new RuntimeException("Could not find region in iaas provider: " + iaasProvider.getName());
    }

    NovaApi novaApi = context.unwrapApi(NovaApi.class);
    FloatingIPApi floatingIPApi = novaApi.getFloatingIPExtensionForZone(region).get();

    String ip = null;
    // first try to find an unassigned IP.
    FluentIterable<FloatingIP> floatingIPs = floatingIPApi.list();
    ArrayList<FloatingIP> unassignedIps = Lists.newArrayList(Iterables.filter(floatingIPs,
            new Predicate<FloatingIP>() {
                @Override
                public boolean apply(FloatingIP floatingIP) {
                    return floatingIP.getInstanceId() == null;
                }
            }));

    if (!unassignedIps.isEmpty()) {
        // try to prevent multiple parallel launches from choosing the same ip.
        Collections.shuffle(unassignedIps);
        ip = Iterables.getLast(unassignedIps).getIp();
    }

    // if no unassigned IP is available, we'll try to allocate an IP.
    if (StringUtils.isEmpty(ip)) {
        String floatingIpPool = iaasProvider.getProperty(CloudControllerConstants.DEFAULT_FLOATING_IP_POOL);
        FloatingIP allocatedFloatingIP;
        if (StringUtils.isEmpty(floatingIpPool)) {
            allocatedFloatingIP = floatingIPApi.create();
        } else {
            log.debug(String.format("Trying to allocate a floating IP address from IP pool %s", floatingIpPool));
            allocatedFloatingIP = floatingIPApi.allocateFromPool(floatingIpPool);
        }
        if (allocatedFloatingIP == null) {
            String msg = String.format("Floating IP API did not return a floating IP address from IP pool %s",
                    floatingIpPool);
            log.error(msg);
            throw new CloudControllerException(msg);
        }
        ip = allocatedFloatingIP.getIp();
    }

    // wait till the fixed IP address gets assigned - this is needed before
    // we associate a public IP
    log.info(String.format("Waiting for private IP addresses get allocated: [node-id] %s", node.getId()));
    while (node.getPrivateAddresses() == null) {
        CloudControllerUtil.sleep(1000);
    }
    log.info(String.format("Private IP addresses allocated: %s", node.getPrivateAddresses()));

    if ((node.getPublicAddresses() != null) && (node.getPublicAddresses().iterator().hasNext())) {
        log.info("Public IP address "
                + node.getPublicAddresses().iterator().next()
                + " is already allocated to the instance: [node-id]  "
                + node.getId());
        return null;
    }

    int retries = 0;
    int retryCount = Integer.getInteger("stratos.public.ip.association.retry.count", 5);
    while ((retries < retryCount) && (!associateIp(floatingIPApi, ip, node.getProviderId()))) {
        // wait for 5s
        CloudControllerUtil.sleep(5000);
        retries++;
    }

    log.info(String.format("Successfully associated an IP address: [node-id] %s [ip] %s", node.getId(), ip));

    List<String> allocatedIPAddresses = new ArrayList<String>();
    allocatedIPAddresses.add(ip);
    return allocatedIPAddresses;
}
 
Example 17
Source File: OpenstackIaas.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public String createVolume(int sizeGB, String snapshotId) {
    IaasProvider iaasInfo = getIaasProvider();
    if (iaasInfo == null) {
        log.fatal(String.format("Cannot create a new volume with snapshot ID : %s", snapshotId));
        return null;
    }
    String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
    String zone = ComputeServiceBuilderUtil.extractZone(iaasInfo);
    if (region == null) {
        log.fatal(String.format("Cannot create a new volume. Extracted region is null for Iaas : %s", iaasInfo));
        return null;
    }
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    NovaApi novaApi = context.unwrapApi(NovaApi.class);
    VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get();
    Volume volume;
    if (StringUtils.isEmpty(snapshotId)) {
        if (log.isDebugEnabled()) {
            log.info("Creating a volume in the zone " + zone);
        }
        volume = volumeApi.create(sizeGB, CreateVolumeOptions.Builder.availabilityZone(zone));
    } else {
        if (log.isDebugEnabled()) {
            log.info("Creating a volume in the zone " + zone + " from the shanpshot " + snapshotId);
        }
        volume = volumeApi
                .create(sizeGB, CreateVolumeOptions.Builder.availabilityZone(zone).snapshotId(snapshotId));
    }

    if (volume == null) {
        log.fatal(String.format("Volume creation was unsuccessful. [region] : %s [zone] : %s of Iaas : %s", region,
                zone, iaasInfo));
        return null;
    }

    String volumeId = volume.getId();
    /*
    Volume.Status volumeStatus = this.getVolumeStatus(volumeApi, volumeId);

    if(!(volumeStatus == Volume.Status.AVAILABLE || volumeStatus == Volume.Status.CREATING)){
        log.error(String.format("Error while creating [volume id] %s. Volume status is %s", volumeId,
        volumeStatus));
        return volumeId;
    }
    try {
        if(!waitForStatus(volumeApi, volumeId, Volume.Status.AVAILABLE)){
            log.error("Volume did not become AVAILABLE. Current status is " + volume.getStatus());
        }
    } catch (TimeoutException e) {
        log.error("[Volume ID] " + volumeId + "did not become AVAILABLE within expected timeout");
        return volumeId;
    }
    */
    log.info(String.format(
            "Successfully created a new volume [id]: %s in [region] : %s [zone] : %s of Iaas : %s [Volume ID]%s",
            volume.getId(), region, zone, iaasInfo, volume.getId()));
    return volumeId;
}
 
Example 18
Source File: CloudStackIaas.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
/**
 * IMPORTANT
 * In cloudstack we can assign public IPs, if we are using an advanced zone only. If we are using a basic zone
 * we cannot assign public ips.
 * <p/>
 * When we use an advanced zone, a public IP address will get automatically assigned to the vm. So we don't need
 * to find an unallocated IP address and assign that address to the vm. If you are using a basic zone you cannot
 * assign public IPs
 * <p/>
 * So  this method will find the IP that has been assigned to the vm and return it.
 */
@Override
public List<String> associateAddresses(NodeMetadata node) {

    IaasProvider iaasInfo = getIaasProvider();
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    CloudStackApi cloudStackApi = context.unwrapApi(CloudStackApi.class);
    String ip = null;

    // get all allocated IPs
    ListPublicIPAddressesOptions listPublicIPAddressesOptions = new ListPublicIPAddressesOptions();
    listPublicIPAddressesOptions.zoneId(iaasInfo.getProperty(CloudControllerConstants.AVAILABILITY_ZONE));

    Set<PublicIPAddress> publicIPAddresses = cloudStackApi.getAddressApi()
            .listPublicIPAddresses(listPublicIPAddressesOptions);

    String id = node.getProviderId(); //vm ID

    for (PublicIPAddress publicIPAddress : publicIPAddresses) {
        if (publicIPAddress.getVirtualMachineId().equals(id)) { //check whether this instance has
            // already got an public ip or not
            ip = publicIPAddress.getIPAddress(); //A public ip has been successfully assigned to the vm
            log.info("Successfully associated an IP address " + ip
                    + " for node with id: " + node.getId());
            break;
        }

    }

    if (ip == null || ip.isEmpty()) { //IP has not been successfully assigned to VM(That means there are
        //  no more IPs  available for the VM)
        String msg = "No address associated for node with id: " + node.getId();
        log.warn(msg);
        throw new CloudControllerException(msg);
    }

    List<String> associatedIPs = new ArrayList<String>();
    associatedIPs.add(ip);

    return associatedIPs;
}
 
Example 19
Source File: OpenstackIaas.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public void deleteVolume(String volumeId) {
    IaasProvider iaasInfo = getIaasProvider();
    ComputeServiceContext context = iaasInfo.getComputeService().getContext();
    String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
    NovaApi novaApi = context.unwrapApi(NovaApi.class);
    VolumeApi api = novaApi.getVolumeExtensionForZone(region).get();
    if (region == null) {
        log.fatal(
                String.format("Cannot delete the volume [id]: %s. Extracted region is null for Iaas : %s", volumeId,
                        iaasInfo));
        return;
    }

    Volume volume = api.get(volumeId);
    if (volume == null) {
        log.warn(String.format("Could not remove volume [id] %s since volume does not exist", volumeId));
        return;
    }
    Volume.Status volumeStatus = volume.getStatus();
    if (volumeStatus == Volume.Status.IN_USE) {
        try {
            waitForStatus(volumeId, Volume.Status.AVAILABLE, 2);
        } catch (TimeoutException e) {
            //Timeout Exception is occurred if the instance did not become available withing expected time period.
            //Hence volume will not be deleted.

            log.error("[Volume ID] " + volumeId
                    + "did not become AVAILABLE within expected timeout, hence returning without deleting the "
                    + "volume");
            return;
        }
    }
    // Coming here means either AVAILABLE or ERROR
    if (api.delete(volumeId)) {
        log.info(String.format("Deletion of Volume [id]: %s was successful. [region] : %s of Iaas : %s", volumeId,
                region, iaasInfo));
    } else {
        log.error(
                String.format("Deletion of Volume [id]: %s was unsuccessful. [region] : %s of Iaas : %s", volumeId,
                        region, iaasInfo));
    }
}
 
Example 20
Source File: SecurityGroupDefinition.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public void createGroupInAwsRegion(ComputeServiceContext computeServiceContext, String region) {
    AWSEC2Api ec2Client = computeServiceContext.unwrapApi(AWSEC2Api.class);
    String sgId = ec2Client.getSecurityGroupApi().get().createSecurityGroupInRegionAndReturnId(region, getName(), "Brooklyn-managed security group "+getName());
    ec2Client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, sgId, ipPerms);
}