SDK Apache jclouds pour Cloudwatt

Site officiel : Apache jclouds
Documentation : Javadoc for Apache jclouds
Remonter un bug : Bug tracker
Compte Twitter : @jclouds


Ce tutoriel a pour but de vous expliquer comment utiliser les APIs Cloudwatt pour le développement de vos applications avec la bibliothèque Apache jclouds.

Cloudwatt propose une gamme d’APIs puissantes qui peuvent être utilisées pour piloter vos Services Cloud (Serveurs Cloud, Stockage objet, Stockage bloc, Mise en réseau…). Pour en savoir plus, veuillez consulter notre référentiel des APIs Cloudwatt.

Bien qu’il soit possible d’écrire des applications ou des scripts sollicitant les APIs adaptées au but recherché, Apache jclouds fournit une simple API que vous pouvez utiliser avec vos applications java.

Installation de jclouds :

Dépendances :

  • Java Development Kit (JDK) version 6 ou plus récent.
  • Maven version 3 ou plus récent.

Installation :

  • Créez un répertoire.
  • Copiez le fichier pom.xml dans le nouveau répertoire.
  • Installez les dépendances en exécutant la commande suivante :
$ mvn dependency:copy-dependencies "-DoutputDirectory=./lib"

Utiliser l’API jclouds :

Voici un scénario dont les différentes étapes serviront d’exemple à l’utilisation de l’API jclouds :

  • déclarer les credentials,
  • importer une paire de clés SSH,
  • créer un réseau et un sous-réseau,
  • créer un routeur,
  • lancer une instance,
  • allouer une IP flottante,
  • associer l’IP flottante à une instance,
  • créer un volume,
  • attacher le volume à l’instance,
  • redémarrer l’instance,
  • terminer l’instance.

Déclarer les informations d’identification :

OS_AUTH_URL, OS_USERNAME, OS_PASSWORD, OS_REGION_NAME and OS_TENANT_NAME se déclarent depuis ENVIRONEMENT ou peuvent être déclarés en ligne de commande.

	public static String loadPropertyFromEnv(String args[],
			BufferedReader reader, String propertyName, String defaultValue)
			throws IOException {
		String property = System.getenv(propertyName);
		if (property == null)
			property = defaultValue;
		for (String s : args) {
			if (s.startsWith(propertyName + "=")) {
				property = s.substring(propertyName.length() + 1);
			}
		}
		while (property == null) {
			System.err.print("\nPlease provide " + propertyName + ": ");
			System.err.flush();
			property = reader.readLine();
		}
		return property;
	}

Importer une paire de clés SSH :

La commande suivante vous permet d’importer une paire de clé SSH qui sera utilisée à la création de l’instance pour permettre un accès sans mot de passe à celle-ci.

	public void createKeyPair(String name, String path) throws IOException {
        KeyPairApi keypairApi = this.novaApi.getKeyPairApi(region).get();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(path));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            line = sb.toString();
            keypairApi.createWithPublicKey(name, line);
        } catch (IOException e) {
            System.out.println("ERROR::Given file path is not valid.");
        } finally {
            br.close();
        }
    }

Créer un réseau et un sous-réseau :

Cette commande permet de créer un réseau privé et un sous-réseau associé.

	 public String createNetwork(String name) {
        NetworkApi networkApi = neutronApi.getNetworkApi(region);
        Network network = networkApi.create(Network.CreateNetwork
                          .createBuilder(name).build());
        return network.getId();
    }

    public String createSubnet(String network, String cidr) {
        SubnetApi subnetApi = neutronApi.getSubnetApi(region);
        Subnet subnet = subnetApi.create(Subnet.CreateSubnet
                        .createBuilder(this.getNetworkId(network), cidr)
                        .ipVersion(4).build());
        return subnet.getId();
    }

Créer un routeur :

La commande suivante permet de créer un routeur.

	public String createRouter(String name) {
        RouterApi routerApi = neutronApi.getRouterApi(region).get();
        Router router = routerApi.create(Router.CreateRouter.createBuilder().name(name).build());
        return router.getId();
    }

