Search in sources :

Example 6 with OpenstackException

use of org.openstack.client.OpenstackException in project platformlayer by platformlayer.

the class GlanceImageStore method uploadImage.

@Override
public String uploadImage(OpsTarget target, Tags tags, File imageFile, long rawImageFileSize) throws OpsException {
    OpenstackImageClient client = getOpenstackImageClient();
    String diskFormat = null;
    if (tags != null) {
        // This logic looks suspicious...
        assert false;
        for (Tag tag : tags.getTags()) {
            ImageFormat imageFormat = ImageFormat.fromTags(tags);
            diskFormat = mapToGlanceDiskFormat(imageFormat);
        }
    }
    String glanceBaseUrl;
    String tokenId;
    try {
        Access access = client.getSession().getAuthenticationToken();
        tokenId = access.getToken().getId();
        glanceBaseUrl = client.root().getBaseUrl();
    } catch (OpenstackException e) {
        throw new OpsException("Error getting glance url", e);
    }
    // Upload to glance
    String glanceUploadUrl = glanceBaseUrl;
    if (!glanceUploadUrl.endsWith("/")) {
        glanceUploadUrl += "/";
    }
    glanceUploadUrl += "images";
    String imageName = "image-" + System.currentTimeMillis();
    Command command = Command.build("curl");
    command.addLiteral("--fail");
    command.addLiteral("--upload-file").addFile(imageFile);
    command.addLiteral("-X").addLiteral("POST");
    command.addLiteral("-H").addQuoted("X-Auth-Token: " + tokenId);
    command.addLiteral("-H").addQuoted("Content-Type: application/octet-stream");
    command.addLiteral("-H").addQuoted("X-Image-Meta-Name: " + imageName);
    command.addLiteral("-H").addQuoted("X-Image-Meta-Is-Public: True");
    // } else {
    if (diskFormat != null) {
        command.addLiteral("-H").addQuoted("X-Image-Meta-Disk-Format: " + diskFormat);
    }
    command.addLiteral("-H").addQuoted("X-Image-Meta-Container-Format: bare");
    // }
    // command.addLiteral("-H").addQuoted("X-Image-Meta-Min-Disk: 0");
    // command.addLiteral("-H").addQuoted("X-Image-Meta-Min-Ram: 0");
    // command.addLiteral("-H").addQuoted("X-Image-Meta-Image-Size: " + rawImageFileSize);
    command.addLiteral("-H").addQuoted("X-Image-Meta-Size: " + rawImageFileSize);
    // image_meta = {'name': fields.pop('name'),
    // 'is_public': utils.bool_from_string(
    // fields.pop('is_public', False)),
    // 'disk_format': fields.pop('disk_format', 'raw'),
    // 'min_disk': fields.pop('min_disk', 0),
    // 'min_ram': fields.pop('min_ram', 0),
    // 'container_format': fields.pop('container_format', 'ovf')}
    // glance add name=DebianSqueeze is_public=True disk_format=raw container_format=bare
    // system_id="http://org.platformlayer/service/imagefactory/v1.0:bootstrap"
    // image_size="${RAW_SIZE}" < disk.raw.gz
    command.addQuoted(glanceUploadUrl);
    command.setTimeout(TimeSpan.FIFTEEN_MINUTES);
    ProcessExecution execution = target.executeCommand(command);
    String imageId;
    // String imageLocation;
    {
        // "is_public": true, "deleted_at": null, "min_ram": 0, "size": 925761536}}
        try {
            JSONObject json = new JSONObject(execution.getStdOut());
            JSONObject image = json.getJSONObject("image");
            // imageLocation = image.getString("location");
            imageId = image.getString("id");
        } catch (JSONException e) {
            log.warn("Image upload returned: " + execution.getStdOut());
            throw new OpsException("Error parsing return value from image upload", e);
        }
    }
    if (tags != null) {
        updateImageTags(imageId, tags);
    }
    return imageId;
}
Also used : OpsException(org.platformlayer.ops.OpsException) JSONObject(org.json.JSONObject) Command(org.platformlayer.ops.Command) ProcessExecution(org.platformlayer.ops.process.ProcessExecution) OpenstackImageClient(org.openstack.client.common.OpenstackImageClient) Access(org.openstack.model.identity.Access) JSONException(org.json.JSONException) Tag(org.platformlayer.core.model.Tag) OpenstackException(org.openstack.client.OpenstackException) ImageFormat(org.platformlayer.ops.images.ImageFormat)

