com.liberologico.cloudesire.gce.ComputeSample.java Source code

Java tutorial

Introduction

Here is the source code for com.liberologico.cloudesire.gce.ComputeSample.java

Source

/*
 * Copyright (c) 2013 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.liberologico.cloudesire.gce;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.ComputeScopes;
import com.google.api.services.compute.model.AccessConfig;
import com.google.api.services.compute.model.AttachedDisk;
import com.google.api.services.compute.model.AttachedDiskInitializeParams;
import com.google.api.services.compute.model.Disk;
import com.google.api.services.compute.model.Firewall;
import com.google.api.services.compute.model.Firewall.Allowed;
import com.google.api.services.compute.model.Image;
import com.google.api.services.compute.model.ImageList;
import com.google.api.services.compute.model.Instance;
import com.google.api.services.compute.model.MachineType;
import com.google.api.services.compute.model.MachineTypeList;
import com.google.api.services.compute.model.Network;
import com.google.api.services.compute.model.NetworkInterface;
import com.google.api.services.compute.model.Operation;
import com.google.api.services.compute.model.Scheduling;
import com.google.api.services.compute.model.Tags;

/**
 * Main class for the Compute Engine API command line sample. Demonstrates how
 * to make an authenticated API call using OAuth 2 helper classes.
 */
public class ComputeSample {

    /**
     * Be sure to specify the name of your application. If the application name
     * is {@code null} or blank, the application will log a warning. Suggested
     * format is "MyCompany-ProductName/1.0".
     */
    private static final String APPLICATION_NAME = "Liberologico-ClouDesireTest/01";

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport httpTransport;

    private static Compute client;
    private static String SERVICE_ACCOUNT_ID = "";
    private static String PROJECT_NAME = "";
    private static String SERVICE_ACCOUNT_PRIVATE_KEY_PATH = "/google_service_account_private_key.p12";
    private static String ZONE = "europe-west1-a";

    private static String DEB7_IMAGE = "backports-debian-7-wheezy-v20140318";

    private static String PROJECT_DEBIAN = "debian-cloud";

    private static String MACHINE_TYPE = "f1-micro";