Créer un groupe de sécurité :

La commande suivante permet de créer un groupe de sécurité.

	public String createSecurityGroup(String name, String description) {
        SecurityGroupApi securityGroupApi = novaApi.getSecurityGroupApi(region).get();
        SecurityGroup securityGroup = securityGroupApi.createWithDescription(
                name, description);
        return securityGroup.getId();
    }

Démarrer une instance :

Pour lancer une instance, vous devez déclarer le nom de celle-ci avec les autres champs obligatoires. Dans l’exemple ci-dessous sont déclarés l’image, le gabarit, la paire de clé SSH, le réseau, le groupe de sécurité et les données utilisateur.

	public String launch_instance(String name, String image, String flavor,
            String keypair, String network, Iterable<String> secGroup,
            String userData) {
        ServerApi serverApi = this.novaApi.getServerApi(region);
        CreateServerOptions options = CreateServerOptions.Builder
                .keyPairName(keypair).networks(this.getNetworkId(network))
                .securityGroupNames(secGroup).userData(userData.getBytes());
        ServerCreated ser = serverApi.create(name, this.getImageId(image),
                this.getFlavorId(flavor), options);
        return ser.getId();
    }

Allouer une IP flottante :

Cette commande vous permet de créer une IP flottante. Cette fonction va d’abord vérifier l’existence d’une IP disponible. Si aucune IP n’est libre, cela engendrera la création d’une nouvelle IP et un retour à l’étape de vérification.

	public String getOrCreateFloatingIP() {
		List<FloatingIP> freeIP = new LinkedList<FloatingIP>();
		FloatingIPApi floatingIPApi = this.novaApi
				.getFloatingIPExtensionForZone(this.defaultZone).get();
		Iterator<? extends FloatingIP> floatingIP = floatingIPApi.list()
				.iterator();
		while (floatingIP.hasNext()) {
			FloatingIP ip = floatingIP.next();
			if (ip.getInstanceId() == null) {
				freeIP.add(ip);
			}
		}
		if (freeIP.size() > 0) {
			return freeIP.get(0).getIp();
		} else {
			return floatingIPApi.create().getIp();
		}
	}

Associer une IP flottante à une instance :

Cette commande permet d’attacher une IP flotante à une instance.

	public void attachIP(String server) {
        FloatingIPApi floatingIPApi = this.novaApi.getFloatingIPApi(this.region).get();
        String ip_to_use;
        List<FloatingIP> freeIP = new LinkedList<FloatingIP>();
        Iterator<? extends FloatingIP> floatingIP = floatingIPApi.list().iterator();
        while (floatingIP.hasNext()) {
           FloatingIP ip = floatingIP.next();
           if (ip.getInstanceId() == null) {
               freeIP.add(ip);
           }
        }
        if (freeIP.size() > 0) {
           ip_to_use =  freeIP.get(0).getIp();
        }
        else {
            ip_to_use =  floatingIPApi.create().getIp();
        }
        floatingIPApi.addToServer(ip_to_use, this.getServerId(server));
    }

Créer un volume :

La commande suivante permet de créer un volume et d’obtenir son ID. Créer un volume requiert de déclarer un nom, une taille et d’autres paramètres. Par soucis de simplicité, l’exemple ci-dessous n’utilise que le nom et la taille du volume.

	public String createVolume(int size, String name) {
        VolumeApi volumeApi = this.cinderApi.getVolumeApi(region);
        Volume vol = volumeApi.create(size, CreateVolumeOptions.Builder.name(name));
        return vol.getId();
    }

Attacher le volume à une instance :

Cette commande permet d’attacher un volume à une instance. Le paramètre device est le nom du connecteur, en général “/dev/vd[b-z]”. Si l’utilisateur ne fournit pas le nom du connecteur, celui par défaut sera sélectionné.

	 public void attachVolume(String volume, String server, String device) {
        if (device == null)
            device = "";
        VolumeAttachmentApi volumeAttachmentApi = this.novaApi.getVolumeAttachmentApi(region).get();
        volumeAttachmentApi.attachVolumeToServerAsDevice(
                this.getVolumeId(volume), this.getServerId(server), device);
    }

    public void attachVolume(String volume, String server) {
        this.attachVolume(volume, server, "");
    }