Example 7 with OpenstackException

use of org.openstack.client.OpenstackException in project platformlayer by platformlayer.

the class GlanceImageStore method findImages.

@Override
public List<CloudImage> findImages(List<Tag> tags) throws OpsException {
    List<CloudImage> matches = Lists.newArrayList();
    OpenstackImageClient glanceClient = getOpenstackImageClient();
    Iterable<Image> images;
    try {
        images = glanceClient.root().images().list(true);
    } catch (OpenstackException e) {
        throw new OpsException("Error listing images", e);
    }
    for (Image image : images) {
        boolean match = true;
        for (Tag tag : tags) {
            match = false;
            String tagKey = tag.getKey();
            String tagValue = tag.getValue();
            boolean checked = false;
            if (ImageFormat.isImageFormatTag(tag)) {
                ImageFormat format = ImageFormat.fromTag(tag);
                // if ("qcow2".equals(tagValue)) {
                // format = ImageFormat.DiskQcow2;
                // } else {
                // throw new UnsupportedOperationException("Unknown glance disk_format: " + tagValue);
                // }
                //
                // Tag mappedTag = format.toTag();
                //
                // match = Objects.equal(mappedTag.getValue().getDiskFormat(), glanceDiskFormat);
                // checked = true;
                String glanceDiskFormat = mapToGlanceDiskFormat(format);
                if (glanceDiskFormat != null) {
                    match = Objects.equal(image.getDiskFormat(), glanceDiskFormat);
                    checked = true;
                }
            }
            if (!checked) {
                for (Entry<String, Object> meta : image.getProperties().asMap().entrySet()) {
                    if (Objects.equal(tagKey, meta.getKey())) {
                        String content = (String) meta.getValue();
                        // OS BUG #885044: Content contains whitespace
                        content = content.trim();
                        if (content.equals(tagValue)) {
                            match = true;
                        }
                    }
                }
            }
            if (!match) {
                break;
            }
        }
        if (match) {
            matches.add(new GlanceImage(image));
        }
    }
    return matches;
}
Also used : OpsException(org.platformlayer.ops.OpsException) CloudImage(org.platformlayer.ops.images.CloudImage) Image(org.openstack.model.image.Image) CloudImage(org.platformlayer.ops.images.CloudImage) OpenstackException(org.openstack.client.OpenstackException) ImageFormat(org.platformlayer.ops.images.ImageFormat) OpenstackImageClient(org.openstack.client.common.OpenstackImageClient) JSONObject(org.json.JSONObject) Tag(org.platformlayer.core.model.Tag)

Example 8 with OpenstackException

use of org.openstack.client.OpenstackException in project platformlayer by platformlayer.

the class OpenstackCloudContext method findServerById.

// private AmazonEC2Client buildEc2Client() throws OpsException {
// OpsContext opsContext = OpsContext.get();
//
// AmazonEC2Client amazonEC2Client = opsContext.getUserInfo().buildEc2Client();
//
// return amazonEC2Client;
// }
//
// // // sshKeyPair = cloud.generateSshKeyPair(sshKeyName);
// // public KeyPair generateSshKeyPair(String sshKeyName) throws OpsException {
// // KeyPair sshKeyPair;
// //
// // try {
// // // OpenStack EC2 api does not support import
// // // // We create a new keypair each time... we don't want the user
// // // logging in
// // // KeyPair sshKeyPair = generateKeyPair("RSA", null);
// //
// // // ImportKeyPairRequest importKeyPairRequest = new
// // // ImportKeyPairRequest();
// // // importKeyPairRequest.setPublicKeyMaterial(publicKeyMaterial);
// // // ImportKeyPairResult importKeyPairResult =
// // // computeClient.importKeyPair(importKeyPairRequest);
// // // sshKeyName = importKeyPairResult.getKeyName();
// // AmazonEC2Client ec2Api = buildEc2Client();
// //
// // CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest(sshKeyName);
// // CreateKeyPairResult createKeyPairResult = ec2Api.createKeyPair(createKeyPairRequest);
// //
// // sshKeyPair = extractKeyPair(createKeyPairResult);
// //
// // return sshKeyPair;
// // } catch (AmazonClientException e) {
// // throw new OpsException("Error building server", e);
// // }
// // }
//
public Server findServerById(OpenstackCloud cloud, String serverId) throws OpsException {
    OpenstackComputeClient computeClient = getComputeClient(cloud);
    try {
        log.info("Getting server info for: " + serverId);
        Server server = computeClient.root().servers().server(serverId).show();
        return server;
    } catch (OpenstackNotFoundException e) {
        return null;
    } catch (OpenstackException e) {
        throw new OpsException("Error getting server", e);
    }
}
Also used : OpsException(org.platformlayer.ops.OpsException) Server(org.openstack.model.compute.Server) OpenstackComputeClient(org.openstack.client.common.OpenstackComputeClient) OpenstackNotFoundException(org.openstack.client.OpenstackNotFoundException) OpenstackException(org.openstack.client.OpenstackException)