    public static void main(String[] args) {
        try {
            // initialize the transport
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();

            // authorization
            Credential credential = authorize();

            // set up global Compute instance
            client = new Compute.Builder(httpTransport, JSON_FACTORY, credential)
                    .setApplicationName(APPLICATION_NAME).build();

            System.out.println("Success! Now add code here.");

            // List<Instance> items = client.instances().list(PROJECT_NAME,
            // ZONE).execute().getItems();
            // for (Instance instance : items)
            // {
            // System.out.println(instance.toPrettyString());
            // }
            // RegionList regions =
            // client.regions().list(PROJECT_NAME).execute();
            // System.out.println(regions.toPrettyString());

            // AddressList addressList = client.addresses()
            // .list(PROJECT_NAME, Regions.EUROPE_WEST).execute();
            // System.out.println(addressList.toPrettyString());

            // AddressAggregatedList aggregatedList = client.addresses()
            // .aggregatedList(PROJECT_NAME).execute();
            // System.out.println(aggregatedList.toPrettyString());

            // Instance instance = client.instances()
            // .get(PROJECT_NAME, ZONE, "test009").execute();
            // System.out.println(instance.toPrettyString());

            // Region regionUS = client.regions()
            // .get(PROJECT_NAME, Regions.US_CENTRAL).execute();
            // System.out.println(regionUS.toPrettyString());

            // Region regionEU = client.regions()
            // .get(PROJECT_NAME, Regions.EUROPE_WEST).execute();
            // System.out.println(regionEU.toPrettyString());
            //
            // Zone zoneEU1 = client.zones().get(PROJECT_NAME, ZONE).execute();
            // System.out.println(zoneEU1.toPrettyString());

            // createVM("test009", 10L);
            // createDisk("dtest07", 10L);
            // attachDisk("test07", "dtest07");
            // deleteVM("test009");
            // createNetwork("test01");
            // deleteNetwork("test009-network");
            // getValidImages(PROJECT_DEBIAN, "backports-debian-7-wheezy");
            // getValidMachineTypes(PROJECT_NAME, ZONE);

            // Instance instance = client.instances()
            // .get(PROJECT_NAME, ZONE, "test007").execute();
            // System.out.println(instance.toPrettyString());
            // List<String> tags = instance.getTags().getItems();
            // tags.add("pippo-geronimo-pasticcio");
            // setInstanceTags("test007", tags);
            // Network network = client.networks()
            // .get(PROJECT_NAME, "test01-network").execute();
            // System.out.println(network.toPrettyString());
            // Firewall firewall = client.firewalls()
            // .get(PROJECT_NAME, "test01-firewall").execute();
            // System.out.println(firewall.toPrettyString());
            // DiskList diskList = client.disks().list(PROJECT_NAME, ZONE)
            // .execute();
            // if (diskList == null)
            // System.out.println("diskList is null");
            // else if (diskList.getItems() == null)
            // System.out.println("diskList.getItems() returns null");
            // else
            // for (Disk d : diskList.getItems())
            // System.out.println(d.toPrettyString());

            // try {
            // Network network = client.networks().get(PROJECT_NAME, "pippo")
            // .execute();
            // } catch (Exception e) {
            // System.out.println(e.getMessage());
            // }
            // NetworkList networkList = client.networks().list(PROJECT_NAME)
            // .execute();
            // if (networkList == null)
            // System.out.println("networkList is null");
            // else
            // for (Network net : networkList.getItems())
            // System.out.println(net.toPrettyString());
            //
            // FirewallList firewallList = client.firewalls().list(PROJECT_NAME)
            // .execute();
            // for (Firewall fw : firewallList.getItems()) {
            // System.out.println(getResourceNameFromUrl(fw.getNetwork()));
            // }

        } catch (IOException e) {
            System.err.println(e.getMessage());
        } catch (Throwable t) {
            t.printStackTrace();
        }
        System.exit(1);
    }

    private static void attachDisk(String vmName, String diskName) throws Exception {
        Disk disk = client.disks().get(PROJECT_NAME, ZONE, diskName).execute();
        if (disk == null) {
            System.out.println("Cannot find disk:" + diskName);
            return;
        }
        System.out.println(disk.toPrettyString());
        Instance vm = client.instances().get(PROJECT_NAME, ZONE, vmName).execute();
        if (vm == null) {
            System.out.println("Cannot find instance:" + vmName);
            return;
        }

        // dico alla VM come deve usare il disco
        AttachedDisk attDisk = new AttachedDisk().setType("PERSISTENT").setAutoDelete(Boolean.TRUE)
                .setMode("READ_WRITE").setSource(disk.getSelfLink());
        // attacco il disco
        Operation attachDisk = client.instances().attachDisk(PROJECT_NAME, ZONE, vmName, attDisk).execute();
        System.out.println(attachDisk.toPrettyString());

        while (!attachDisk.getStatus().equals("DONE")) {
            Thread.sleep(2000);
            attachDisk = client.zoneOperations().get(PROJECT_NAME, ZONE, attachDisk.getName()).execute();
            System.out.println("PROGRESS:" + attachDisk.getProgress());
            System.out.println("STATUS:" + attachDisk.getStatus());
        }

    }