Redémarrer une instance:

Attention : Le type de redémarrage (HARD/SOFT) doit être spécifié.

	public void rebootServer(String server, RebootType type) {
        ServerApi serverApi = this.novaApi.getServerApi(region);
        serverApi.reboot(this.getServerId(server), type);
    }

Terminer une instance :

La commande suivante permet de terminer/supprimer l’instance :

	public void deleteServer(String server) {
        ServerApi serverApi = this.novaApi.getServerApi(region);
        serverApi.delete(this.getServerId(server));
    }

Fonction utile pour récupérer les IDs des ressources :

Pour accéder à des informations sur une ressource (SERVER, IMAGE, FLAVOR…) ou en transmettre via une API vous devez déclarer l’ID de la ressource en question (RESOURCE). L’utilisateur peut retrouver cette ID en fournissant le nom de la ressource sollicité grâce aux commandes suivantes :

	public String getServerId(String serverName) {
        ServerApi serverApi = this.novaApi.getServerApi(region);
        try {
            Server serverObj = serverApi.get(serverName);
            return serverObj.getId();
        } catch (NullPointerException e) {
            for (Resource s : serverApi.list().concat()) {
                if (s.getName().equalsIgnoreCase(serverName))
                    return s.getId();
            }
        }
        throw new NullPointerException("Server not found");
    }

     public String getServerStatus(String serverName) {
        ServerApi serverApi = this.novaApi.getServerApi(region);
        Server server = serverApi.get(this.getServerId(serverName));
        return server.getStatus().name();
    }

    public String getNetworkId(String networkName) {
        NetworkApi networkApi = this.neutronApi.getNetworkApi(region);
        try {
            Network networkObj = networkApi.get(networkName);
            return networkObj.getId();
        } catch (NullPointerException e) {
            for (Network n : networkApi.list().concat()) {
                if (n.getName().equalsIgnoreCase(networkName))
                    return n.getId();
            }
        }
        throw new NullPointerException("Server not found");
    }


    public String getImageId(String imageName) {
        ImageApi imageApi = this.novaApi.getImageApi(region);
        try {
            Image imageObj = imageApi.get(imageName);
            return imageObj.getId();
        } catch (NullPointerException e) {
            for (Resource i : imageApi.list().concat()) {
                if (i.getName().equalsIgnoreCase(imageName))
                    return i.getId();
            }
        }
        throw new NullPointerException("Image not found");
    }

    public String getFlavorId(String flavorName) {
        FlavorApi flavorApi = this.novaApi.getFlavorApi(region);
        try {
            Flavor flavorObj = flavorApi.get(flavorName);
            return flavorObj.getId();
        } catch (NullPointerException e) {
            for (Resource f : flavorApi.list().concat()) {
                if (f.getName().equalsIgnoreCase(flavorName))
                    return f.getId();
            }
        }
        throw new NullPointerException("Flavor not found");
    }

    public String getVolumeId(String volumeName) {
        VolumeApi volumeApi = this.cinderApi.getVolumeApi(region);;
        try {
            Volume volumeObj = volumeApi.get(volumeName);
            return volumeObj.getId();
        } catch (NullPointerException e) {
            Iterator<? extends Volume> volumeList = volumeApi.list().iterator();
            while (volumeList.hasNext()) {
                Volume v = volumeList.next();
                if (v.getName().equalsIgnoreCase(volumeName))
                    return v.getId();
            }
        }
        throw new NullPointerException("Volume not Found");
    }

    public String getSecurityGroupId(String sgName) {
        SecurityGroupApi securityGroupApi = novaApi.getSecurityGroupApi(region).get();
        try {
            SecurityGroup securityGroup = securityGroupApi.get(sgName);
            return securityGroup.getId();
        } catch (Exception e) {
            Iterator<? extends SecurityGroup> sgList = securityGroupApi.list()
                    .iterator();
            while (sgList.hasNext()) {
                SecurityGroup group = sgList.next();
                if (group.getName().equalsIgnoreCase(sgName))
                    return group.getId();
            }
        }
        throw new NullPointerException("Security Group not found");
    }

    public String getRouterId(String routerName) {
		RouterApi routerApi = this.neutronApi.getRouterApi(region).get();
		try {
			Router routerObj = routerApi.get(routerName);
			return routerObj.getId();
		} catch (NullPointerException e) {

			for (Router r : routerApi.list().concat()) {
				if (r.getName().equalsIgnoreCase(routerName))
					return r.getId();
			}
		}
		throw new NullPointerException("network not Found");
	}