Example 9 with OpenstackException

use of org.openstack.client.OpenstackException in project platformlayer by platformlayer.

the class OpenstackCloudContext method terminateInstance.

public AsyncServerOperation terminateInstance(OpenstackCloud cloud, String instanceId) throws OpsException {
    try {
        OpenstackComputeClient computeClient = getComputeClient(cloud);
        log.info("Terminating server: " + instanceId);
        AsyncServerOperation deleteOperation = computeClient.deleteServer(instanceId);
        return deleteOperation;
    } catch (OpenstackNotFoundException e) {
        log.info("Could not find instance to be terminated, assuming already terminated: " + instanceId);
        return null;
    } catch (OpenstackException e) {
        throw new OpsException("Error terminating server", e);
    }
}
Also used : OpsException(org.platformlayer.ops.OpsException) OpenstackComputeClient(org.openstack.client.common.OpenstackComputeClient) OpenstackNotFoundException(org.openstack.client.OpenstackNotFoundException) AsyncServerOperation(org.openstack.client.compute.AsyncServerOperation) OpenstackException(org.openstack.client.OpenstackException)

Example 10 with OpenstackException

use of org.openstack.client.OpenstackException in project platformlayer by platformlayer.

the class OpenstackCloudContext method ensurePoweredOn.

public AsyncServerOperation ensurePoweredOn(OpenstackCloud cloud, Server server) throws OpsException {
    String status = server.getStatus();
    if (Objects.equal(status, "SHUTOFF")) {
        try {
            OpenstackComputeClient computeClient = getComputeClient(cloud);
            String serverId = server.getId();
            log.info("Starting SHUTOFF server: " + serverId);
            AsyncServerOperation powerOnOperation = computeClient.powerServerOn(serverId);
            return powerOnOperation;
        } catch (OpenstackException e) {
            throw new OpsException("Error powering server on", e);
        }
    }
    return null;
}
Also used : OpsException(org.platformlayer.ops.OpsException) OpenstackComputeClient(org.openstack.client.common.OpenstackComputeClient) AsyncServerOperation(org.openstack.client.compute.AsyncServerOperation) OpenstackException(org.openstack.client.OpenstackException)

Aggregations

OpenstackException (org.openstack.client.OpenstackException)10 OpsException (org.platformlayer.ops.OpsException)10 OpenstackComputeClient (org.openstack.client.common.OpenstackComputeClient)4 Tag (org.platformlayer.core.model.Tag)4 JSONObject (org.json.JSONObject)3 OpenstackImageClient (org.openstack.client.common.OpenstackImageClient)3 AsyncServerOperation (org.openstack.client.compute.AsyncServerOperation)3 ImageFormat (org.platformlayer.ops.images.ImageFormat)3 OpenstackNotFoundException (org.openstack.client.OpenstackNotFoundException)2 SecurityGroup (org.openstack.model.compute.SecurityGroup)2 Server (org.openstack.model.compute.Server)2 CloudImage (org.platformlayer.ops.images.CloudImage)2 IOException (java.io.IOException)1 TimeoutException (java.util.concurrent.TimeoutException)1 JAXBException (javax.xml.bind.JAXBException)1 JSONException (org.json.JSONException)1 CreateSecurityGroupRuleRequest (org.openstack.model.compute.CreateSecurityGroupRuleRequest)1 Flavor (org.openstack.model.compute.Flavor)1 Image (org.openstack.model.compute.Image)1 KeyPair (org.openstack.model.compute.KeyPair)1