    /** Authorizes the installed application to access user's protected data. */
    private static Credential authorize() throws Exception {

        Set<String> scopes = new HashSet<String>();
        scopes.add(ComputeScopes.COMPUTE + " " + ComputeScopes.DEVSTORAGE_FULL_CONTROL);
        // scopes.add(ComputeScopes.COMPUTE);
        // scopes.add(ComputeScopes.COMPUTE_READONLY);
        // scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
        // scopes.add(ComputeScopes.DEVSTORAGE_READ_ONLY);
        // scopes.add(ComputeScopes.DEVSTORAGE_READ_WRITE);

        // KeyStore ks = KeyStore.getInstance("PKCS12");
        // InputStream stream = Thread.currentThread().getContextClassLoader()
        // .getResourceAsStream("google_service_account_private_key.p12");
        // if (stream == null) {
        // log.error("Cannot find service account private key");
        // throw new IllegalArgumentException(
        // "Cannot find service account private key");
        // }
        // ks.load(stream, "notasecret".toCharArray());
        //
        // PrivateKeyEntry entry = (PrivateKeyEntry) ks.getEntry(ks.aliases()
        // .nextElement(),
        // new PasswordProtection("notasecret".toCharArray()));
        // GoogleCredential credential = new GoogleCredential.Builder()
        // .setTransport(httpTransport)
        // .setJsonFactory(JSON_FACTORY)
        // .setServiceAccountId(
        // "1018123978583-6d4kl0d8fbb2fveqardv2rn3blubkria@developer.gserviceaccount.com")
        // .setServiceAccountScopes(scopes)
        // .setServiceAccountPrivateKey(entry.getPrivateKey()).build();

        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(JSON_FACTORY).setServiceAccountId(SERVICE_ACCOUNT_ID)
                .setServiceAccountScopes(scopes)
                .setServiceAccountPrivateKeyFromP12File(new File(SERVICE_ACCOUNT_PRIVATE_KEY_PATH)).build();

        return credential;
    }

    private static void createDisk(String diskName, long sizeGb) throws Exception {
        Disk disk = new Disk().setName(diskName).setSizeGb(sizeGb);
        // creo il disco nuovo
        Operation iDiskOp = client.disks().insert(PROJECT_NAME, ZONE, disk).execute();
        System.out.println(iDiskOp.toPrettyString());

        while (!iDiskOp.getStatus().equals("DONE")) {
            Thread.sleep(2000);
            iDiskOp = client.zoneOperations().get(PROJECT_NAME, ZONE, iDiskOp.getName()).execute();
            System.out.println("PROGRESS:" + iDiskOp.getProgress());
            System.out.println("STATUS:" + iDiskOp.getStatus());
        }
        disk = client.disks().get(PROJECT_NAME, ZONE, diskName).execute();
        System.out.println(disk.toPrettyString());
    }

    private static NetworkInterface createNetwork(String vmName) throws Exception {
        Network network = new Network();
        network.setName(vmName + "-network");
        network.setIPv4Range("10.240.0.0/16");
        Operation cNetworkop = client.networks().insert(PROJECT_NAME, network).execute();
        System.out.println(cNetworkop.toPrettyString());
        while (!cNetworkop.getStatus().equals("DONE")) {
            Thread.sleep(2000);
            cNetworkop = client.globalOperations().get(PROJECT_NAME, cNetworkop.getName()).execute();
            System.out.println("PROGRESS:" + cNetworkop.getProgress());
            System.out.println("STATUS:" + cNetworkop.getStatus());
        }

        network = client.networks().get(PROJECT_NAME, vmName + "-network").execute();
        Allowed allowed = new Allowed();
        allowed.setIPProtocol("tcp");
        allowed.setPorts(new ArrayList<String>(Arrays.asList("22", "80", "8080")));
        Firewall firewall = new Firewall().setName(vmName + "-firewall");
        firewall.setSourceRanges(new ArrayList<String>(Arrays.asList("0.0.0.0/0")));
        firewall.setAllowed(new ArrayList<Allowed>(Arrays.asList(allowed)));
        firewall.setNetwork(network.getSelfLink());

        Operation executeOp = client.firewalls().insert(PROJECT_NAME, firewall).execute();
        System.out.println(executeOp.toPrettyString());
        while (!executeOp.getStatus().equals("DONE")) {
            Thread.sleep(2000);
            executeOp = client.globalOperations().get(PROJECT_NAME, executeOp.getName()).execute();
            System.out.println("PROGRESS:" + executeOp.getProgress());
            System.out.println("STATUS:" + executeOp.getStatus());
        }

        return new NetworkInterface().setNetwork(network.getSelfLink());
    }