Fonction utile pour nettoyer l’environement de travail et supprimer les ressources crées des ressources :

	public boolean deleteKeyPair(String keyName) throws NullPointerException {
		try {
			KeyPairApi keypairApi = this.novaApi.getKeyPairApi(region).get();
			return keypairApi.delete(keyName);
		} catch (NullPointerException e) {
		    System.out.println("The provided KeyPair can not be found");
		}
		return false;

	}

	public boolean deleteSG(String sgName) throws NullPointerException {
		try {
			SecurityGroupApi sgApi = this.novaApi.getSecurityGroupApi(region).get();
			return sgApi.delete(getSecurityGroupId(sgName));
		} catch (NullPointerException e) {
		    System.out.println("The provided SecGroup can not be found");
		}
		return false;

	}

	public boolean deleteVolume(String volumeName) throws NullPointerException {
		try {
			VolumeApi volumeApi = this.cinderApi.getVolumeApi(region);
			return volumeApi.delete(getVolumeId(volumeName));
		} catch (NullPointerException e) {
		    System.out.println("The provided Volume can not be found");
		}
		return false;

	}

	public boolean deleteNetworkRessources(String networkName, String routerName) throws NullPointerException {
		try {
			NetworkApi networkApi = this.neutronApi.getNetworkApi(region);
			RouterApi routerApi = this.neutronApi.getRouterApi(region).get();
			return networkApi.delete(getNetworkId(networkName)) && routerApi.delete(getRouterId(routerName));
		} catch (NullPointerException e) {
		    System.out.println("The provided Network or router can not be found");
		}
		return false;

	}