    private static void createVM(String vmName, long sizeGb) throws Exception {
        Instance instance = new Instance().setName(vmName);

        // recupero l'immagine con il SO
        Image deb7 = client.images().get(PROJECT_DEBIAN, DEB7_IMAGE).execute();
        System.out.println(deb7.toPrettyString());
        // gli dico di fare un disco bootabile con l'immagine recuperata prima
        AttachedDiskInitializeParams iParams = new AttachedDiskInitializeParams();
        iParams.setDiskName(vmName).setDiskSizeGb(sizeGb).setSourceImage(deb7.getSelfLink());
        AttachedDisk attDisk = new AttachedDisk().setBoot(true).setType("PERSISTENT").setAutoDelete(Boolean.TRUE)
                .setMode("READ_WRITE").setInitializeParams(iParams);
        instance.setDisks(new ArrayList<AttachedDisk>(Arrays.asList(attDisk)));

        // recupero le informazioni per il tipo di macchina scelta
        // (MACHINE_TYPE)
        MachineType machineType = client.machineTypes().get(PROJECT_NAME, ZONE, MACHINE_TYPE).execute();
        System.out.println(machineType.toPrettyString());
        instance.setMachineType(machineType.getSelfLink());

        // recupero la configurazione di rete di default per il progetto
        // Network network = client.networks().get(PROJECT_NAME, "default")
        // .execute();
        // System.out.println(network.toPrettyString());
        // configurazione di rete di default
        // NetworkInterface networkInterface = new NetworkInterface()
        // .setNetwork(network.getSelfLink());

        // configurazione di rete custom
        NetworkInterface networkInterface = createNetwork(vmName);

        // gli dico di settare un ip dinamico
        AccessConfig accessConfig = new AccessConfig();

        // static ip, bisogna prima creare la risorsa (POST su adresses())
        // accessConfig.setNatIP(adresses.getSelfLink());

        accessConfig.setType("ONE_TO_ONE_NAT");

        // configurazione di rete dell'istanza
        networkInterface.setAccessConfigs(new ArrayList<AccessConfig>(Arrays.asList(accessConfig)));
        instance.setCanIpForward(false)
                .setNetworkInterfaces(new ArrayList<NetworkInterface>(Arrays.asList(networkInterface)));

        // informazioni accessorie obbligatorie
        Scheduling scheduling = new Scheduling();
        scheduling.setAutomaticRestart(true);
        scheduling.setOnHostMaintenance("MIGRATE");
        instance.setScheduling(scheduling);

        // creo la vm
        Operation createInstance = client.instances().insert(PROJECT_NAME, ZONE, instance).execute();
        System.out.println(createInstance.toPrettyString());

        while (!createInstance.getStatus().equals("DONE")) {
            Thread.sleep(2000);
            createInstance = client.zoneOperations().get(PROJECT_NAME, ZONE, createInstance.getName()).execute();
            System.out.println("PROGRESS:" + createInstance.getProgress());
            System.out.println("STATUS:" + createInstance.getStatus());
        }
    }

    private static void deleteNetwork(String vmName) throws Exception {
        Operation deleteFirewall = client.firewalls().delete(PROJECT_NAME, vmName + "-firewall").execute();
        System.out.println(deleteFirewall.toPrettyString());
        while (!deleteFirewall.getStatus().equals("DONE")) {
            Thread.sleep(2000);
            deleteFirewall = client.globalOperations().get(PROJECT_NAME, deleteFirewall.getName()).execute();
            System.out.println("PROGRESS:" + deleteFirewall.getProgress());
            System.out.println("STATUS:" + deleteFirewall.getStatus());
        }
        Operation deleteNetworkOp = client.networks().delete(PROJECT_NAME, vmName + "-network").execute();
        System.out.println(deleteNetworkOp.toPrettyString());
        while (!deleteNetworkOp.getStatus().equals("DONE")) {
            Thread.sleep(2000);
            deleteNetworkOp = client.globalOperations().get(PROJECT_NAME, deleteNetworkOp.getName()).execute();
            System.out.println("PROGRESS:" + deleteNetworkOp.getProgress());
            System.out.println("STATUS:" + deleteNetworkOp.getStatus());
        }
    }

    private static void deleteVM(String vmName) throws Exception {
        // cancello la vm
        Operation deleteInstance = client.instances().delete(PROJECT_NAME, ZONE, vmName).execute();
        System.out.println(deleteInstance.toPrettyString());

        while (!deleteInstance.getStatus().equals("DONE")) {
            Thread.sleep(2000);
            deleteInstance = client.zoneOperations().get(PROJECT_NAME, ZONE, deleteInstance.getName()).execute();
            System.out.println("PROGRESS:" + deleteInstance.getProgress());
            System.out.println("STATUS:" + deleteInstance.getStatus());
        }
    }

    private static void getDisk(String diskName) throws Exception {
        Disk disk = client.disks().get(PROJECT_NAME, ZONE, diskName).execute();
        System.out.println(disk.toPrettyString());
    }

    private static String getResourceNameFromUrl(String url) {
        Pattern pattern = Pattern.compile(".+/(.+)$");
        Matcher matcher = pattern.matcher(url);
        if (matcher.matches())
            return matcher.group(1);
        throw new IllegalArgumentException();
    }

    private static List<Image> getValidImages(String projectName, String requiredOs) throws Exception {
        ImageList imageListPD = client.images().list(projectName).execute();
        List<Image> validImages = new LinkedList<Image>();
        if (imageListPD != null) {
            List<Image> images = imageListPD.getItems();
            for (Image i : images)
                if (i.getDeprecated() == null && matchString(i.getName(), requiredOs))
                    validImages.add(i);
        }
        for (Image i : validImages)
            System.out.println(i.toPrettyString());
        return validImages;
    }

    private static List<MachineType> getValidMachineTypes(String projectName, String zone) throws Exception {
        MachineTypeList typeList = client.machineTypes().list(PROJECT_NAME, ZONE).execute();
        List<MachineType> validMachineTypes = new LinkedList<MachineType>();
        if (typeList != null) {
            List<MachineType> mTypes = typeList.getItems();
            for (MachineType mt : mTypes)
                if (mt.getDeprecated() == null)
                    validMachineTypes.add(mt);

        }
        for (MachineType mt : validMachineTypes)
            System.out.println(mt.toPrettyString());
        return validMachineTypes;
    }

    private static boolean matchString(String source, String match) {
        if (match == null)
            return true;
        Pattern pattern = Pattern.compile(source);
        Matcher matcher = pattern.matcher(match);
        matcher.matches();
        return matcher.hitEnd();
    }

    private static void setInstanceTags(String vmName, List<String> newTags) throws Exception {
        Instance instance = client.instances().get(PROJECT_NAME, ZONE, vmName).execute();
        System.out.println(instance.toPrettyString());
        Tags tags = instance.getTags();
        tags.setItems(newTags);
        Operation setTagsOp = client.instances().setTags(PROJECT_NAME, ZONE, vmName, tags).execute();
        System.out.println(setTagsOp.toPrettyString());
        while (!setTagsOp.getStatus().equals("DONE")) {
            Thread.sleep(2000);
            setTagsOp = client.zoneOperations().get(PROJECT_NAME, ZONE, setTagsOp.getName()).execute();
            System.out.println("PROGRESS:" + setTagsOp.getProgress());
            System.out.println("STATUS:" + setTagsOp.getStatus());
        }
    }
}