Exemple d’utilisation de cette fonction :

	public static void main(String[] args) throws IOException {
        OpenstackClient client;
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        String username = OpenstackClient.loadPropertyFromEnv(args, reader,
                "OS_USERNAME", null);
        String password = OpenstackClient.loadPropertyFromEnv(args, reader,
                "OS_PASSWORD", null);
        String authUrl = OpenstackClient.loadPropertyFromEnv(args, reader,
                "OS_AUTH_URL", null);
        String tenantName = OpenstackClient.loadPropertyFromEnv(args, reader,
                "OS_TENANT_NAME", null);
        String region = OpenstackClient.loadPropertyFromEnv(args, reader,
                "OS_REGION_NAME", null);

        String keyName = "jckey";
        client = new OpenstackClient(username, password, tenantName, authUrl, region);
        client.createKeyPair(keyName, "/home/masco/masco_id_rsa.pub");
        client.createSecurityGroup("mySecGroup", "this is discription");
        String nw = client.createNetwork("jcnetwork");
        client.createSubnet(nw, "192.168.199.0/24");
        client.createRouter("jcloudRouter");
        HashSet<String> secGroup = new HashSet<String>();
        secGroup.add(client.getSecurityGroupId("default"));
        String volume = client.createVolume(1, "jcVolume");
        String s = client.launch_instance("jcinstance", "CentOS 6.5",
                "s1.cw.small-1", keyName, nw, secGroup, "Simple User Data");
        /*
         * sleep for some time so the instance will be ready so we can attach
         * the ip and volume.
         */
        try {
            while(!client.getServerStatus(s).equals("ACTIVE")) {
                Thread.sleep(15000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        client.attachIP(s);
        client.attachVolume(volume, s);
        client.rebootServer(s, RebootType.SOFT);
        client.deleteServer(s);
        client.deleteKeyPair(keyName);
		client.deleteSG("mySecGroup");
		client.deleteVolume("jcVolume");
		client.deleteNetworkRessources("jcnetwork", "jcloudRouter");


    }

Le code complet de l’exemple :

package com.cloudwatt.openstack.jcloud;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.jclouds.Constants;
import org.jclouds.ContextBuilder;
import org.jclouds.collect.PagedIterable;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import  org.jclouds.openstack.cinder.v1.CinderApi;
import  org.jclouds.openstack.cinder.v1.domain.Volume;
import  org.jclouds.openstack.cinder.v1.features.VolumeApi;
import  org.jclouds.openstack.cinder.v1.options.CreateVolumeOptions;
import org.jclouds.openstack.keystone.v2_0.config.CredentialTypes;
import org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties;
import org.jclouds.openstack.neutron.v2.NeutronApi;
import org.jclouds.openstack.neutron.v2.domain.Network;
import org.jclouds.openstack.neutron.v2.domain.Router;
import org.jclouds.openstack.neutron.v2.domain.Subnet;
import org.jclouds.openstack.neutron.v2.extensions.RouterApi;
import org.jclouds.openstack.neutron.v2.features.NetworkApi;
import org.jclouds.openstack.neutron.v2.features.SubnetApi;
import org.jclouds.openstack.nova.v2_0.NovaApi;
import org.jclouds.openstack.nova.v2_0.domain.Flavor;
import org.jclouds.openstack.nova.v2_0.domain.FloatingIP;
import org.jclouds.openstack.nova.v2_0.domain.Image;
import org.jclouds.openstack.nova.v2_0.domain.RebootType;
import org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;
import org.jclouds.openstack.nova.v2_0.domain.Server;
import org.jclouds.openstack.nova.v2_0.domain.ServerCreated;
import org.jclouds.openstack.nova.v2_0.extensions.FloatingIPApi;
import org.jclouds.openstack.nova.v2_0.extensions.KeyPairApi;
import org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi;
import org.jclouds.openstack.nova.v2_0.extensions.VolumeAttachmentApi;
import org.jclouds.openstack.nova.v2_0.features.FlavorApi;
import org.jclouds.openstack.nova.v2_0.features.ImageApi;
import org.jclouds.openstack.nova.v2_0.features.ServerApi;
import org.jclouds.openstack.nova.v2_0.options.CreateServerOptions;
import org.jclouds.openstack.v2_0.domain.Resource;
import org.jclouds.rest.internal.BaseHttpApiMetadata;


import com.google.common.collect.ImmutableSet;
import com.google.inject.Module;

public class Cloudwatt {
    public static void main(String[] args) throws IOException {
        OpenstackClient client;
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        String username = OpenstackClient.loadPropertyFromEnv(args, reader,
                "OS_USERNAME", null);
        String password = OpenstackClient.loadPropertyFromEnv(args, reader,
                "OS_PASSWORD", null);
        String authUrl = OpenstackClient.loadPropertyFromEnv(args, reader,
                "OS_AUTH_URL", null);
        String tenantName = OpenstackClient.loadPropertyFromEnv(args, reader,
                "OS_TENANT_NAME", null);
        String region = OpenstackClient.loadPropertyFromEnv(args, reader,
                "OS_REGION_NAME", null);
        /*
         * String user = "masco.kaliyamoorthy@enovance.com"; String password =
         * "Masvandayar@003"; String tenant =
         * "e2614ec6-8a63-11e3-b8f7-525400872571"; String url =
         * "https://identity.fr1.cloudwatt.com/v2.0/";
         */
        String keyName = "jckey";
        client = new OpenstackClient(username, password, tenantName, authUrl, region);
        client.createKeyPair(keyName, "/home/masco/masco_id_rsa.pub");
        client.createSecurityGroup("mySecGroup", "this is discription");
        String nw = client.createNetwork("jcnetwork");
        client.createSubnet(nw, "192.168.199.0/24");
        client.createRouter("jcloudRouter");
        HashSet<String> secGroup = new HashSet<String>();
        secGroup.add(client.getSecurityGroupId("default"));
        String volume = client.createVolume(1, "jcVolume");
        String s = client.launch_instance("jcinstance", "CentOS 6.5",
                "s1.cw.small-1", keyName, nw, secGroup, "Simple User Data");
        /*
         * sleep for some time so the instance will be ready so we can attach
         * the ip and volume.
         */
        try {
            while(!client.getServerStatus(s).equals("ACTIVE")) {
                Thread.sleep(15000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        client.attachIP(s);
        client.attachVolume(volume, s);
        client.rebootServer(s, RebootType.SOFT);
        client.deleteServer(s);
        client.deleteKeyPair(keyName);
		client.deleteSG("mySecGroup");
		client.deleteVolume("jcVolume");
		client.deleteNetworkRessources("jcnetwork", "jcloudRouter");
    }
}

class OpenstackClient {
    private final NovaApi novaApi;
    private final NeutronApi neutronApi;
    private final CinderApi cinderApi;
    private String region;

    public OpenstackClient(String user, String password, String tenant,
            String url, String region ) {
        this.region = region;
        Iterable<Module> modules = ImmutableSet
                .<Module> of(new SLF4JLoggingModule());
        Properties overrides = new Properties();
        overrides.setProperty(KeystoneProperties.CREDENTIAL_TYPE,
                CredentialTypes.PASSWORD_CREDENTIALS);
        overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
        overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");

        Properties cinderOverrides = BaseHttpApiMetadata.defaultProperties();
        cinderOverrides.setProperty(KeystoneProperties.SERVICE_TYPE, "volumev2");
        cinderOverrides.setProperty(KeystoneProperties.CREDENTIAL_TYPE,
                CredentialTypes.PASSWORD_CREDENTIALS);
        cinderOverrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
        cinderOverrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");

        novaApi = ContextBuilder.newBuilder("openstack-nova").endpoint(url)
                .credentials(tenant + ":" + user, password).modules(modules)
                .overrides(overrides).buildApi(NovaApi.class);
        neutronApi = ContextBuilder.newBuilder("openstack-neutron")
                .endpoint(url).credentials(tenant + ":" + user, password)
                .modules(modules).overrides(overrides)
                .buildApi(NeutronApi.class);
        cinderApi = ContextBuilder.newBuilder("openstack-cinder")
                .endpoint(url).credentials(tenant + ":" + user, password)
                .modules(modules).overrides(cinderOverrides)
                .buildApi(CinderApi.class);
    }

    public static String loadPropertyFromEnv(String args[],
            BufferedReader reader, String propertyName, String defaultValue)
            throws IOException {
        String property = System.getenv(propertyName);
        if (property == null)
            property = defaultValue;
        for (String s : args) {
            if (s.startsWith(propertyName + "=")) {
                property = s.substring(propertyName.length() + 1);
            }
        }
        while (property == null) {
            System.err.print("\nPlease provide " + propertyName + ": ");
            System.err.flush();
            property = reader.readLine();
        }
        return property;
    }

    public void createKeyPair(String name, String path) throws IOException {
        KeyPairApi keypairApi = this.novaApi.getKeyPairApi(region).get();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(path));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            line = sb.toString();
            keypairApi.createWithPublicKey(name, line);
        } catch (IOException e) {
            System.out.println("ERROR::Given file path is not valid.");
        } finally {
            br.close();
        }
    }

    public String createNetwork(String name) {
        NetworkApi networkApi = neutronApi.getNetworkApi(region);
        Network network = networkApi.create(Network.CreateNetwork
                          .createBuilder(name).build());
        return network.getId();
    }

    public String createSubnet(String network, String cidr) {
        SubnetApi subnetApi = neutronApi.getSubnetApi(region);
        Subnet subnet = subnetApi.create(Subnet.CreateSubnet
                        .createBuilder(this.getNetworkId(network), cidr)
                        .ipVersion(4).build());
        return subnet.getId();
    }

    public String createRouter(String name) {
        RouterApi routerApi = neutronApi.getRouterApi(region).get();
        Router router = routerApi.create(Router.CreateRouter.createBuilder().name(name).build());
        return router.getId();
    }

    public String createSecurityGroup(String name, String description) {
        SecurityGroupApi securityGroupApi = novaApi.getSecurityGroupApi(region).get();
        SecurityGroup securityGroup = securityGroupApi.createWithDescription(
                name, description);
        return securityGroup.getId();
    }

    public void attachIP(String server) {
        FloatingIPApi floatingIPApi = this.novaApi.getFloatingIPApi(this.region).get();
        String ip_to_use;
        List<FloatingIP> freeIP = new LinkedList<FloatingIP>();
        Iterator<? extends FloatingIP> floatingIP = floatingIPApi.list().iterator();
        while (floatingIP.hasNext()) {
           FloatingIP ip = floatingIP.next();
           if (ip.getInstanceId() == null) {
               freeIP.add(ip);
           }
        }
        if (freeIP.size() > 0) {
           ip_to_use =  freeIP.get(0).getIp();
        }
        else {
            ip_to_use =  floatingIPApi.create().getIp();
        }
        floatingIPApi.addToServer(ip_to_use, this.getServerId(server));
    }

    public String createVolume(int size, String name) {
        VolumeApi volumeApi = this.cinderApi.getVolumeApi(region);
        Volume vol = volumeApi.create(size, CreateVolumeOptions.Builder.name(name));
        return vol.getId();
    }

    public void attachVolume(String volume, String server, String device) {
        if (device == null)
            device = "";
        VolumeAttachmentApi volumeAttachmentApi = this.novaApi.getVolumeAttachmentApi(region).get();
        volumeAttachmentApi.attachVolumeToServerAsDevice(
                this.getVolumeId(volume), this.getServerId(server), device);
    }

    public void attachVolume(String volume, String server) {
        this.attachVolume(volume, server, "");
    }

    public String launch_instance(String name, String image, String flavor,
            String keypair, String network, Iterable<String> secGroup,
            String userData) {
        ServerApi serverApi = this.novaApi.getServerApi(region);
        CreateServerOptions options = CreateServerOptions.Builder
                .keyPairName(keypair).networks(this.getNetworkId(network))
                .securityGroupNames(secGroup).userData(userData.getBytes());
        ServerCreated ser = serverApi.create(name, this.getImageId(image),
                this.getFlavorId(flavor), options);
        return ser.getId();
    }

    public void rebootServer(String server, RebootType type) {
        ServerApi serverApi = this.novaApi.getServerApi(region);
        serverApi.reboot(this.getServerId(server), type);
    }

    public void deleteServer(String server) {
        ServerApi serverApi = this.novaApi.getServerApi(region);
        serverApi.delete(this.getServerId(server));
    }

    public String getServerId(String serverName) {
        ServerApi serverApi = this.novaApi.getServerApi(region);
        try {
            Server serverObj = serverApi.get(serverName);
            return serverObj.getId();
        } catch (NullPointerException e) {
            for (Resource s : serverApi.list().concat()) {
                if (s.getName().equalsIgnoreCase(serverName))
                    return s.getId();
            }
        }
        throw new NullPointerException("Server not found");
    }

     public String getServerStatus(String serverName) {
        ServerApi serverApi = this.novaApi.getServerApi(region);
        Server server = serverApi.get(this.getServerId(serverName));
        return server.getStatus().name();
    }

    public String getNetworkId(String networkName) {
        NetworkApi networkApi = this.neutronApi.getNetworkApi(region);
        try {
            Network networkObj = networkApi.get(networkName);
            return networkObj.getId();
        } catch (NullPointerException e) {
            for (Network n : networkApi.list().concat()) {
                if (n.getName().equalsIgnoreCase(networkName))
                    return n.getId();
            }
        }
        throw new NullPointerException("Server not found");
    }


    public String getImageId(String imageName) {
        ImageApi imageApi = this.novaApi.getImageApi(region);
        try {
            Image imageObj = imageApi.get(imageName);
            return imageObj.getId();
        } catch (NullPointerException e) {
            for (Resource i : imageApi.list().concat()) {
                if (i.getName().equalsIgnoreCase(imageName))
                    return i.getId();
            }
        }
        throw new NullPointerException("Image not found");
    }

    public String getFlavorId(String flavorName) {
        FlavorApi flavorApi = this.novaApi.getFlavorApi(region);
        try {
            Flavor flavorObj = flavorApi.get(flavorName);
            return flavorObj.getId();
        } catch (NullPointerException e) {
            for (Resource f : flavorApi.list().concat()) {
                if (f.getName().equalsIgnoreCase(flavorName))
                    return f.getId();
            }
        }
        throw new NullPointerException("Flavor not found");
    }

    public String getVolumeId(String volumeName) {
        VolumeApi volumeApi = this.cinderApi.getVolumeApi(region);;
        try {
            Volume volumeObj = volumeApi.get(volumeName);
            return volumeObj.getId();
        } catch (NullPointerException e) {
            Iterator<? extends Volume> volumeList = volumeApi.list().iterator();
            while (volumeList.hasNext()) {
                Volume v = volumeList.next();
                if (v.getName().equalsIgnoreCase(volumeName))
                    return v.getId();
            }
        }
        throw new NullPointerException("Volume not Found");
    }

    public String getSecurityGroupId(String sgName) {
        SecurityGroupApi securityGroupApi = novaApi.getSecurityGroupApi(region).get();
        try {
            SecurityGroup securityGroup = securityGroupApi.get(sgName);
            return securityGroup.getId();
        } catch (Exception e) {
            Iterator<? extends SecurityGroup> sgList = securityGroupApi.list()
                    .iterator();
            while (sgList.hasNext()) {
                SecurityGroup group = sgList.next();
                if (group.getName().equalsIgnoreCase(sgName))
                    return group.getId();
            }
        }
        throw new NullPointerException("Security Group not found");
    }

    public String getRouterId(String routerName) {
		RouterApi routerApi = this.neutronApi.getRouterApi(region).get();
		try {
			Router routerObj = routerApi.get(routerName);
			return routerObj.getId();
		} catch (NullPointerException e) {

			for (Router r : routerApi.list().concat()) {
				if (r.getName().equalsIgnoreCase(routerName))
					return r.getId();
			}
		}
		throw new NullPointerException("network not Found");
	}

	public boolean deleteKeyPair(String keyName) throws NullPointerException {
		try {
			KeyPairApi keypairApi = this.novaApi.getKeyPairApi(region).get();
			return keypairApi.delete(keyName);
		} catch (NullPointerException e) {
		    System.out.println("The provided KeyPair can not be found");
		}
		return false;

	}

	public boolean deleteSG(String sgName) throws NullPointerException {
		try {
			SecurityGroupApi sgApi = this.novaApi.getSecurityGroupApi(region).get();
			return sgApi.delete(getSecurityGroupId(sgName));
		} catch (NullPointerException e) {
		    System.out.println("The provided SecGroup can not be found");
		}
		return false;

	}

	public boolean deleteVolume(String volumeName) throws NullPointerException {
		try {
			VolumeApi volumeApi = this.cinderApi.getVolumeApi(region);
			return volumeApi.delete(getVolumeId(volumeName));
		} catch (NullPointerException e) {
		    System.out.println("The provided Volume can not be found");
		}
		return false;

	}

	public boolean deleteNetworkRessources(String networkName, String routerName) throws NullPointerException {
		try {
			NetworkApi networkApi = this.neutronApi.getNetworkApi(region);
			RouterApi routerApi = this.neutronApi.getRouterApi(region).get();
			return networkApi.delete(getNetworkId(networkName)) && routerApi.delete(getRouterId(routerName));
		} catch (NullPointerException e) {
		    System.out.println("The provided Network or router can not be found");
		}
		return false;

	}
}