From 81a2736189d7af9e7ce660f7360906f5f3135ba2 Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Thu, 14 Apr 2016 14:10:55 +0100 Subject: [PATCH 01/15] exceptions fixes --- .../org/dasein/cloud/google/DataCenters.java | 8 +-- .../org/dasein/cloud/google/GoogleMethod.java | 11 ++-- .../GCERelationalDatabaseCapabilities.java | 35 +++++++++++-- .../google/compute/server/DiskSupport.java | 22 ++++---- .../google/compute/server/ImageSupport.java | 8 +-- .../google/compute/server/ServerSupport.java | 42 +++++++-------- .../compute/server/SnapshotSupport.java | 14 ++--- .../cloud/google/network/FirewallSupport.java | 14 ++--- .../google/network/IPAddressSupport.java | 22 ++++---- .../google/network/LoadBalancerSupport.java | 52 +++++++++---------- .../cloud/google/network/NetworkSupport.java | 16 +++--- .../cloud/google/network/VpnSupport.java | 23 ++++---- .../org/dasein/cloud/google/platform/RDS.java | 20 +++---- .../cloud/google/storage/DriveSupport.java | 24 ++++----- 14 files changed, 168 insertions(+), 143 deletions(-) diff --git a/src/main/java/org/dasein/cloud/google/DataCenters.java b/src/main/java/org/dasein/cloud/google/DataCenters.java index 53fec76..1c19995 100755 --- a/src/main/java/org/dasein/cloud/google/DataCenters.java +++ b/src/main/java/org/dasein/cloud/google/DataCenters.java @@ -94,7 +94,7 @@ public DataCenterCapabilities getCapabilities() throws InternalException, CloudE } throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred retrieving the dataCenter: " + dataCenterId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred retrieving the dataCenter: " + dataCenterId + ": " + ex.getMessage()); } } } @@ -114,7 +114,7 @@ public DataCenterCapabilities getCapabilities() throws InternalException, CloudE } throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred retrieving the region: " + providerRegionId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred retrieving the region: " + providerRegionId + ": " + ex.getMessage(), ex); } } } @@ -161,7 +161,7 @@ public DataCenterCapabilities getCapabilities() throws InternalException, CloudE GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException(CloudErrorType.COMMUNICATION, gceDataCenters.getLastStatusCode(), gceDataCenters.getLastStatusMessage(), "An error occurred while listing DataCenters"); + throw new GeneralCloudException("An error occurred while listing DataCenters: "+gceDataCenters.getLastStatusMessage()); } } if (cache != null) { @@ -205,7 +205,7 @@ public Collection listRegions() throws InternalException, CloudException GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException(CloudErrorType.COMMUNICATION, gceRegions.getLastStatusCode(), gceRegions.getLastStatusMessage(), "An error occurred while listing regions"); + throw new GeneralCloudException("An error occurred while listing regions: "+gceRegions.getLastStatusMessage()); } } cache.put(ctx, regions); diff --git a/src/main/java/org/dasein/cloud/google/GoogleMethod.java b/src/main/java/org/dasein/cloud/google/GoogleMethod.java index 46f536e..4cf5328 100755 --- a/src/main/java/org/dasein/cloud/google/GoogleMethod.java +++ b/src/main/java/org/dasein/cloud/google/GoogleMethod.java @@ -26,7 +26,6 @@ import com.google.api.services.sqladmin.SQLAdmin; import com.google.api.services.sqladmin.model.OperationError; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; import org.dasein.cloud.CloudException; import org.dasein.cloud.CommunicationException; import org.dasein.cloud.GeneralCloudException; @@ -59,7 +58,7 @@ public GoogleMethod(@Nonnull Google provider) { while(timeout > System.currentTimeMillis()) { if(job.getError() != null){ for(Operation.Error.Errors error : job.getError().getErrors()){ - throw new GeneralCloudException("An error occurred: " + error.getMessage(), CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred: " + error.getMessage()); } } else if(job.getStatus().equals("DONE")){ @@ -105,7 +104,7 @@ else if(job.getStatus().equals("DONE")){ while(timeout > System.currentTimeMillis()) { if(job.getError() != null){ for(Operation.Error.Errors error : job.getError().getErrors()){ - throw new GeneralCloudException("An error occurred: " + error.getMessage(), CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred: " + error.getMessage()); } } else if(job.getStatus().equals("DONE")){ @@ -158,7 +157,7 @@ public void getRDSOperationComplete(ProviderContext ctx, String operation) throw if (instanceOperation.getError() != null) { for (OperationError error : instanceOperation.getError().getErrors()) { - throw new GeneralCloudException("An error occurred: " + error.getCode() + " : " + error.getKind(), CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred: " + error.getCode() + " : " + error.getKind()); } } else if (instanceOperation.getStatus().equals("DONE")) { return; @@ -190,7 +189,7 @@ public void getRDSOperationCompleteLong(ProviderContext ctx, String operation) t if (null != instanceOperation) { if (null != instanceOperation.getError()) { for (OperationError error : instanceOperation.getError().getErrors()) { - throw new GeneralCloudException("An error occurred: " + error.getCode() + " : " + error.getKind(), CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred: " + error.getCode() + " : " + error.getKind()); } } else if (instanceOperation.getStatus().equals("DONE")) { return; @@ -222,7 +221,7 @@ public void getRDSOperationCompleteLong(ProviderContext ctx, String operation) t if (job.getError() != null) { for (Errors error : job.getError().getErrors()) { - throw new GeneralCloudException("An error occurred: " + error.getMessage(), CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred: " + error.getMessage()); } } else if (job.getStatus().equals("DONE")) { diff --git a/src/main/java/org/dasein/cloud/google/capabilities/GCERelationalDatabaseCapabilities.java b/src/main/java/org/dasein/cloud/google/capabilities/GCERelationalDatabaseCapabilities.java index 38ae4f2..1e5fcbb 100644 --- a/src/main/java/org/dasein/cloud/google/capabilities/GCERelationalDatabaseCapabilities.java +++ b/src/main/java/org/dasein/cloud/google/capabilities/GCERelationalDatabaseCapabilities.java @@ -19,18 +19,19 @@ package org.dasein.cloud.google.capabilities; -import java.util.Locale; - -import javax.annotation.Nonnull; - import org.dasein.cloud.AbstractCapabilities; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.ProviderContext; +import org.dasein.cloud.Requirement; import org.dasein.cloud.google.Google; +import org.dasein.cloud.platform.DatabaseProduct; import org.dasein.cloud.platform.RelationalDatabaseCapabilities; import org.dasein.cloud.util.NamingConstraints; +import javax.annotation.Nonnull; +import java.util.Locale; + public class GCERelationalDatabaseCapabilities extends AbstractCapabilities implements RelationalDatabaseCapabilities { private Google provider; @@ -51,6 +52,12 @@ public String getProviderTermForSnapshot( Locale locale ) { return "point-in-time recovery"; } + @Nonnull + @Override + public Requirement requiresEngineVersion() throws CloudException, InternalException { + return Requirement.OPTIONAL; + } + @Override public String getProviderTermForBackup( Locale locale ) { return "Backup"; @@ -141,4 +148,24 @@ public String getRegionId() { .withNoSpaces() .constrainedBy('-'); } + + @Nonnull + @Override + public NamingConstraints getAdminUsernameNamingConstraints(DatabaseProduct product) throws CloudException, InternalException { + return NamingConstraints.getAlphaNumeric(1, 63). + withRegularExpression("^[a-z][-a-z0-9]{0,61}$") + .lowerCaseOnly() + .withNoSpaces() + .constrainedBy('-'); + } + + @Nonnull + @Override + public NamingConstraints getAdminPasswordNamingConstraints(DatabaseProduct product) throws CloudException, InternalException { + return NamingConstraints.getAlphaNumeric(1, 63). + withRegularExpression("^[a-z][-a-z0-9]{0,61}$") + .lowerCaseOnly() + .withNoSpaces() + .constrainedBy('-'); + } } diff --git a/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java b/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java index c16c921..e9493ad 100644 --- a/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java +++ b/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java @@ -107,7 +107,7 @@ public void attach(@Nonnull String volumeId, @Nonnull String toServerId, @Nonnul GoogleMethod method = new GoogleMethod(provider); if(!method.getOperationComplete(provider.getContext(), job, GoogleOperationType.ZONE_OPERATION, "", vm.getProviderDataCenterId())){ - throw new GeneralCloudException("An error occurred attaching the disk: Operation Timedout", CloudErrorType.OPERATION_TIMED_OUT); + throw new GeneralCloudException("An error occurred attaching the disk: Operation Timedout"); } } catch (IOException ex) { logger.error(ex.getMessage()); @@ -115,10 +115,10 @@ public void attach(@Nonnull String volumeId, @Nonnull String toServerId, @Nonnul GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while attaching the disk: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while attaching the disk: " + ex.getMessage(), ex); } } catch (Exception ex) { - throw new GeneralCloudException("An error occurred while attaching the disk: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while attaching the disk: " + ex.getMessage(), ex); } } finally{ @@ -155,7 +155,7 @@ public void attach(@Nonnull String volumeId, @Nonnull String toServerId, @Nonnul GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while creating the Volume: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while creating the Volume: " + ex.getMessage(), ex); } } } @@ -181,7 +181,7 @@ public void detach(@Nonnull String volumeId, boolean force) throws InternalExcep job = gce.instances().detachDisk(provider.getContext().getAccountNumber(), volume.getProviderDataCenterId(), vmName, volume.getDeviceId()).execute(); GoogleMethod method = new GoogleMethod(provider); if (!method.getOperationComplete(provider.getContext(), job, GoogleOperationType.ZONE_OPERATION, "", volume.getProviderDataCenterId())){ - throw new GeneralCloudException("An error occurred while detaching the volume: Operation Timedout", CloudErrorType.OPERATION_TIMED_OUT); + throw new GeneralCloudException("An error occurred while detaching the volume: Operation Timedout"); } } } catch (IOException ex) { @@ -190,10 +190,10 @@ public void detach(@Nonnull String volumeId, boolean force) throws InternalExcep GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while detaching the volume: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while detaching the volume: " + ex.getMessage(), ex); } } catch (Exception ex) { - throw new GeneralCloudException("An error occurred while detaching the volume", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while detaching the volume", ex); } } finally{ @@ -235,7 +235,7 @@ public Volume getVolume(@Nonnull String volumeId) throws InternalException, Clou GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred getting the volume: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred getting the volume: " + ex.getMessage(), ex); } } } @@ -295,7 +295,7 @@ public Volume getVolume(@Nonnull String volumeId) throws InternalException, Clou GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred listing Volumes: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred listing Volumes: " + ex.getMessage(), ex); } } } @@ -320,7 +320,7 @@ public void remove(@Nonnull String volumeId) throws InternalException, CloudExce Operation job = gce.disks().delete(provider.getContext().getAccountNumber(), volume.getProviderDataCenterId(), volume.getProviderVolumeId()).execute(); GoogleMethod method = new GoogleMethod(provider); if(!method.getOperationComplete(provider.getContext(), job, GoogleOperationType.ZONE_OPERATION, "", volume.getProviderDataCenterId())){ - throw new GeneralCloudException("An error occurred while deleting the Volume: Operation Timedout", CloudErrorType.OPERATION_TIMED_OUT); + throw new GeneralCloudException("An error occurred while deleting the Volume: Operation Timedout"); } } catch (IOException ex) { logger.error(ex.getMessage()); @@ -328,7 +328,7 @@ public void remove(@Nonnull String volumeId) throws InternalException, CloudExce GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while deleting the volume: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while deleting the volume: " + ex.getMessage(), ex); } } } diff --git a/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java b/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java index 73729e5..805e0d2 100644 --- a/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java +++ b/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java @@ -158,7 +158,7 @@ public void bundleVirtualMachineAsync(@Nonnull String virtualMachineId, @Nonnull GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException(ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException(ex.getMessage(), ex); } } return toMachineImage(image); @@ -208,7 +208,7 @@ public boolean isSubscribed() throws CloudException, InternalException { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException(ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException(ex.getMessage(), ex); } } return images; @@ -269,7 +269,7 @@ public void remove(@Nonnull String providerImageId, boolean checkState) throws C throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while deleting the image: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while deleting the image: " + ex.getMessage(), ex); } } } @@ -557,7 +557,7 @@ public MachineImage capture(@Nonnull ImageCreateOptions options, @Nullable Async GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while deleting the image: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while deleting the image: " + ex.getMessage(), ex); } } diff --git a/src/main/java/org/dasein/cloud/google/compute/server/ServerSupport.java b/src/main/java/org/dasein/cloud/google/compute/server/ServerSupport.java index c4ff6a8..6e9691f 100644 --- a/src/main/java/org/dasein/cloud/google/compute/server/ServerSupport.java +++ b/src/main/java/org/dasein/cloud/google/compute/server/ServerSupport.java @@ -218,7 +218,7 @@ public String getPassword(@Nonnull String vmId) throws InternalException, CloudE GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred when getting console output for VM: " + vmId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred when getting console output for VM: " + vmId + ": " + ex.getMessage(), ex); } } throw new ResourceNotFoundException("Virtual Machine", vmId); @@ -245,7 +245,7 @@ public VirtualMachineProduct getProduct(@Nonnull String productId) throws Intern GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred retrieving the product: " + productId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred retrieving the product: " + productId + ": " + ex.getMessage(), ex); } } } @@ -275,7 +275,7 @@ public VirtualMachine getVirtualMachine(@Nonnull String vmId)throws InternalExce GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred retrieving VM: " + vmId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred retrieving VM: " + vmId + ": " + ex.getMessage(), ex); } } } @@ -477,15 +477,15 @@ public void validateLaunchOptions(@Nonnull VMLaunchOptions withLaunchOptions) th GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred launching the instance: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred launching the instance: " + ex.getMessage(), ex); } } catch (Exception e) { if ((e.getMessage().contains("The resource")) && (e.getMessage().contains("disks")) && (e.getMessage().contains("already exists"))) { - throw new GeneralCloudException("A disk named '" + withLaunchOptions.getFriendlyName() + "' already exists.", e, CloudErrorType.INVALID_USER_DATA); + throw new GeneralCloudException("A disk named '" + withLaunchOptions.getFriendlyName() + "' already exists.", e); } else { - throw new GeneralCloudException("Error launching vm", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Error launching vm", e); } } @@ -512,7 +512,7 @@ public void validateLaunchOptions(@Nonnull VMLaunchOptions withLaunchOptions) th try { output = gce.instances().getSerialPortOutput(provider.getContext().getAccountNumber(), withLaunchOptions.getDataCenterId(), vmId).setPort(4).execute(); } catch ( IOException e ) { - throw new GeneralCloudException("Error getting serial port output during password reset", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Error getting serial port output during password reset", e); } // Get the last line - this will be a JSON string corresponding to the most recent password reset attempt. String[] entries = output.getContents().split("\n"); @@ -596,7 +596,7 @@ private boolean guessWindows(Image img) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred listing VM products.", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred listing VM products.", ex); } } } @@ -675,7 +675,7 @@ private Iterable listProducts(VirtualMachineProductFilter GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while listing Virtual Machines.", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while listing Virtual Machines.", ex); } } } @@ -730,7 +730,7 @@ public void reboot(@Nonnull String vmId) throws CloudException, InternalExceptio GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while rebooting VM: " + vmId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while rebooting VM: " + vmId + ": " + ex.getMessage(), ex); } } } @@ -761,7 +761,7 @@ public void start(@Nonnull String vmId) throws InternalException, CloudException GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while starting VM: " + vmId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while starting VM: " + vmId + ": " + ex.getMessage(), ex); } } } @@ -778,7 +778,7 @@ public void stop(@Nonnull String vmId, boolean force) throws InternalException, GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while stopping VM: " + vmId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while stopping VM: " + vmId + ": " + ex.getMessage(), ex); } } } @@ -820,7 +820,7 @@ public void terminateVm(@Nonnull String vmId, String reason) throws InternalExce if(job != null) { method = new GoogleMethod(provider); if (false == method.getOperationComplete(provider.getContext(), job, GoogleOperationType.ZONE_OPERATION, null, zone)) { - throw new GeneralCloudException("An error occurred while terminating the VM. Note: The root disk might also still exist", CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while terminating the VM. Note: The root disk might also still exist"); } } } catch (IOException ex) { @@ -829,10 +829,10 @@ public void terminateVm(@Nonnull String vmId, String reason) throws InternalExce GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while terminating VM: " + vmId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while terminating VM: " + vmId + ": " + ex.getMessage(), ex); } } catch (Exception ex) { - throw new GeneralCloudException("An error occurred while terminating VM: " + vmId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); // catch exception from getOperationComplete + throw new GeneralCloudException("An error occurred while terminating VM: " + vmId + ": " + ex.getMessage(), ex); // catch exception from getOperationComplete } } finally { @@ -859,10 +859,10 @@ public void terminateVmDisk(@Nonnull String diskName, String zone) throws Intern throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } } else { - throw new GeneralCloudException("An error occurred while deleting VM disk: " + diskName + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while deleting VM disk: " + diskName + ": " + ex.getMessage(), ex); } } catch (Exception ex) { - throw new GeneralCloudException("An error occurred while deleting VM disk: " + diskName + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); // catch exception from getOperationComplete + throw new GeneralCloudException("An error occurred while deleting VM disk: " + diskName + ": " + ex.getMessage(), ex); // catch exception from getOperationComplete } } finally{ @@ -962,7 +962,7 @@ private VirtualMachine toVirtualMachine(Instance instance) throws InternalExcept GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("IOException: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("IOException: " + ex.getMessage(), ex); } } } @@ -1142,7 +1142,7 @@ public void populate( @Nonnull Jiterator iterator ) throws Exception { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred retrieving VM: " + vmId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred retrieving VM: " + vmId + ": " + ex.getMessage(), ex); } } } @@ -1157,7 +1157,7 @@ private void resetPassword(String vmId, String dataCenterId, KeyPair keys) throw try { inst = gce.instances().get(provider.getContext().getAccountNumber(), dataCenterId, vmId).execute(); } catch ( IOException e ) { - throw new GeneralCloudException("Error resetting password", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Error resetting password", e); } Metadata metadata = inst.getMetadata(); @@ -1167,7 +1167,7 @@ private void resetPassword(String vmId, String dataCenterId, KeyPair keys) throw try { gce.instances().setMetadata(provider.getContext().getAccountNumber(), dataCenterId, vmId, metadata).execute(); } catch ( IOException e ) { - throw new GeneralCloudException("Error resetting password", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Error resetting password", e); } try { Thread.sleep(30000); diff --git a/src/main/java/org/dasein/cloud/google/compute/server/SnapshotSupport.java b/src/main/java/org/dasein/cloud/google/compute/server/SnapshotSupport.java index 8d9bdea..98d32b3 100644 --- a/src/main/java/org/dasein/cloud/google/compute/server/SnapshotSupport.java +++ b/src/main/java/org/dasein/cloud/google/compute/server/SnapshotSupport.java @@ -92,14 +92,14 @@ public String createSnapshot(@Nonnull SnapshotCreateOptions options) throws Clou } } } - throw new GeneralCloudException("An error occurred creating the snapshot: Operation Timedout", CloudErrorType.OPERATION_TIMED_OUT); + throw new GeneralCloudException("An error occurred creating the snapshot: Operation Timedout"); } catch (IOException ex) { logger.error(ex.getMessage()); if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred creating the snapshot: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred creating the snapshot: " + ex.getMessage(), ex); } } catch (Exception ex) { throw new OperationNotSupportedException("Copying snapshots is not supported in GCE"); @@ -136,7 +136,7 @@ public Snapshot getSnapshot(@Nonnull String snapshotId) throws InternalException GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred getting the snapshot: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred getting the snapshot: " + ex.getMessage(), ex); } } } @@ -183,7 +183,7 @@ public boolean isSubscribed() throws InternalException, CloudException{ GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred retrieving snapshot status", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred retrieving snapshot status", ex); } } } @@ -215,7 +215,7 @@ public boolean isSubscribed() throws InternalException, CloudException{ GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while listing snapshots: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while listing snapshots: " + ex.getMessage(), ex); } } } @@ -239,7 +239,7 @@ public void remove(@Nonnull String snapshotId) throws InternalException, CloudEx GoogleMethod method = new GoogleMethod(provider); if(!method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, "", "")){ - throw new GeneralCloudException("An error occurred deleting the snapshot: Operation timed out", CloudErrorType.OPERATION_TIMED_OUT); + throw new GeneralCloudException("An error occurred deleting the snapshot: Operation timed out"); } } catch (IOException ex) { if (ex.getClass() == GoogleJsonResponseException.class) { @@ -247,7 +247,7 @@ public void remove(@Nonnull String snapshotId) throws InternalException, CloudEx GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred deleting the snapshot: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred deleting the snapshot: " + ex.getMessage(), ex); } } } diff --git a/src/main/java/org/dasein/cloud/google/network/FirewallSupport.java b/src/main/java/org/dasein/cloud/google/network/FirewallSupport.java index c653dc5..2e25318 100644 --- a/src/main/java/org/dasein/cloud/google/network/FirewallSupport.java +++ b/src/main/java/org/dasein/cloud/google/network/FirewallSupport.java @@ -180,7 +180,7 @@ public class FirewallSupport extends AbstractFirewallSupport { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred creating a new rule on " + firewallId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred creating a new rule on " + firewallId + ": " + ex.getMessage(), ex); } } @@ -232,7 +232,7 @@ public Firewall getFirewall(@Nonnull String firewallId) throws InternalException GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException(ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException(ex.getMessage(), ex); } } } @@ -259,7 +259,7 @@ public Firewall getFirewall(@Nonnull String firewallId) throws InternalException GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException(ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException(ex.getMessage(), ex); } } } @@ -311,7 +311,7 @@ public boolean isSubscribed() throws CloudException, InternalException { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while listing Firewalls: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while listing Firewalls: " + ex.getMessage(), ex); } } return firewalls; @@ -349,13 +349,13 @@ public void revoke(@Nonnull String providerFirewallRuleId) throws InternalExcept Operation job = gce.firewalls().update(provider.getContext().getAccountNumber(), firewall, fw).execute(); GoogleMethod method = new GoogleMethod(provider); if (!method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, "", "")) { - throw new GeneralCloudException("An error occurred deleting the rule: Operation Timed Out", CloudErrorType.OPERATION_TIMED_OUT); + throw new GeneralCloudException("An error occurred deleting the rule: Operation Timed Out"); } } else { Operation job = gce.firewalls().delete(provider.getContext().getAccountNumber(), providerFirewallRuleId).execute(); GoogleMethod method = new GoogleMethod(provider); if(!method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, "", "")) { - throw new GeneralCloudException("An error occurred deleting the rule: Operation Timed Out", CloudErrorType.OPERATION_TIMED_OUT); + throw new GeneralCloudException("An error occurred deleting the rule: Operation Timed Out"); } } } catch (IOException ex) { @@ -364,7 +364,7 @@ public void revoke(@Nonnull String providerFirewallRuleId) throws InternalExcept GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while deleting the firewall rule: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while deleting the firewall rule: " + ex.getMessage(), ex); } } } diff --git a/src/main/java/org/dasein/cloud/google/network/IPAddressSupport.java b/src/main/java/org/dasein/cloud/google/network/IPAddressSupport.java index b5efe87..9bf6fcb 100644 --- a/src/main/java/org/dasein/cloud/google/network/IPAddressSupport.java +++ b/src/main/java/org/dasein/cloud/google/network/IPAddressSupport.java @@ -98,7 +98,7 @@ public void assign(@Nonnull String addressId, @Nonnull String serverId) throws I Operation job = gce.instances().addAccessConfig(getContext().getAccountNumber(), vm.getProviderDataCenterId(), serverId, "nic0", accessConfig).execute(); if(!method.getOperationComplete(getContext(), job, GoogleOperationType.ZONE_OPERATION, "", vm.getProviderDataCenterId())){ - throw new GeneralCloudException("An error occurred assigning the IP: " + addressId + ": Operation timed out", CloudErrorType.OPERATION_TIMED_OUT); + throw new GeneralCloudException("An error occurred assigning the IP: " + addressId + ": Operation timed out"); } } catch (Exception ex) { logger.error(ex.getMessage()); @@ -106,7 +106,7 @@ public void assign(@Nonnull String addressId, @Nonnull String serverId) throws I GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred assigning the IP: " + addressId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred assigning the IP: " + addressId + ": " + ex.getMessage(), ex); } } } @@ -163,7 +163,7 @@ public IpAddress getIpAddress(@Nonnull String addressId) throws InternalExceptio GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred getting the IPAddress: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred getting the IPAddress: " + ex.getMessage(), ex); } } return null; @@ -192,7 +192,7 @@ public String getIpAddressIdFromIP(@Nonnull String ipAddress, @Nonnull String re GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred finding the specified IPAddress: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred finding the specified IPAddress: " + ex.getMessage(), ex); } } } @@ -236,7 +236,7 @@ public Iterable listIpPool(@Nonnull IPVersion version, boolean unassi GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred listing IPs: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred listing IPs: " + ex.getMessage(), ex); } } } @@ -280,7 +280,7 @@ public Iterable listIpPoolStatus(@Nonnull IPVersion version) thr GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred listing IPs: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred listing IPs: " + ex.getMessage(), ex); } } } @@ -300,7 +300,7 @@ public void releaseFromPool(@Nonnull String addressId) throws InternalException, GoogleMethod method = new GoogleMethod(getProvider()); if(!method.getOperationComplete(getContext(), job, GoogleOperationType.REGION_OPERATION, ipAddress.getRegionId(), "")){ - throw new GeneralCloudException("An error occurred releasing address: " + addressId + ": Operation timed out", CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred releasing address: " + addressId + ": Operation timed out"); } } catch (IOException ex) { logger.error(ex.getMessage()); @@ -308,7 +308,7 @@ public void releaseFromPool(@Nonnull String addressId) throws InternalException, GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred releasing address: " + addressId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred releasing address: " + addressId + ": " + ex.getMessage(), ex); } } } @@ -344,7 +344,7 @@ public void releaseFromServer(@Nonnull String addressId) throws InternalExceptio GoogleMethod method = new GoogleMethod(getProvider()); if(!method.getOperationComplete(getContext(), job, GoogleOperationType.ZONE_OPERATION, "", zone)){ - throw new GeneralCloudException("An error occurred releasing the address from the server: Operation timed out", CloudErrorType.OPERATION_TIMED_OUT); + throw new GeneralCloudException("An error occurred releasing the address from the server: Operation timed out"); } } catch (IOException ex) { logger.error(ex.getMessage()); @@ -352,7 +352,7 @@ public void releaseFromServer(@Nonnull String addressId) throws InternalExceptio GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred releasing the address from the server: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred releasing the address from the server: " + ex.getMessage(), ex); } } catch (Exception ex) { logger.error(ex.getMessage()); @@ -384,7 +384,7 @@ public String request(@Nonnull IPVersion version) throws InternalException, Clou GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred requesting an IPAddress: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred requesting an IPAddress: " + ex.getMessage(), ex); } } } diff --git a/src/main/java/org/dasein/cloud/google/network/LoadBalancerSupport.java b/src/main/java/org/dasein/cloud/google/network/LoadBalancerSupport.java index bbaf623..22a0ae0 100644 --- a/src/main/java/org/dasein/cloud/google/network/LoadBalancerSupport.java +++ b/src/main/java/org/dasein/cloud/google/network/LoadBalancerSupport.java @@ -121,7 +121,7 @@ private void releaseLoadBalancerIp(@Nonnull LoadBalancer lb) throws CloudExcepti } } } catch (Exception e) { - throw new GeneralCloudException("Exception releasing load balancer ip", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception releasing load balancer ip", e); } } @@ -151,13 +151,13 @@ public void removeLoadBalancer(@Nonnull String loadBalancerId) throws CloudExcep removeLoadBalancerHealthCheck(healthCheckName); } } catch (CloudException e) { - throw new GeneralCloudException("Exception removing load balancer", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception removing load balancer", e); } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception removing load balancer", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception removing load balancer", e); } } finally { @@ -175,7 +175,7 @@ public String getLoadBalancerHealthCheckName(@Nonnull String loadBalancerId) thr GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception getting load balancer healthcheck name", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception getting load balancer healthcheck name", e); } } @@ -212,7 +212,7 @@ private List getForwardingRules(String targetPoolName) throws CloudExcep GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception getting load balancer forwarding rules", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception getting load balancer forwarding rules", e); } } finally { APITrace.end(); @@ -285,7 +285,7 @@ public void removeListeners(String toLoadBalancerId, LbListener[] listeners) thr GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception removing listeners", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception removing listeners", e); } } } @@ -304,7 +304,7 @@ private void removeLoadBalancerForwardingRule(String forwardingRuleName) throws GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception removing load balancer forwarding rule", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception removing load balancer forwarding rule", e); } } finally { @@ -332,7 +332,7 @@ private void removeLoadBalancerForwardingRule(String forwardingRuleName) throws GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception creating load balancer", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception creating load balancer", e); } } HealthCheckOptions hco = options.getHealthCheckOptions(); @@ -408,10 +408,10 @@ public void addListeners(String toLoadBalancerId, LbListener[] listeners) throws GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception adding listener", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception adding listener", e); } } catch (Exception e) { - throw new GeneralCloudException("Exception adding listener", e, CloudErrorType.GENERAL); // catch the exception from method.getOperation + throw new GeneralCloudException("Exception adding listener", e); // catch the exception from method.getOperation } } @@ -479,10 +479,10 @@ void createLoadBalancerForwardingRule(@Nonnull LoadBalancerCreateOptions options GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception creating forwarding rule", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception creating forwarding rule", e); } } catch (Exception e) { - throw new GeneralCloudException("Exception creating forwarding rule", e, CloudErrorType.GENERAL); // catch the exception from method.getOperation + throw new GeneralCloudException("Exception creating forwarding rule", e); // catch the exception from method.getOperation } finally { APITrace.end(); @@ -532,7 +532,7 @@ public LoadBalancerHealthCheck createLoadBalancerHealthCheck(@Nullable String na GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception creating health check", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception creating health check", e); } } finally { @@ -554,7 +554,7 @@ public void attachHealthCheckToLoadBalancer(@Nonnull String providerLoadBalancer GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception getting health check for load balancer", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception getting health check for load balancer", e); } } @@ -572,7 +572,7 @@ public void attachHealthCheckToLoadBalancer(@Nonnull String providerLoadBalancer GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception adding health check to load balancer", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception adding health check to load balancer", e); } } finally { @@ -668,7 +668,7 @@ public Iterable listLBHealthChecks(@Nullable HealthChec GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception listing load balancer health checks", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception listing load balancer health checks", e); } } finally { @@ -691,12 +691,12 @@ public void removeLoadBalancerHealthCheck(String healthCheckId) throws CloudExce GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception removing load balancer health check", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception removing load balancer health check", e); } } } catch (Exception e) { if (!e.getMessage().contains(" is already being used by ")) { //if its in use elsewhere, then let it be. - throw new GeneralCloudException("Exception removing load balancer health check", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception removing load balancer health check", e); } } finally { APITrace.end(); @@ -716,7 +716,7 @@ public LoadBalancerHealthCheck modifyHealthCheck(@Nonnull String providerLBHealt GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception getting helath check for modification", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception getting helath check for modification", e); } } @@ -740,7 +740,7 @@ public LoadBalancerHealthCheck modifyHealthCheck(@Nonnull String providerLBHealt GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception updating health check", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception updating health check", e); } } finally { @@ -778,7 +778,7 @@ private LoadBalancerHealthCheck getLoadBalancerHealthCheck(@Nonnull String provi throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } } else { - throw new GeneralCloudException("Exception getting load balancer health check", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception getting load balancer health check", e); } } finally { @@ -824,7 +824,7 @@ public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String ... ser GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception adding servers to load balancer", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception adding servers to load balancer", e); } } finally { @@ -862,7 +862,7 @@ public void removeServers(@Nonnull String fromLoadBalancerId, @Nonnull String .. GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception removing servers", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception removing servers", e); } } finally { @@ -883,7 +883,7 @@ public void removeServers(@Nonnull String fromLoadBalancerId, @Nonnull String .. GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception listing endpoints", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception listing endpoints", e); } } @@ -942,7 +942,7 @@ public void removeServers(@Nonnull String fromLoadBalancerId, @Nonnull String .. GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception listing load balancer status", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception listing load balancer status", e); } } finally { @@ -978,7 +978,7 @@ public void removeServers(@Nonnull String fromLoadBalancerId, @Nonnull String .. GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception listing load balancers", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception listing load balancers", e); } } finally { diff --git a/src/main/java/org/dasein/cloud/google/network/NetworkSupport.java b/src/main/java/org/dasein/cloud/google/network/NetworkSupport.java index 655d99a..a9e81de 100644 --- a/src/main/java/org/dasein/cloud/google/network/NetworkSupport.java +++ b/src/main/java/org/dasein/cloud/google/network/NetworkSupport.java @@ -121,7 +121,7 @@ public Route addRouteToVirtualMachine(String toRoutingTableId, IPVersion version GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while creating the route: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while creating the route: " + ex.getMessage(), ex); } } } @@ -161,7 +161,7 @@ public Route addRouteToVirtualMachine(String toRoutingTableId, IPVersion version GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while creating vlan: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while creating vlan: " + ex.getMessage(), ex); } } } @@ -197,7 +197,7 @@ public RoutingTable getRoutingTableForVlan(@Nonnull String vlanId)throws CloudEx GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException(ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException(ex.getMessage(), ex); } } } @@ -245,7 +245,7 @@ public void removeInternetGatewayById(@Nonnull String id) throws CloudException, GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred getting VLAN statuses", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred getting VLAN statuses", ex); } } } @@ -279,10 +279,10 @@ public void removeInternetGatewayById(@Nonnull String id) throws CloudException, GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while listing VLans: " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while listing VLans: " + ex.getMessage(), ex); } } catch (Exception e) { - throw new GeneralCloudException("An error occurred while listing VLans for " + ctx.getAccountNumber() + ": " + e.getMessage(), e, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while listing VLans for " + ctx.getAccountNumber() + ": " + e.getMessage(), e); } return vlans; } @@ -316,7 +316,7 @@ public void removeVlan(String vlanId) throws CloudException, InternalException { op = gce.networks().delete(provider.getContext().getAccountNumber(), vlan.getName()).execute(); if(!method.getOperationComplete(provider.getContext(), op, GoogleOperationType.GLOBAL_OPERATION, "", "")){ - throw new GeneralCloudException("An error occurred while removing network: " + vlanId + ": Operation timed out", CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while removing network: " + vlanId + ": Operation timed out"); } } catch (IOException ex) { logger.error(ex.getMessage()); @@ -324,7 +324,7 @@ public void removeVlan(String vlanId) throws CloudException, InternalException { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred while removing network: " + vlanId + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred while removing network: " + vlanId + ": " + ex.getMessage(), ex); } } } diff --git a/src/main/java/org/dasein/cloud/google/network/VpnSupport.java b/src/main/java/org/dasein/cloud/google/network/VpnSupport.java index a0bd0e6..0216fac 100644 --- a/src/main/java/org/dasein/cloud/google/network/VpnSupport.java +++ b/src/main/java/org/dasein/cloud/google/network/VpnSupport.java @@ -11,7 +11,6 @@ import com.google.api.services.compute.model.TargetVpnGatewayList; import com.google.api.services.compute.model.VpnTunnel; import com.google.api.services.compute.model.VpnTunnelList; -import org.dasein.cloud.CloudErrorType; import org.dasein.cloud.CloudException; import org.dasein.cloud.GeneralCloudException; import org.dasein.cloud.InternalException; @@ -98,7 +97,7 @@ public Vpn createVpn(VpnCreateOptions vpnLaunchOptions) throws CloudException, I createForwardingRule(vpnLaunchOptions.getName(), "-rule-udp4500", vpn.getProviderVpnIp(), "UDP", "4500"); } catch ( Exception e ) { - throw new GeneralCloudException("Exception creating vpn", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception creating vpn", e); } } finally { APITrace.end(); @@ -141,7 +140,7 @@ public void deleteVpn(String providerVpnId) throws CloudException, InternalExcep op = gce.targetVpnGateways().delete(getContext().getAccountNumber(), getContext().getRegionId(), providerVpnId).execute(); method.getOperationComplete(getContext(), op, GoogleOperationType.REGION_OPERATION, getContext().getRegionId(), null); } catch (IOException e ) { - throw new GeneralCloudException("Exception deleting vpn", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception deleting vpn", e); } } finally { APITrace.end(); @@ -165,7 +164,7 @@ private void createForwardingRule(@Nonnull String targetVpnGatewayId, @Nonnull S try { op = gce.forwardingRules().insert(getContext().getAccountNumber(), getContext().getRegionId(), frContent ).execute(); } catch (Exception e ) { - throw new GeneralCloudException("Exception creating forwarding rule", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception creating forwarding rule", e); } method.getOperationComplete(getContext(), op, GoogleOperationType.REGION_OPERATION, getContext().getRegionId(), null); @@ -200,7 +199,7 @@ private void createForwardingRule(@Nonnull String targetVpnGatewayId, @Nonnull S return toVpnGateway(vpnAfter); } catch ( Exception e ) { - throw new GeneralCloudException("Exception creating vpn gateway", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception creating vpn gateway", e); } finally { APITrace.end(); } @@ -226,7 +225,7 @@ private void createRoute(String vpnName, String name, String description, String try { op = gce.routes().insert(getContext().getAccountNumber(), routeContent ).execute(); } catch (IOException e) { - throw new GeneralCloudException("Exception creating route", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception creating route", e); } method.getOperationComplete(getContext(), op, GoogleOperationType.GLOBAL_OPERATION, null, null); } @@ -247,7 +246,7 @@ public void deleteVpnGateway(String providerVpnGatewayId) throws CloudException, op = gce.vpnTunnels().delete(getContext().getAccountNumber(), getContext().getRegionId(), providerVpnGatewayId).execute(); method.getOperationComplete(getContext(), op, GoogleOperationType.REGION_OPERATION, getContext().getRegionId(), null); } catch ( IOException e ) { - throw new GeneralCloudException("Exception deleting vpn gateway", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception deleting vpn gateway", e); } finally { APITrace.end(); @@ -298,7 +297,7 @@ public VpnGateway getGateway(String gatewayId) throws CloudException, InternalEx try { vpnAfter = gce.vpnTunnels().get(getContext().getAccountNumber(), getContext().getRegionId(), gatewayId).execute(); } catch ( IOException e ) { - throw new GeneralCloudException("Exception getting gateway", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception getting gateway", e); } return toVpnGateway(vpnAfter); @@ -325,7 +324,7 @@ public Vpn getVpn(String providerTargetVpnGatewayId) throws CloudException, Inte } return null; } catch (IOException e) { - throw new GeneralCloudException("Exception getting vpn", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception getting vpn", e); } finally { APITrace.end(); } @@ -374,7 +373,7 @@ public Iterable listVpnConnections(String toVpnId) throws CloudEx try { tunnels = gce.vpnTunnels().list(getContext().getAccountNumber(), region.getName()).execute(); } catch ( IOException e ) { - throw new GeneralCloudException("Exception listing vpn connections", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception listing vpn connections", e); } if ((null != tunnels) && (null != tunnels.getItems())) { @@ -422,7 +421,7 @@ public Iterable listVpnStatus() throws CloudException, InternalE try { tunnels = gce.vpnTunnels().list(getContext().getAccountNumber(), region.getName()).execute(); } catch ( IOException e ) { - throw new GeneralCloudException("Exception listing vpn tunnels", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception listing vpn tunnels", e); } if ((null != tunnels) && (null != tunnels.getItems())) { for (VpnTunnel tunnel : tunnels.getItems()) { @@ -486,7 +485,7 @@ public Iterable listVpns() throws CloudException, InternalException { } } } catch ( Exception e ) { - throw new GeneralCloudException("Exception listing vpns", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception listing vpns", e); } finally { APITrace.end(); } diff --git a/src/main/java/org/dasein/cloud/google/platform/RDS.java b/src/main/java/org/dasein/cloud/google/platform/RDS.java index 0911852..9295a04 100644 --- a/src/main/java/org/dasein/cloud/google/platform/RDS.java +++ b/src/main/java/org/dasein/cloud/google/platform/RDS.java @@ -129,7 +129,7 @@ public void handleGoogleException(String message, Exception e) throws CloudExcep GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException(message, e, CloudErrorType.GENERAL); + throw new GeneralCloudException(message, e); } } @@ -416,7 +416,7 @@ public String createFromScratch(String dataSourceName, DatabaseProduct product, response = sqlAdmin.instances().insert(ctx.getAccountNumber(), content).execute(); } catch (GoogleJsonResponseException ge) { if ((ge.getStatusMessage().equals("Conflict")) && (ge.getStatusCode() == 409)) { - throw new GeneralCloudException("The name " + dataSourceName + " has been used in the past 2 months. Once used, DB names are reserved for 2 months after their decomission.", ge, CloudErrorType.GENERAL); + throw new GeneralCloudException("The name " + dataSourceName + " has been used in the past 2 months. Once used, DB names are reserved for 2 months after their decomission.", ge); } else { throw new Exception(ge); } @@ -425,7 +425,7 @@ public String createFromScratch(String dataSourceName, DatabaseProduct product, method.getRDSOperationCompleteLong(ctx, response.getName()); } catch (NullPointerException npe) { logger.error("getRDSOperationCompleteLong failed: " + npe); - throw new GeneralCloudException("getRDSOperationCompleteLong failed: " + npe, npe, CloudErrorType.GENERAL); + throw new GeneralCloudException("getRDSOperationCompleteLong failed: " + npe, npe); } try { @@ -883,7 +883,7 @@ public Iterable listDatabases() throws CloudException, InternalExcepti for (DatabaseInstance d : databaseInstances) { Settings s = d.getSettings(); if (null == s) { - throw new GeneralCloudException("getSettings() returned null!", CloudErrorType.GENERAL); + throw new GeneralCloudException("getSettings() returned null!"); } BackupConfiguration backupConfig = s.getBackupConfiguration(); @@ -1000,15 +1000,15 @@ public void removeDatabase(String providerDatabaseId) throws CloudException, Int if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; if ((gjre.getStatusMessage().equals("Conflict")) && (gjre.getStatusCode() == 409)) { - throw new GeneralCloudException("Database already deleted.", e, CloudErrorType.INVALID_STATE); + throw new GeneralCloudException("Database already deleted.", e); } else { throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } } else { - throw new GeneralCloudException("Exception deleting database", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception deleting database", e); } } catch (Exception e) { - throw new GeneralCloudException("Exception deleting database", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception deleting database", e); } Collection list = (Collection)listDatabasesCache.get(ctx); @@ -1043,10 +1043,10 @@ public void restart(String providerDatabaseId, boolean blockUntilDone) throws Cl GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception restarting database", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception restarting database", e); } } catch (Exception e) { - throw new GeneralCloudException("Exception restarting database", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception restarting database", e); } } @@ -1106,7 +1106,7 @@ public DatabaseBackup getUsableBackup(String providerDbId, String beforeTimestam if (bestCandidateBackup != null) { return bestCandidateBackup; } else { - throw new GeneralCloudException("No available backups meet requirements.", CloudErrorType.GENERAL); + throw new GeneralCloudException("No available backups meet requirements."); } } diff --git a/src/main/java/org/dasein/cloud/google/storage/DriveSupport.java b/src/main/java/org/dasein/cloud/google/storage/DriveSupport.java index 9f0a13c..1ab41dc 100644 --- a/src/main/java/org/dasein/cloud/google/storage/DriveSupport.java +++ b/src/main/java/org/dasein/cloud/google/storage/DriveSupport.java @@ -100,7 +100,7 @@ public DriveSupport(Google provider) { } catch( IOException e ) { logger.error("Could not fetch file to " + toFile + ": " + e.getMessage()); - throw new GeneralCloudException("Could not fetch file to \" + toFile + \": \" + e.getMessage()", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Could not fetch file to \" + toFile + \": \" + e.getMessage()", e); } } catch (IOException ex) { logger.error(ex.getMessage()); @@ -108,7 +108,7 @@ public DriveSupport(Google provider) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception downloading", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception downloading", ex); } } } @@ -158,7 +158,7 @@ public DriveSupport(Google provider) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception uploading", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception uploading", ex); } } } @@ -221,7 +221,7 @@ public DriveSupport(Google provider) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception creating bucket", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception creating bucket", ex); } } } @@ -273,7 +273,7 @@ public DriveSupport(Google provider) { } throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred when getting bucket: " + bucketName + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred when getting bucket: " + bucketName + ": " + ex.getMessage(), ex); } } } @@ -305,7 +305,7 @@ public DriveSupport(Google provider) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("An error occurred when getting object: " + objectName + ": " + ex.getMessage(), ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("An error occurred when getting object: " + objectName + ": " + ex.getMessage(), ex); } } } @@ -374,7 +374,7 @@ public DriveSupport(Google provider) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception checking object shared publicly", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception checking object shared publicly", ex); } } } @@ -423,7 +423,7 @@ public DriveSupport(Google provider) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception listing buckets", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception listing buckets", ex); } } } @@ -449,7 +449,7 @@ public DriveSupport(Google provider) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception making bucket public", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception making bucket public", ex); } } } @@ -475,7 +475,7 @@ public DriveSupport(Google provider) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception making object public", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception making object public", ex); } } } @@ -522,7 +522,7 @@ public DriveSupport(Google provider) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception removing bucket", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception removing bucket", ex); } } } @@ -548,7 +548,7 @@ public DriveSupport(Google provider) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else { - throw new GeneralCloudException("Exception removing object", ex, CloudErrorType.GENERAL); + throw new GeneralCloudException("Exception removing object", ex); } } } From 3d97192691d273632a0f8ef7649851c4eb55bbb8 Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Thu, 14 Apr 2016 14:23:35 +0100 Subject: [PATCH 02/15] remove ci support which doesn't reflect intended usage --- pom.xml | 2 +- .../cloud/ci/GCETopologyCapabilities.java | 25 - .../org/dasein/cloud/ci/GoogleCIServices.java | 44 -- .../cloud/ci/GoogleTopologySupport.java | 260 ------- .../dasein/cloud/ci/ReplicapoolTemplate.java | 174 ----- .../java/org/dasein/cloud/google/Google.java | 34 - .../org/dasein/cloud/google/GoogleMethod.java | 36 - .../GCEHttpLoadBalancerCapabilities.java | 127 ---- .../GCEReplicapoolCapabilities.java | 109 --- .../compute/server/ReplicapoolSupport.java | 251 ------- .../network/CIHttpLoadBalancerSupport.java | 641 ------------------ 11 files changed, 1 insertion(+), 1702 deletions(-) delete mode 100644 src/main/java/org/dasein/cloud/ci/GCETopologyCapabilities.java delete mode 100644 src/main/java/org/dasein/cloud/ci/GoogleCIServices.java delete mode 100644 src/main/java/org/dasein/cloud/ci/GoogleTopologySupport.java delete mode 100644 src/main/java/org/dasein/cloud/ci/ReplicapoolTemplate.java delete mode 100644 src/main/java/org/dasein/cloud/google/capabilities/GCEHttpLoadBalancerCapabilities.java delete mode 100644 src/main/java/org/dasein/cloud/google/capabilities/GCEReplicapoolCapabilities.java delete mode 100644 src/main/java/org/dasein/cloud/google/compute/server/ReplicapoolSupport.java delete mode 100644 src/main/java/org/dasein/cloud/google/network/CIHttpLoadBalancerSupport.java diff --git a/pom.xml b/pom.xml index af65065..3d84700 100644 --- a/pom.xml +++ b/pom.xml @@ -59,7 +59,7 @@ org.dasein dasein-cloud-core - 0.9.0 + 0.9.5-SNAPSHOT org.dasein diff --git a/src/main/java/org/dasein/cloud/ci/GCETopologyCapabilities.java b/src/main/java/org/dasein/cloud/ci/GCETopologyCapabilities.java deleted file mode 100644 index 7931a60..0000000 --- a/src/main/java/org/dasein/cloud/ci/GCETopologyCapabilities.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.dasein.cloud.ci; - -import javax.annotation.Nonnull; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.google.Google; -import org.dasein.cloud.util.NamingConstraints; - -public class GCETopologyCapabilities implements TopologyCapabilities { - - public GCETopologyCapabilities(Google provider) { - // TODO Auto-generated constructor stub - } - - @Override - public @Nonnull NamingConstraints getTopologyNamingConstraints() throws CloudException, InternalException { - return NamingConstraints.getAlphaNumeric(1, 63) - .withRegularExpression("^[a-z][-a-z0-9]{0,61}[a-z0-9]$") - .lowerCaseOnly() - .withNoSpaces() - .withLastCharacterSymbolAllowed(false) - .constrainedBy('-'); - } - -} diff --git a/src/main/java/org/dasein/cloud/ci/GoogleCIServices.java b/src/main/java/org/dasein/cloud/ci/GoogleCIServices.java deleted file mode 100644 index 1c3fa4f..0000000 --- a/src/main/java/org/dasein/cloud/ci/GoogleCIServices.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.dasein.cloud.ci; - -import javax.annotation.Nullable; - -import org.dasein.cloud.google.Google; -import org.dasein.cloud.google.compute.server.ReplicapoolSupport; -import org.dasein.cloud.google.network.CIHttpLoadBalancerSupport; - -public class GoogleCIServices extends AbstractCIServices { - - public GoogleCIServices(Google provider) { - super(provider); - } - - @Override - public @Nullable ConvergedInfrastructureSupport getConvergedInfrastructureSupport() { - return new ReplicapoolSupport(getProvider()); - } - - @Override - public @Nullable TopologySupport getTopologySupport() { - return new GoogleTopologySupport(getProvider()); - } - - @Override - public boolean hasConvergedInfrastructureSupport() { - return (getConvergedInfrastructureSupport() == null); - } - - @Override - public boolean hasTopologySupport() { - return (getTopologySupport() == null); - } - - @Override - public ConvergedHttpLoadBalancerSupport getConvergedHttpLoadBalancerSupport() { - return new CIHttpLoadBalancerSupport(getProvider()); - } - - @Override - public boolean hasConvergedHttpLoadBalancerSupport() { - return (getConvergedHttpLoadBalancerSupport() != null); - } -} diff --git a/src/main/java/org/dasein/cloud/ci/GoogleTopologySupport.java b/src/main/java/org/dasein/cloud/ci/GoogleTopologySupport.java deleted file mode 100644 index e1cbc69..0000000 --- a/src/main/java/org/dasein/cloud/ci/GoogleTopologySupport.java +++ /dev/null @@ -1,260 +0,0 @@ -package org.dasein.cloud.ci; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.services.compute.Compute.InstanceTemplates; -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.InstanceProperties; -import com.google.api.services.compute.model.InstanceTemplate; -import com.google.api.services.compute.model.InstanceTemplateList; -import com.google.api.services.compute.model.Metadata; -import com.google.api.services.compute.model.Metadata.Items; -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; -import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.GeneralCloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ci.Topology.VLANDevice; -import org.dasein.cloud.ci.Topology.VMDevice; -import org.dasein.cloud.ci.TopologyProvisionOptions.Disk; -import org.dasein.cloud.ci.TopologyProvisionOptions.Network; -import org.dasein.cloud.compute.Architecture; -import org.dasein.cloud.compute.MachineImage; -import org.dasein.cloud.compute.VirtualMachineProduct; -import org.dasein.cloud.google.Google; -import org.dasein.cloud.google.GoogleException; -import org.dasein.cloud.google.GoogleMethod; -import org.dasein.cloud.google.GoogleOperationType; -import org.dasein.cloud.google.compute.server.ServerSupport; - -import javax.annotation.Nonnull; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -public class GoogleTopologySupport extends AbstractTopologySupport { - static private final Logger logger = Google.getLogger(GoogleTopologySupport.class); - private InstanceTemplates instanceTemplates = null;; - - public GoogleTopologySupport(Google provider) { - super(provider); - try { - instanceTemplates = getProvider().getGoogleCompute().instanceTemplates(); - - } catch ( CloudException e ) { - logger.error(e); - } catch ( InternalException e ) { - logger.error(e); - } - } - - @Override - public String getProviderTermForTopology(Locale locale) { - return "Instance Template"; - } - - @Override - public boolean isSubscribed() throws CloudException, InternalException { - return true; - } - - @Override - public Iterable listTopologies(TopologyFilterOptions options) throws CloudException, InternalException { - List topologies = new ArrayList(); - try { - InstanceTemplateList templateList = instanceTemplates.list(getContext().getAccountNumber()).execute(); - if (templateList != null && templateList.getItems() != null) { - for (InstanceTemplate template : templateList.getItems()) { - InstanceProperties templateProperties = template.getProperties(); - VMDevice vmDevices = null; - String machineType = templateProperties.getMachineType(); - ServerSupport server = new ServerSupport(getProvider()); - Iterable vmProducts = server.listProducts(Architecture.I64, "us-central1-f"); - for (VirtualMachineProduct vmProduct : vmProducts) { - if ( vmProduct.getName().equals(machineType) ) { - vmDevices = VMDevice.getInstance(machineType, machineType, vmProduct.getCpuCount(), vmProduct.getRamSize(), (String) null); - } - } - - List networkInterfaces = templateProperties.getNetworkInterfaces(); - String name = null; - String deviceId = null; - for (NetworkInterface networkInterface : networkInterfaces) { - deviceId = networkInterface.getNetwork(); - name = deviceId.replaceAll(".*/", ""); - } - - Topology topology = Topology.getInstance(getContext().getAccountNumber(), null, template.getName(), TopologyState.ACTIVE, template.getName(), template.getDescription()); - - if ( null != vmDevices ) { - topology = topology.withVirtualMachines(vmDevices); - } - - if ( (null != name) && (null != deviceId) ) { - topology = topology.withVLANs(VLANDevice.getInstance(deviceId, name)); - } - - if ( (null == options) || (options.matches(topology)) ) { - topologies.add(topology); - } - } - } - } catch ( IOException e ) { - throw new GeneralCloudException("Problem listing topologies", e, CloudErrorType.GENERAL); - } - - return topologies; - } - - @Override - public boolean createTopology(@Nonnull TopologyProvisionOptions withTopologyOptions) throws CloudException, InternalException { - InstanceTemplate newInstanceTemplate = new InstanceTemplate(); - - newInstanceTemplate.setName(getCapabilities().getTopologyNamingConstraints().convertToValidName(withTopologyOptions.getProductName(), Locale.US)); - newInstanceTemplate.setDescription(withTopologyOptions.getProductDescription()); - InstanceProperties instanceProperties = new InstanceProperties(); - instanceProperties.setCanIpForward(withTopologyOptions.getCanIpForward()); - instanceProperties.setDescription(withTopologyOptions.getProductDescription()); - - VirtualMachineProduct p = getProvider().getComputeServices().getVirtualMachineSupport().getProduct(withTopologyOptions.getMachineType()); - instanceProperties.setMachineType(p.getName()); - - List disks = withTopologyOptions.getDiskArray(); - List attachedDisks = new ArrayList(); - for (Disk topologyDisk : disks) { - AttachedDisk disk = new AttachedDisk(); - disk.setAutoDelete(topologyDisk.getAutoDelete()); - disk.setBoot(topologyDisk.getBootable()); - disk.setDeviceName(withTopologyOptions.getProductName()); - AttachedDiskInitializeParams attachedDiskInitializeParams = new AttachedDiskInitializeParams(); - MachineImage img = getProvider().getComputeServices().getImageSupport().getImage(topologyDisk.getDeviceSource()); - attachedDiskInitializeParams.setSourceImage(img.getTag("contentLink").toString()); - if (topologyDisk.getDeviceType() == TopologyProvisionOptions.DiskType.SSD_PERSISTENT_DISK) { - attachedDiskInitializeParams.setDiskType("pd-ssd"); - } else { - attachedDiskInitializeParams.setDiskType("pd-standard"); - } - - disk.setInitializeParams(attachedDiskInitializeParams); - attachedDisks.add(disk); - } - instanceProperties.setDisks(attachedDisks); //must provide at least one AttachedDisk definition. - - List topologyNetworksList = withTopologyOptions.getNetworkArray(); - List networks = new ArrayList(); - for (Network topologyNetwork : topologyNetworksList) { - NetworkInterface networkInterface = new NetworkInterface(); - networkInterface.setName(topologyNetwork.getNetworkName()); - - List topologyNetworksAccessConfig = topologyNetwork.getAccessConfig(); - List accessConfig = new ArrayList(); - - for (TopologyProvisionOptions.AccessConfig topologyAccessConfig : topologyNetworksAccessConfig) { - AccessConfig cfg = new AccessConfig(); - cfg.setName(topologyAccessConfig.getName()); - cfg.setKind("compute#accessConfig"); - cfg.setType(topologyAccessConfig.getType()); - accessConfig.add(cfg); - } - networkInterface.setAccessConfigs(accessConfig); - networks.add(networkInterface); - } - instanceProperties.setNetworkInterfaces(networks); - - Tags tags = new Tags(); - tags.setItems(withTopologyOptions.getTags()); - instanceProperties.setTags(tags); - - String[] sshKeys = withTopologyOptions.getSshKeys(); - Metadata metadata = new Metadata(); - List metadataItems = new ArrayList(); - for (String sshKey : sshKeys) { - Metadata.Items item = new Metadata.Items() ; - item.setKey("sshKeys"); - item.setValue(sshKey); - metadataItems.add(item); - } - - Map metaDataItems = withTopologyOptions.getMetadata(); - for (String itemKey : metaDataItems.keySet()) { - Metadata.Items item = new Metadata.Items() ; - item.setKey(itemKey); - item.setValue(metaDataItems.get(itemKey)); - metadataItems.add(item); - } - - metadata.setItems(metadataItems); - instanceProperties.setMetadata(metadata); - - Scheduling scheduling = new Scheduling(); - scheduling.setAutomaticRestart(withTopologyOptions.getAutomaticRestart()); - if (withTopologyOptions.getMaintenenceAction() == TopologyProvisionOptions.MaintenanceOption.MIGRATE_VM_INSTANCE) { - scheduling.setOnHostMaintenance("MIGRATE"); - } else { - scheduling.setOnHostMaintenance("TERMINATE"); - } - instanceProperties.setScheduling(scheduling); - -/* - List serviceAccounts = new ArrayList(); - ServiceAccount serviceAccount = new ServiceAccount(); - serviceAccount.setEmail("email"); - List scopes = new ArrayList(); - serviceAccount.setScopes(scopes); - serviceAccounts.add(serviceAccount); - instanceProperties.setServiceAccounts(serviceAccounts); - -*/ - newInstanceTemplate.setProperties(instanceProperties); - try { - Operation job = instanceTemplates.insert(getContext().getAccountNumber(), newInstanceTemplate).execute(); - GoogleMethod method = new GoogleMethod(getProvider()); - method.getOperationComplete(getContext(), job, GoogleOperationType.GLOBAL_OPERATION, "", ""); - } catch (IOException ex) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException(ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - return true; - } - - @Override - public boolean removeTopologies(@Nonnull String[] topologyIds) throws CloudException, InternalException { - for (String topologyName: topologyIds) { - try { - Operation job = instanceTemplates.delete(getContext().getAccountNumber(), topologyName).execute(); - GoogleMethod method = new GoogleMethod(getProvider()); - method.getOperationComplete(getContext(), job, GoogleOperationType.GLOBAL_OPERATION, "", ""); - } catch (IOException ex) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException(ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - } - return true; - } - - private transient volatile GCETopologyCapabilities capabilities; - - @Override - public @Nonnull GCETopologyCapabilities getCapabilities() throws CloudException, InternalException { - if( capabilities == null ) { - capabilities = new GCETopologyCapabilities(getProvider()); - } - return capabilities; - } - -} diff --git a/src/main/java/org/dasein/cloud/ci/ReplicapoolTemplate.java b/src/main/java/org/dasein/cloud/ci/ReplicapoolTemplate.java deleted file mode 100644 index a240f23..0000000 --- a/src/main/java/org/dasein/cloud/ci/ReplicapoolTemplate.java +++ /dev/null @@ -1,174 +0,0 @@ -/** - * Copyright (C) 2012-2014 Dell, Inc - * See annotations for authorship information - * - * ==================================================================== - * 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 org.dasein.cloud.ci; - -import javax.annotation.Nonnull; - -import org.dasein.cloud.CloudProvider; -import org.dasein.cloud.Tag; -import org.dasein.cloud.compute.VirtualMachineProduct; - -import com.google.api.services.compute.model.Metadata; - -/** - * Implements the Replicapool Templates supported in the Google API. - * @author Roger Unwin - * @version 2015.03 initial version - * @since 2015.03 - */ - -public class ReplicapoolTemplate { - - private boolean automaticRestart = false; - private boolean maintenenceMigration = false; - private boolean ipForwarding = false; - private String[] readonlyDisks = new String[0]; - private Tag[] tags = new Tag[0]; - private String[] sshKeys = new String[0]; - private String poolName = null; - private Metadata metadata; - private boolean allowHttp = false; - private boolean allowHttps = false; - private VirtualMachineProduct vmProduct; - private String providerImageId; - private String bootDiskType; - private boolean deleteDiskOnTerminate; - private boolean assignEphemeralExternalIp; - - public ReplicapoolTemplate(@Nonnull String poolName, - @Nonnull Metadata metadata, - @Nonnull boolean allowHttp, - @Nonnull boolean allowHttps, - @Nonnull VirtualMachineProduct vmProduct, - @Nonnull String providerImageId, - @Nonnull String bootDiskType, // Standard persistent disk or SSD - @Nonnull boolean deleteDiskOnTerminate, - @Nonnull boolean assignEphemeralExternalIp) { - this.poolName = poolName; - this.metadata = metadata; - this.allowHttp = allowHttp; - this.allowHttps = allowHttps; - this.vmProduct = vmProduct; - this.providerImageId = providerImageId; - this.bootDiskType = bootDiskType; - this.deleteDiskOnTerminate = deleteDiskOnTerminate; - this.assignEphemeralExternalIp = assignEphemeralExternalIp; - } - - public ReplicapoolTemplate withSshKeys(@Nonnull String[] sshKeys) { - this.sshKeys = sshKeys; - return this; - } - - public String[] getSshKeys() { - return sshKeys; - } - - public ReplicapoolTemplate withTags(Tag... tags) { - this.tags = tags; - return this; - } - - public Tag[] getTags() { - return tags; - } - - public ReplicapoolTemplate withReadonlyDisks(String[] readonlyDisks) { - this.readonlyDisks = readonlyDisks; - return this; - } - - public String[] getReadonlyDisks() { - return readonlyDisks; - } - - public ReplicapoolTemplate withIpForwarding(boolean ipForwarding) { - this.ipForwarding = ipForwarding; - return this; - } - - public boolean hasIpForwarding() { - return ipForwarding; - } - - public ReplicapoolTemplate withAutomaticRestart(boolean automaticRestart) { - this.automaticRestart = automaticRestart; - return this; - } - - public boolean hasAutomaticRestart() { - return automaticRestart; - } - - public ReplicapoolTemplate withMaintenenceMigration(boolean maintenenceMigration) { - this.maintenenceMigration = maintenenceMigration; - return this; - } - - public boolean hasMaintenenceMigration() { - return maintenenceMigration; - } - - public String getPoolName() { - return poolName; - } - - public Metadata getMetadata() { - return metadata; - } - - public boolean getAllowHttp() { - return allowHttp; - } - - public boolean getAllowHttps() { - return allowHttps; - } - - public VirtualMachineProduct getVmProduct() { - return vmProduct; - } - - public String getProviderImageId() { - return providerImageId; - } - - public String getBootDiskType() { - return bootDiskType; - } - - public boolean getDeleteDiskOnTerminate() { - return deleteDiskOnTerminate; - } - - public boolean getAssignEphemeralExternalIp() { - return assignEphemeralExternalIp; - } - - public boolean create(CloudProvider provider) { - return false; - // TODO Auto-generated method stub - } - - public boolean remove(CloudProvider provider) { - return false; - // TODO Auto-generated method stub - } -} diff --git a/src/main/java/org/dasein/cloud/google/Google.java b/src/main/java/org/dasein/cloud/google/Google.java index efa9ab8..08eac6a 100755 --- a/src/main/java/org/dasein/cloud/google/Google.java +++ b/src/main/java/org/dasein/cloud/google/Google.java @@ -37,8 +37,6 @@ import org.dasein.cloud.ContextRequirements; import org.dasein.cloud.InternalException; import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.ci.CIServices; -import org.dasein.cloud.ci.GoogleCIServices; import org.dasein.cloud.google.compute.GoogleCompute; import org.dasein.cloud.google.network.GoogleNetwork; import org.dasein.cloud.google.platform.GooglePlatform; @@ -347,38 +345,6 @@ public SQLAdmin getGoogleSQLAdmin() throws CloudException, InternalException{ return googleSql.iterator().next(); } - @Override - public @Nullable CIServices getCIServices() { - return new GoogleCIServices(this); - } - - public Replicapool getGoogleReplicapool() throws CloudException, InternalException{ - ProviderContext ctx = getContext(); - Collection cachedCredential = (Collection)cachedCredentials.get(ctx); - Collection replicaPool = (Collection)replicapoolCache.get(ctx); - try { - final HttpTransport transport = getTransport(); - if (cachedCredential == null) { - cachedCredential = new ArrayList(); - cachedCredential.add(getCreds(transport, jsonFactory, sqlScope)); - cachedCredentials.put(ctx, cachedCredential); - } - - if (replicaPool == null) { - replicaPool = new ArrayList(); - replicaPool.add((Replicapool) new Replicapool.Builder(transport, jsonFactory, cachedCredential.iterator().next()).setApplicationName(ctx.getAccountNumber()).setHttpRequestInitializer(initializer).build()); - replicapoolCache.put(ctx, replicaPool); - } - } catch (Exception ex){ - throw new AuthenticationException(400, "Bad Credentials", "An authentication error has occurred: Bad Credentials"); - } - - initializer.setStackedRequestInitializer(ctx, cachedCredential.iterator().next()); - LogHandler.verifyInitialized(); - - return replicaPool.iterator().next(); - } - @Override public @Nullable String testContext() { if (logger.isTraceEnabled()) { diff --git a/src/main/java/org/dasein/cloud/google/GoogleMethod.java b/src/main/java/org/dasein/cloud/google/GoogleMethod.java index 4cf5328..75be446 100755 --- a/src/main/java/org/dasein/cloud/google/GoogleMethod.java +++ b/src/main/java/org/dasein/cloud/google/GoogleMethod.java @@ -21,8 +21,6 @@ import com.google.api.services.compute.Compute; import com.google.api.services.compute.model.Operation; -import com.google.api.services.replicapool.Replicapool; -import com.google.api.services.replicapool.model.Operation.Error.Errors; import com.google.api.services.sqladmin.SQLAdmin; import com.google.api.services.sqladmin.model.OperationError; import org.apache.log4j.Logger; @@ -201,38 +199,4 @@ public void getRDSOperationCompleteLong(ProviderContext ctx, String operation) t } throw new CommunicationException(408, "", "System timed out waiting for Operation to complete"); } - - public @Nonnull boolean getCIOperationComplete(ProviderContext ctx, com.google.api.services.replicapool.model.Operation job, GoogleOperationType operationType, String regionId, String dataCenterId) throws CloudException, InternalException { - long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 20L); - Replicapool rp; - - try { - rp = provider.getGoogleReplicapool(); - } catch ( InternalException e ) { - throw new InternalException("Cannot get Compute(google)"); - } - - while (timeout > System.currentTimeMillis()) { - try { - job = rp.zoneOperations().get(ctx.getAccountNumber(), dataCenterId, job.getName()).execute(); - } catch(IOException ex) { - System.out.println(ex); - } - - if (job.getError() != null) { - for (Errors error : job.getError().getErrors()) { - throw new GeneralCloudException("An error occurred: " + error.getMessage()); - } - } - else if (job.getStatus().equals("DONE")) { - return true; - } - - try { - Thread.sleep(1000L); - } catch (InterruptedException ignore) { } - - } - throw new CommunicationException(408, "", "System timed out waiting for Operation to complete"); - } } diff --git a/src/main/java/org/dasein/cloud/google/capabilities/GCEHttpLoadBalancerCapabilities.java b/src/main/java/org/dasein/cloud/google/capabilities/GCEHttpLoadBalancerCapabilities.java deleted file mode 100644 index 5945a2a..0000000 --- a/src/main/java/org/dasein/cloud/google/capabilities/GCEHttpLoadBalancerCapabilities.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright (C) 2012-2014 Dell, Inc - * See annotations for authorship information - * - * ==================================================================== - * 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 org.dasein.cloud.google.capabilities; - -import org.dasein.cloud.AbstractCapabilities; -import org.dasein.cloud.ci.HttpLoadBalancerCapabilities; -import org.dasein.cloud.google.Google; -import org.dasein.cloud.util.NamingConstraints; - -import javax.annotation.Nonnull; -import java.util.Arrays; -import java.util.Collections; -import java.util.Locale; - -public class GCEHttpLoadBalancerCapabilities extends AbstractCapabilities implements HttpLoadBalancerCapabilities { - - public GCEHttpLoadBalancerCapabilities(Google provider) { - super(provider); - } - - @Override - public boolean supportsHttpTraffic() { - return true; - } - - @Override - public boolean supportsHttpsTraffic() { - return false; - } - - @Override - public boolean supportsHealthChecks() { - return true; - } - - @Override - public boolean supportsMoreThanOneHealthCheck() { - return false; - } - - @Override - public boolean supportsBackendServices() { - return true; - } - - @Override - public boolean supportsMoreThanOneBackendService() { - return true; - } - - @Override - public boolean supportsUrlSets() { - return true; - } - - @Override - public boolean supportsMoreThanOneUrlSet() { - return true; - } - - @Override - public boolean supportsTargetHttpProxies() { - return true; - } - - @Override - public boolean supportsMoreThanOneTargetHttpProxy() { - return true; - } - - @Override - public boolean supportsForwardingRules() { - return true; - } - - @Override - public boolean supportsMoreThanOneForwardingRule() { - return true; - } - - @Override - public String getProviderTermForHttpLoadBalancer(Locale locale) { - return "HTTP Load Balancer"; - } - - @Override - public Iterable listSupportedHttpPorts() { - return Collections.unmodifiableList(Arrays.asList("80", "8080")); - } - - @Override - public boolean supportsUsingExistingHealthCheck() { - return true; - } - - @Override - public boolean supportsUsingExistingBackendService() { - return true; - } - - @Override - public @Nonnull NamingConstraints getConvergedHttpLoadBalancerNamingConstraints() { - return NamingConstraints.getAlphaNumeric(1, 63) - .withRegularExpression("^[a-z][-a-z0-9]{0,61}[a-z0-9]$") - .lowerCaseOnly() - .withNoSpaces() - .withLastCharacterSymbolAllowed(false) - .constrainedBy('-'); - } -} diff --git a/src/main/java/org/dasein/cloud/google/capabilities/GCEReplicapoolCapabilities.java b/src/main/java/org/dasein/cloud/google/capabilities/GCEReplicapoolCapabilities.java deleted file mode 100644 index 8af9412..0000000 --- a/src/main/java/org/dasein/cloud/google/capabilities/GCEReplicapoolCapabilities.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright (C) 2012-2014 Dell, Inc - * See annotations for authorship information - * - * ==================================================================== - * 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 org.dasein.cloud.google.capabilities; - -import org.dasein.cloud.AbstractCapabilities; -import org.dasein.cloud.ci.ConvergedInfrastructureCapabilities; -import org.dasein.cloud.google.Google; -import org.dasein.cloud.util.NamingConstraints; -import javax.annotation.Nonnull; - -/** - * @author Roger Unwin - * @version 2015.03 initial version - * @since 2015.03 - */ -public class GCEReplicapoolCapabilities extends AbstractCapabilities implements ConvergedInfrastructureCapabilities { - - public GCEReplicapoolCapabilities(Google provider) { - super(provider); - // TODO Auto-generated constructor stub - } - - public boolean supportsHttpTraffic() { - return true; - } - - public boolean supportsHttpsTraffic() { - return true; - } - - public boolean supportsMetadata() { - return true; - } - - public boolean supportsSshKeys() { - return true; - } - - public boolean supportsTags() { - return true; - } - - public boolean supportsSsdDisk() { - return true; - } - - public boolean supportsStandardDisk() { - return true; - } - - public boolean supportsDeleteDiskOnTerminate() { - return true; - } - - public boolean supportsReadOnlySharedDisks() { - return true; - } - - public boolean supportsVmAutomaticRestart() { - return true; - } - - public boolean supportsMigrateVmOnMaintenance() { - return true; - } - - public boolean supportsTemplates() { - return true; - } - - public boolean supportsRegions() { // Zone - return true; - } - - public boolean supportsCreateFromInstance() { - return true; - } - - public boolean supportsAutoScaling() { - return true; - } - - @Override - public @Nonnull NamingConstraints getConvergedInfrastructureNamingConstraints() { - return NamingConstraints.getAlphaNumeric(1, 63) - .withRegularExpression("^[a-z][-a-z0-9]{0,61}[a-z0-9]$") - .lowerCaseOnly() - .withNoSpaces() - .withLastCharacterSymbolAllowed(false) - .constrainedBy('-'); - } -} diff --git a/src/main/java/org/dasein/cloud/google/compute/server/ReplicapoolSupport.java b/src/main/java/org/dasein/cloud/google/compute/server/ReplicapoolSupport.java deleted file mode 100644 index 57caf14..0000000 --- a/src/main/java/org/dasein/cloud/google/compute/server/ReplicapoolSupport.java +++ /dev/null @@ -1,251 +0,0 @@ -/** - * Copyright (C) 2012-2014 Dell, Inc - * See annotations for authorship information - * - * ==================================================================== - * 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 org.dasein.cloud.google.compute.server; - -import com.google.api.services.compute.Compute; -import com.google.api.services.compute.model.Instance; -import com.google.api.services.compute.model.InstanceList; -import com.google.api.services.compute.model.NetworkInterface; -import com.google.api.services.replicapool.Replicapool; -import com.google.api.services.replicapool.model.InstanceGroupManager; -import com.google.api.services.replicapool.model.InstanceGroupManagerList; -import com.google.api.services.replicapool.model.Operation; -import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.GeneralCloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.ci.AbstractConvergedInfrastructureSupport; -import org.dasein.cloud.ci.CIFilterOptions; -import org.dasein.cloud.ci.CIProvisionOptions; -import org.dasein.cloud.ci.ConvergedInfrastructure; -import org.dasein.cloud.ci.ConvergedInfrastructureState; -import org.dasein.cloud.dc.DataCenter; -import org.dasein.cloud.dc.Region; -import org.dasein.cloud.google.Google; -import org.dasein.cloud.google.GoogleMethod; -import org.dasein.cloud.google.GoogleOperationType; -import org.dasein.cloud.google.capabilities.GCEReplicapoolCapabilities; -import org.dasein.cloud.util.APITrace; - -import javax.annotation.Nonnull; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -/** - * Implements the replicapool services supported in the Google API. - * @author Roger Unwin - * @version 2015.03 initial version - * @since 2015.03 - */ -public class ReplicapoolSupport extends AbstractConvergedInfrastructureSupport { - static private final Logger logger = Google.getLogger(ReplicapoolSupport.class); - private Google provider = null; - - public ReplicapoolSupport(Google provider) { - super(provider); - this.provider = provider; - } - - @Override - public boolean isSubscribed() throws CloudException, InternalException { - APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.isSubscribed"); - try { - return true; // cop-out for now. - } finally{ - APITrace.end(); - } - } - - private transient volatile GCEReplicapoolCapabilities capabilities; - - public @Nonnull GCEReplicapoolCapabilities getCapabilities() { - if( capabilities == null ) { - capabilities = new GCEReplicapoolCapabilities(provider); - } - return capabilities; - } - - @Override - public Iterable listConvergedInfrastructures(CIFilterOptions options) throws CloudException, InternalException { - APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.listConvergedInfrastructures"); - List convergedInfrastrutures = new ArrayList(); - try { - Replicapool rp = provider.getGoogleReplicapool(); - - InstanceGroupManagerList result = null; - try { - for (Region region : provider.getDataCenterServices().listRegions()) { - String regionName = region.getProviderRegionId(); - for (DataCenter dataCenter : provider.getDataCenterServices().listDataCenters(regionName)) { - String dataCenterId = dataCenter.getProviderDataCenterId(); - result = rp.instanceGroupManagers().list(provider.getContext().getAccountNumber(), dataCenterId).execute(); //provider.getContext().getRegionId() - if (null != result.getItems()) { - for (InstanceGroupManager item : result.getItems()) { - ConvergedInfrastructure ci = ConvergedInfrastructure.getInstance(provider.getContext().getAccountNumber(), - regionName, dataCenterId, item.getName(), ConvergedInfrastructureState.RUNNING, item.getName(), item.getDescription(), item.getInstanceTemplate()); - ci.setTag("selfLink", item.getSelfLink()); - ci.setTag("instanceGroupLink", item.getGroup()); - if (options != null) { - if (options.matches(ci)) { - convergedInfrastrutures.add(ci); - } - } - else { - convergedInfrastrutures.add(ci); - } - } - } - } - } - } catch ( IOException e ) { - throw new GeneralCloudException("Error listing converged infrastructure", e, CloudErrorType.GENERAL); - } - } finally{ - APITrace.end(); - } - return convergedInfrastrutures; - } - - @Override - public Iterable listVirtualMachines(String inCIId) throws InternalException, CloudException { - APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.listVirtualMachines"); - List vms = new ArrayList(); - try { - Replicapool rp = provider.getGoogleReplicapool(); - Compute gce = provider.getGoogleCompute(); - String datacenterId = null; - Iterable cis = listConvergedInfrastructures(null); - for (ConvergedInfrastructure ci : cis) { - if (ci.getName().equals(inCIId)) { - datacenterId = ci.getProviderDataCenterId(); - } - } - - InstanceGroupManager pool = rp.instanceGroupManagers().get(provider.getContext().getAccountNumber(), datacenterId, inCIId).execute(); - String baseInstanceName = pool.getBaseInstanceName(); - InstanceList result = gce.instances().list(provider.getContext().getAccountNumber(), datacenterId).execute(); - for (Instance instance : result.getItems()) { - if (instance.getName().startsWith(baseInstanceName + "-")) { - vms.add(instance.getName()); - } - } - return vms; - } catch ( IOException e ) { - throw new GeneralCloudException("Error listing virtual machines", e, CloudErrorType.GENERAL); - } finally{ - APITrace.end(); - } - } - - @Override - public Iterable listVLANs(String inCIId) throws CloudException, InternalException { - APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.listVLANs"); - List nets = new ArrayList(); - try { - Replicapool rp = provider.getGoogleReplicapool(); - Compute gce = provider.getGoogleCompute(); - - String datacenterId = null; - Iterable cis = listConvergedInfrastructures(null); - for (ConvergedInfrastructure ci : cis) { - if (ci.getName().equals(inCIId)) { - datacenterId = ci.getProviderDataCenterId(); - } - } - - InstanceGroupManager pool = rp.instanceGroupManagers().get(provider.getContext().getAccountNumber(), datacenterId, inCIId).execute(); - String baseInstanceName = pool.getBaseInstanceName(); - InstanceList result = gce.instances().list(provider.getContext().getAccountNumber(), datacenterId).execute(); - for (Instance instance : result.getItems()) { - if (instance.getName().startsWith(baseInstanceName + "-")) { - if (null != instance.getNetworkInterfaces()) { - for (NetworkInterface net : instance.getNetworkInterfaces()) { - nets.add(net.getNetwork().replaceAll(".*/", "")); - } - } - } - } - return nets; - } catch ( IOException e ) { - throw new GeneralCloudException("Error listing vlans", e, CloudErrorType.GENERAL); - } finally{ - APITrace.end(); - } - } - - /* - * Create a replicaPool based on options in CIProvisionOptions options - * @see org.dasein.cloud.ci.ConvergedInfrastructureSupport#provision(org.dasein.cloud.ci.CIProvisionOptions) - */ - @Override - public ConvergedInfrastructure provision(CIProvisionOptions options) throws CloudException, InternalException { - APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.provision"); - Replicapool rp = provider.getGoogleReplicapool(); - try { - ProviderContext ctx = provider.getContext(); - InstanceGroupManager content = new InstanceGroupManager(); - content.setBaseInstanceName(getCapabilities().getConvergedInfrastructureNamingConstraints().convertToValidName(options.getBaseInstanceName(), Locale.US)); - content.setDescription(options.getDescription()); - content.setInstanceTemplate("https://www.googleapis.com/compute/v1/projects/" + ctx.getAccountNumber() + "/global/instanceTemplates/" + options.getInstanceTemplate()); - content.setName(getCapabilities().getConvergedInfrastructureNamingConstraints().convertToValidName(options.getName(), Locale.US)); - String region = options.getZone().replaceFirst("-.$", ""); - //content.setTargetPools(targetPools); - Operation job = rp.instanceGroupManagers().insert(ctx.getAccountNumber(), options.getZone(), options.getSize(), content).execute(); - GoogleMethod method = new GoogleMethod(provider); - method.getCIOperationComplete(ctx, job, GoogleOperationType.ZONE_OPERATION, region, options.getZone()); - return ConvergedInfrastructure.getInstance(ctx.getAccountNumber(), region, options.getZone(), options.getBaseInstanceName(), ConvergedInfrastructureState.RUNNING, options.getName(), options.getDescription(), options.getInstanceTemplate()); - } catch ( IOException e ) { - throw new GeneralCloudException("Error provisioning", e, CloudErrorType.GENERAL); - } finally{ - APITrace.end(); - } - } - - @Override - public void terminate(String ciId, String explanation) throws CloudException, InternalException { - APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.terminate"); - ProviderContext ctx = provider.getContext(); - - try { - Replicapool rp = provider.getGoogleReplicapool(); - for (ConvergedInfrastructure ci : listConvergedInfrastructures(null)) { - if (ci.getName().equals(ciId)) { - Operation job = rp.instanceGroupManagers().delete(provider.getContext().getAccountNumber(), ci.getProviderDataCenterId(), ciId).execute(); - GoogleMethod method = new GoogleMethod(provider); - method.getCIOperationComplete(ctx, job, GoogleOperationType.ZONE_OPERATION, ctx.getRegionId(), ci.getProviderDataCenterId()); - } - } - } catch ( IOException e ) { - throw new GeneralCloudException("Error terminating", e, CloudErrorType.GENERAL); - - } finally { - APITrace.end(); - } - } - - @Override - public boolean hasConvergedHttpLoadBalancerSupport() { - return true; - } -} diff --git a/src/main/java/org/dasein/cloud/google/network/CIHttpLoadBalancerSupport.java b/src/main/java/org/dasein/cloud/google/network/CIHttpLoadBalancerSupport.java deleted file mode 100644 index cb50b23..0000000 --- a/src/main/java/org/dasein/cloud/google/network/CIHttpLoadBalancerSupport.java +++ /dev/null @@ -1,641 +0,0 @@ -package org.dasein.cloud.google.network; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.services.compute.Compute; -import com.google.api.services.compute.model.Backend; -import com.google.api.services.compute.model.BackendService; -import com.google.api.services.compute.model.ForwardingRule; -import com.google.api.services.compute.model.ForwardingRuleList; -import com.google.api.services.compute.model.HostRule; -import com.google.api.services.compute.model.HttpHealthCheck; -import com.google.api.services.compute.model.Operation; -import com.google.api.services.compute.model.PathMatcher; -import com.google.api.services.compute.model.PathRule; -import com.google.api.services.compute.model.TargetHttpProxy; -import com.google.api.services.compute.model.TargetHttpProxyList; -import com.google.api.services.compute.model.UrlMap; -import com.google.api.services.compute.model.UrlMapList; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.GeneralCloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.Tag; -import org.dasein.cloud.ci.AbstractConvergedHttpLoadBalancer; -import org.dasein.cloud.ci.ConvergedHttpLoadBalancer; -import org.dasein.cloud.ci.HttpLoadBalancerCapabilities; -import org.dasein.cloud.google.Google; -import org.dasein.cloud.google.GoogleException; -import org.dasein.cloud.google.GoogleMethod; -import org.dasein.cloud.google.GoogleOperationType; -import org.dasein.cloud.google.capabilities.GCEHttpLoadBalancerCapabilities; -import org.dasein.cloud.identity.ServiceAction; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -public class CIHttpLoadBalancerSupport extends AbstractConvergedHttpLoadBalancer { - - private Google provider; - private ProviderContext ctx; - - public CIHttpLoadBalancerSupport(Google provider) { - super(provider); - this.provider = provider; - - ctx = provider.getContext(); - } - - @Override - public HttpLoadBalancerCapabilities getCapabilities() { - return new GCEHttpLoadBalancerCapabilities(provider); - } - - @Override - public String getProviderTermForConvergedHttpLoadBalancer(Locale locale) { - return "HTTP load balancer"; - } - - @Override - public boolean isSubscribed() throws CloudException, InternalException { - return true; // TODO punt! - } - - @Override - public Iterable listConvergedHttpLoadBalancers() throws CloudException, InternalException { - List httpLoadBalancers = new ArrayList(); - - Compute gce = provider.getGoogleCompute(); - - try { - UrlMapList urlMaps = gce.urlMaps().list(ctx.getAccountNumber()).execute(); - if ((null != urlMaps) && (null != urlMaps.getItems())) { - for (UrlMap urlMap: urlMaps.getItems()) { - httpLoadBalancers.add(urlMap.getName()); - } - } - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred listing convergedHttpLoadBalancers " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - return httpLoadBalancers; - } - - @Override - public @Nullable ConvergedHttpLoadBalancer getConvergedHttpLoadBalancer(@Nonnull String convergedHttpLoadBalancerName) throws CloudException, InternalException { - return toConvergedHttpLoadBalancer(convergedHttpLoadBalancerName); - } - - private String flatten(List items) { - String flattened = ""; - for (String item : items) { - flattened += item + ", "; - } - return flattened.replaceFirst(", $", ""); - } - - public ConvergedHttpLoadBalancer toConvergedHttpLoadBalancer(@Nonnull String urlMap) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - ConvergedHttpLoadBalancer convergedHttpLoadBalancer; - urlMap = urlMap.replaceAll(".*/", ""); - try { - UrlMap um = gce.urlMaps().get(ctx.getAccountNumber(), urlMap).execute(); - convergedHttpLoadBalancer = ConvergedHttpLoadBalancer.getInstance(um.getName(), um.getDescription(), um.getSelfLink(), um.getCreationTimestamp(), um.getDefaultService().replaceAll(".*/", "")); - - List hostRules = um.getHostRules(); - Map descriptionMap = new HashMap(); - Map hostMatchPatternMap = new HashMap(); - for (HostRule hostRule: hostRules) { - descriptionMap.put(hostRule.getPathMatcher(), hostRule.getDescription()); - hostMatchPatternMap.put(hostRule.getPathMatcher(), flatten(hostRule.getHosts())); - } - - List pathMatchers = um.getPathMatchers(); - for (PathMatcher pathMatcher: pathMatchers) { - Map pathMap = new HashMap(); - String defaultService = pathMatcher.getDefaultService().replaceAll(".*/", ""); - pathMap.put("/*", defaultService); - if (null != pathMatcher.getPathRules()) { - for (PathRule pathRule: pathMatcher.getPathRules()) { - pathMap.put(flatten(pathRule.getPaths()), pathRule.getService().replaceAll(".*/", "")); - } - } - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withUrlSet(pathMatcher.getName(), descriptionMap.get(pathMatcher.getName()), hostMatchPatternMap.get(pathMatcher.getName()), pathMap); - } - - // um.getTests() List object unknown - - TargetHttpProxyList targetHttpProxyList = gce.targetHttpProxies().list(ctx.getAccountNumber()).execute(); - for (TargetHttpProxy targetProxy: targetHttpProxyList.getItems()) { - if (targetProxy.getUrlMap().endsWith(urlMap)) { - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withTargetHttpProxy(targetProxy.getName(), targetProxy.getDescription(), targetProxy.getCreationTimestamp(), targetProxy.getSelfLink()); - ForwardingRuleList forwardingRuleList = gce.globalForwardingRules().list(ctx.getAccountNumber()).execute(); - for (ForwardingRule forwardingRule: forwardingRuleList.getItems()) { - if (forwardingRule.getTarget().endsWith(targetProxy.getName())) { - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withForwardingRule(forwardingRule.getName(), forwardingRule.getDescription(), forwardingRule.getCreationTimestamp(), forwardingRule.getIPAddress(), forwardingRule.getIPProtocol(), forwardingRule.getPortRange(), forwardingRule.getSelfLink(), forwardingRule.getTarget().replaceAll(".*/", "")); - } - } - } - } - - List backendServices = new ArrayList(); - backendServices.add(um.getDefaultService().replaceAll(".*/", "")); - - List allHealthChecks = new ArrayList(); - for (String backendService : new HashSet(backendServices)) { // use HashSet to make it unique list - BackendService bes = gce.backendServices().get(ctx.getAccountNumber(), backendService).execute(); - - List healthChecks = bes.getHealthChecks(); - List instanceGroups = new ArrayList(); - for (Backend backend : bes.getBackends()) { - instanceGroups.add(backend.getGroup().replaceAll(".*/", "")); - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withBackendServiceBackend(bes.getName(), backend.getDescription(), backend.getBalancingMode(), backend.getCapacityScaler(), backend.getGroup(), backend.getMaxRate(), backend.getMaxRatePerInstance(), backend.getMaxUtilization()); - } - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withBackendService(bes.getName(), bes.getDescription(), bes.getCreationTimestamp(), bes.getPort(), bes.getPortName(), bes.getProtocol(), healthChecks.toArray(new String[healthChecks.size()]), instanceGroups.toArray(new String[instanceGroups.size()]), bes.getSelfLink(), bes.getTimeoutSec()); - - for (String healthCheck : bes.getHealthChecks()) { - allHealthChecks.add(healthCheck.replaceAll(".*/", "")); - } - } - - for (String healthCheck : new HashSet(allHealthChecks)) { // use HashSet to make it unique list - HttpHealthCheck hc = gce.httpHealthChecks().get(ctx.getAccountNumber(), healthCheck).execute(); - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withHealthCheck(hc.getName(), hc.getDescription(), hc.getCreationTimestamp(), hc.getHost(), hc.getPort(), hc.getRequestPath(), hc.getCheckIntervalSec(), hc.getTimeoutSec(), hc.getHealthyThreshold(), hc.getUnhealthyThreshold(), hc.getSelfLink()); - } - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else - throw new GeneralCloudException("An error occurred listing convergedHttpLoadBalancers " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } catch (Exception ex) { - throw new GeneralCloudException("Error listing Converged Http Load Balancers " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - return convergedHttpLoadBalancer; - } - - /* - * takes either a globalForwardingRule name or url - */ - public void removeGlobalForwardingRule(@Nonnull String globalForwardingRule) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - Operation job = gce.globalForwardingRules().delete(ctx.getAccountNumber(), globalForwardingRule.replaceAll(".*/", "")).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (!ex.getMessage().contains("is already being used by")) { - return; - } // its ok not to remove resources in use elsewhere. - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing global forwarding rule " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - } - - /* - * takes either a targetHttpProxy name or url - */ - public void removeTargetHttpProxy(@Nonnull String targetHttpProxy) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - Operation job = gce.targetHttpProxies().delete(ctx.getAccountNumber(), targetHttpProxy.replaceAll(".*/", "")).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (!ex.getMessage().contains("is already being used by")) { - return; - } - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing target http proxy " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - } - - /* - * takes either a urlMap name or url - */ - public void removeUrlMap(@Nonnull String urlMap) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - Operation job = gce.urlMaps().delete(ctx.getAccountNumber(), urlMap.replaceAll(".*/", "")).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing url map " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error removing url map " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - /* - * takes either a backendService name or url - */ - public void removeBackendService(@Nonnull String backendService) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - Operation job = gce.backendServices().delete(ctx.getAccountNumber(), backendService.replaceAll(".*/", "")).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (!ex.getMessage().contains("is already being used by")) { - return; - } // its ok not to remove resources in use elsewhere. - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing backend service " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - } - - /* - * takes either a httpHealthCheck name or url - */ - public void removeHttpHealthCheck(@Nonnull String httpHealthCheck) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - Operation job = gce.httpHealthChecks().delete(ctx.getAccountNumber(), httpHealthCheck.replaceAll(".*/", "")).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (!ex.getMessage().contains("is already being used by")) { - return; - } // its ok not to remove resources in use elsewhere. - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing http health check " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - } - - @Override - public void removeConvergedHttpLoadBalancers(@Nonnull String urlMap) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - urlMap = urlMap.replaceAll(".*/", ""); - try { - ForwardingRuleList forwardingRuleList = gce.globalForwardingRules().list(ctx.getAccountNumber()).execute(); - TargetHttpProxyList targetHttpProxyList = gce.targetHttpProxies().list(ctx.getAccountNumber()).execute(); - - for (TargetHttpProxy targetProxy: targetHttpProxyList.getItems()) { - if (targetProxy.getUrlMap().endsWith(urlMap)) { - for (ForwardingRule forwardingRule: forwardingRuleList.getItems()) { - if (forwardingRule.getTarget().endsWith(targetProxy.getName())) { - removeGlobalForwardingRule(forwardingRule.getName()); - } - } - removeTargetHttpProxy(targetProxy.getName()); - } - } - - UrlMap um = gce.urlMaps().get(ctx.getAccountNumber(), urlMap).execute(); - - List backendServices = new ArrayList(); - backendServices.add(um.getDefaultService().replaceAll(".*/", "")); - List pathMatchers = um.getPathMatchers(); - for (PathMatcher pathMatcher: pathMatchers) { - backendServices.add(pathMatcher.getDefaultService().replaceAll(".*/", "")); - if (null != pathMatcher.getPathRules()) { - for (PathRule pathRule: pathMatcher.getPathRules()) { - backendServices.add(pathRule.getService().replaceAll(".*/", "")); - } - } - } - - removeUrlMap(um.getName()); - - List healthChecks = new ArrayList(); - for (String backendService : new HashSet(backendServices)) { // use HashSet to make it unique list - BackendService bes = gce.backendServices().get(ctx.getAccountNumber(), backendService).execute(); - for (String healthCheck : bes.getHealthChecks()) { - healthChecks.add(healthCheck); - } - removeBackendService(backendService); - } - - for (String healthCheck : new HashSet(healthChecks)) { // use HashSet to make it unique list - removeHttpHealthCheck(healthCheck); - } - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing convergedHttpLoadBalancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error removing Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - public void createBackendService(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - GoogleMethod method = new GoogleMethod(provider); - - List backendServices = withConvergedHttpLoadBalancerOptions.getBackendServices(); - for (ConvergedHttpLoadBalancer.BackendService backendService : backendServices) { - if (null == backendService.getSelfLink()) { - BackendService beContent = new BackendService(); - beContent.setName(getCapabilities().getConvergedHttpLoadBalancerNamingConstraints().convertToValidName(backendService.getName(), Locale.US)); - beContent.setDescription(backendService.getDescription()); - beContent.setPort(backendService.getPort()); - beContent.setPortName(backendService.getPortName()); - beContent.setTimeoutSec(backendService.getTimeoutSec()); - - List healthCheckSelfUrls = new ArrayList(); - for (String healthCheckName : backendService.getHealthChecks()) { - healthCheckSelfUrls.add(withConvergedHttpLoadBalancerOptions.getHealthCheckSelfUrl(healthCheckName)); - } - beContent.setHealthChecks(healthCheckSelfUrls); - - List backends = new ArrayList(); - - for (String backendServiceInstranceGroupSelfUrl : backendService.getBackendServiceBackends()) { - Backend backend = new Backend(); - backend.setGroup(backendServiceInstranceGroupSelfUrl); - backends.add(backend); - } - - beContent.setBackends(backends); - - try { - Operation foo = gce.backendServices().insert(ctx.getAccountNumber(), beContent ).execute(); - method.getOperationComplete(provider.getContext(), foo, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred creating backend service " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch ( Exception ex ) { - throw new GeneralCloudException("Error creating backend service " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - backendService.setServiceUrl(gce.getBaseUrl() + ctx.getAccountNumber() + "/global/backendServices/" + backendService.getName()); - } - } - } - - public void createURLMap(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - GoogleMethod method = new GoogleMethod(provider); - - String origName = withConvergedHttpLoadBalancerOptions.getName(); - String validName = getCapabilities().getConvergedHttpLoadBalancerNamingConstraints().convertToValidName(origName, Locale.US); - - try { - List urlSets = withConvergedHttpLoadBalancerOptions.getUrlSets(); - - UrlMap urlMap = new UrlMap(); - - List pathMatchers = new ArrayList(); - List hostRules = new ArrayList(); - - for (ConvergedHttpLoadBalancer.UrlSet urlSet : urlSets) { - HostRule hostRule = new HostRule(); - List hosts = new ArrayList(); - String hostMatchPatterns = urlSet.getHostMatchPatterns(); - if (hostMatchPatterns.contains(",")) { - for (String hostMatchPattern : hostMatchPatterns.split(", ?")) { - hosts.add(hostMatchPattern); - } - } else { - hosts.add(hostMatchPatterns); - } - hostRule.setHosts(hosts); - hostRule.setPathMatcher(urlSet.getName()); - hostRules.add(hostRule); - - PathMatcher pathMatcher = new PathMatcher(); - pathMatcher.setName(urlSet.getName()); - //pathMatcher.setDescription(urlSet.getDescription()); // GCE does not support - - List pathRules = new ArrayList(); - - Map pathMap = urlSet.getPathMap(); - for (String key : pathMap.keySet()) { - PathRule pathRule = new PathRule(); - List paths = new ArrayList(); - if (key.equals("/*")) { - pathMatcher.setDefaultService(withConvergedHttpLoadBalancerOptions.getBackendServiceSelfUrl(pathMap.get(key))); - } else { - if (key.contains(",")) { - for (String path : key.split(", *")) { - paths.add(path); - } - } else { - paths.add(key); - } - pathRule.setPaths(paths); - pathRule.setService(withConvergedHttpLoadBalancerOptions.getBackendServiceSelfUrl(pathMap.get(key))); - pathRules.add(pathRule); - } - } - pathMatcher.setPathRules(pathRules); - pathMatchers.add(pathMatcher); - } - - urlMap.setHostRules(hostRules); - urlMap.setName(validName); - urlMap.setPathMatchers(pathMatchers); - urlMap.setDescription(withConvergedHttpLoadBalancerOptions.getDescription()); // GCE does not support - urlMap.setDefaultService(withConvergedHttpLoadBalancerOptions.getBackendServiceSelfUrl(withConvergedHttpLoadBalancerOptions.getDefaultBackendService())); - Operation job = gce.urlMaps().insert(ctx.getAccountNumber(), urlMap ).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred creating url map " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error creating url map " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - - withConvergedHttpLoadBalancerOptions.setUrlMapSelfUrl(gce.getBaseUrl() + ctx.getAccountNumber() + "/global/urlMaps/" + validName); - } - - public void createTargetProxy(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - GoogleMethod method = new GoogleMethod(provider); - TargetHttpProxy content = new TargetHttpProxy(); - - List targetHttpProxies = withConvergedHttpLoadBalancerOptions.getTargetHttpProxies(); - try { - for (ConvergedHttpLoadBalancer.TargetHttpProxy targetHttpProxy : targetHttpProxies) { - content.setName(getCapabilities().getConvergedHttpLoadBalancerNamingConstraints().convertToValidName(targetHttpProxy.getName(), Locale.US)); - content.setDescription(targetHttpProxy.getDescription()); - content.setUrlMap(withConvergedHttpLoadBalancerOptions.getSelfLink()); - Operation job = gce.targetHttpProxies().insert(ctx.getAccountNumber(), content ).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - targetHttpProxy.setTargetProxySelfUrl(gce.getBaseUrl() + ctx.getAccountNumber() + "/global/targetHttpProxies/" + targetHttpProxy.getName()); - } - } catch (IOException ex) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred creating target proxy " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error creating target proxy " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - public void createGlobalForwardingRule(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - GoogleMethod method = new GoogleMethod(provider); - ForwardingRule gfwContent = new ForwardingRule(); - - List forwardingRules = withConvergedHttpLoadBalancerOptions.getForwardingRules(); - try { - for (ConvergedHttpLoadBalancer.ForwardingRule forwardingRule : forwardingRules) { - gfwContent.setName(getCapabilities().getConvergedHttpLoadBalancerNamingConstraints().convertToValidName(forwardingRule.getName(), Locale.US)); - gfwContent.setDescription(forwardingRule.getDescription()); - if (null != forwardingRule.getIpAddress()) { - gfwContent.setIPAddress(forwardingRule.getIpAddress()); - } - gfwContent.setIPProtocol(forwardingRule.getIpProtocol()); - gfwContent.setPortRange(forwardingRule.getPortRange()); - gfwContent.setTarget(withConvergedHttpLoadBalancerOptions.getTargetProxySelfUrl(forwardingRule.getTarget())); - Operation job = gce.globalForwardingRules().insert(ctx.getAccountNumber(), gfwContent ).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - forwardingRule.setGlobalForwardingRuleSelfUrl(gce.getBaseUrl() + ctx.getAccountNumber() + "/global/httpHealthChecks/" + forwardingRule.getName()); - } - } catch (IOException ex) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred creating GlobalForwardingRule: " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error occurred creating GlobalForwardingRule: " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - @Override - public String createConvergedHttpLoadBalancer(@Nonnull ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - try { - createHttpHealthChecks(withConvergedHttpLoadBalancerOptions); - } catch (Exception ex) { - throw new GeneralCloudException("Error creating Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - try { - createBackendService(withConvergedHttpLoadBalancerOptions); - } catch (Exception ex) { - throw new GeneralCloudException("Error creating Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - try { - createURLMap(withConvergedHttpLoadBalancerOptions); - } catch (Exception ex) { - throw new GeneralCloudException("Error creating Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - try { - createTargetProxy(withConvergedHttpLoadBalancerOptions); - } catch (Exception ex) { - throw new GeneralCloudException("Error creating Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - try { - createGlobalForwardingRule(withConvergedHttpLoadBalancerOptions); - } catch (Exception ex) { - throw new GeneralCloudException("Error creating Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - - return withConvergedHttpLoadBalancerOptions.getSelfLink(); - } - - private void createHttpHealthChecks(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - List healthChecks = withConvergedHttpLoadBalancerOptions.getHealthChecks(); - for (ConvergedHttpLoadBalancer.HealthCheck healthCheck : healthChecks) { - if (null == healthCheck.getSelfLink()) { - HttpHealthCheck httpHealthCheck = new HttpHealthCheck(); - httpHealthCheck.setName(getCapabilities().getConvergedHttpLoadBalancerNamingConstraints().convertToValidName(healthCheck.getName(), Locale.US)); - httpHealthCheck.setDescription(healthCheck.getDescription()); - httpHealthCheck.setCheckIntervalSec(healthCheck.getCheckIntervalSec()); - httpHealthCheck.setHealthyThreshold(healthCheck.getHealthyThreshold()); - httpHealthCheck.setUnhealthyThreshold(healthCheck.getUnHealthyThreshold()); - httpHealthCheck.setTimeoutSec(healthCheck.getTimeoutSec()); - httpHealthCheck.setHost(healthCheck.getHost()); // optional i think - httpHealthCheck.setPort(healthCheck.getPort()); - httpHealthCheck.setRequestPath(healthCheck.getRequestPath()); - Operation job = gce.httpHealthChecks().insert(ctx.getAccountNumber(), httpHealthCheck).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - healthCheck.setSelfLink(gce.getBaseUrl() + ctx.getAccountNumber() + "/global/httpHealthChecks/" + healthCheck.getName()); - } - } - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred creating http health checks " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error creating http health checks " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - @Override - public void updateTags(String convergedHttpLoadbalancerId, Tag... tags) throws CloudException, InternalException { - // TODO Auto-generated method stub - } - - @Override - public void updateTags(String[] convergedHttpLoadbalancerIds, Tag... tags) throws CloudException, InternalException { - // TODO Auto-generated method stub - } - - @Override - public void removeTags(String convergedHttpLoadbalancerId, Tag... tags) throws CloudException, InternalException { - // TODO Auto-generated method stub - } - - @Override - public void removeTags(String[] convergedHttpLoadbalancerIds, Tag... tags) throws CloudException, InternalException { - // TODO Auto-generated method stub - } - - @Override - public String[] mapServiceAction(ServiceAction action) { - // TODO Auto-generated method stub - return null; - } -} From fa05cd08b37cc21dc150dcff372ab7c518a848ae Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Tue, 26 Apr 2016 12:54:00 +0100 Subject: [PATCH 03/15] ci support tidy up --- .../cloud/ci/GCETopologyCapabilities.java | 9 +- .../org/dasein/cloud/ci/GoogleCIServices.java | 27 +- .../cloud/ci/GoogleTopologySupport.java | 195 +----- .../server => ci}/ReplicapoolSupport.java | 113 ++- .../dasein/cloud/ci/ReplicapoolTemplate.java | 174 ----- .../java/org/dasein/cloud/google/Google.java | 4 +- .../GCEHttpLoadBalancerCapabilities.java | 127 ---- .../GCEReplicapoolCapabilities.java | 73 +- .../network/CIHttpLoadBalancerSupport.java | 641 ------------------ 9 files changed, 75 insertions(+), 1288 deletions(-) rename src/main/java/org/dasein/cloud/{google/compute/server => ci}/ReplicapoolSupport.java (68%) delete mode 100644 src/main/java/org/dasein/cloud/ci/ReplicapoolTemplate.java delete mode 100644 src/main/java/org/dasein/cloud/google/capabilities/GCEHttpLoadBalancerCapabilities.java delete mode 100644 src/main/java/org/dasein/cloud/google/network/CIHttpLoadBalancerSupport.java diff --git a/src/main/java/org/dasein/cloud/ci/GCETopologyCapabilities.java b/src/main/java/org/dasein/cloud/ci/GCETopologyCapabilities.java index 7931a60..b9801fe 100644 --- a/src/main/java/org/dasein/cloud/ci/GCETopologyCapabilities.java +++ b/src/main/java/org/dasein/cloud/ci/GCETopologyCapabilities.java @@ -1,11 +1,13 @@ package org.dasein.cloud.ci; -import javax.annotation.Nonnull; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.google.Google; import org.dasein.cloud.util.NamingConstraints; +import javax.annotation.Nonnull; +import java.util.Locale; + public class GCETopologyCapabilities implements TopologyCapabilities { public GCETopologyCapabilities(Google provider) { @@ -22,4 +24,9 @@ public GCETopologyCapabilities(Google provider) { .constrainedBy('-'); } + @Override + public String getProviderTermForTopology(Locale locale) { + return "Instance Template"; + } + } diff --git a/src/main/java/org/dasein/cloud/ci/GoogleCIServices.java b/src/main/java/org/dasein/cloud/ci/GoogleCIServices.java index 1c3fa4f..1fc0fff 100644 --- a/src/main/java/org/dasein/cloud/ci/GoogleCIServices.java +++ b/src/main/java/org/dasein/cloud/ci/GoogleCIServices.java @@ -1,12 +1,10 @@ package org.dasein.cloud.ci; -import javax.annotation.Nullable; - import org.dasein.cloud.google.Google; -import org.dasein.cloud.google.compute.server.ReplicapoolSupport; -import org.dasein.cloud.google.network.CIHttpLoadBalancerSupport; -public class GoogleCIServices extends AbstractCIServices { +import javax.annotation.Nullable; + +public class GoogleCIServices extends AbstractConvergedInfrastructureServices { public GoogleCIServices(Google provider) { super(provider); @@ -17,28 +15,19 @@ public GoogleCIServices(Google provider) { return new ReplicapoolSupport(getProvider()); } - @Override - public @Nullable TopologySupport getTopologySupport() { - return new GoogleTopologySupport(getProvider()); - } - @Override public boolean hasConvergedInfrastructureSupport() { - return (getConvergedInfrastructureSupport() == null); + return (getConvergedInfrastructureSupport() != null); } - @Override - public boolean hasTopologySupport() { - return (getTopologySupport() == null); - } @Override - public ConvergedHttpLoadBalancerSupport getConvergedHttpLoadBalancerSupport() { - return new CIHttpLoadBalancerSupport(getProvider()); + public @Nullable TopologySupport getTopologySupport() { + return new GoogleTopologySupport(getProvider()); } @Override - public boolean hasConvergedHttpLoadBalancerSupport() { - return (getConvergedHttpLoadBalancerSupport() != null); + public boolean hasTopologySupport() { + return (getTopologySupport() != null); } } diff --git a/src/main/java/org/dasein/cloud/ci/GoogleTopologySupport.java b/src/main/java/org/dasein/cloud/ci/GoogleTopologySupport.java index e1cbc69..7e278b7 100644 --- a/src/main/java/org/dasein/cloud/ci/GoogleTopologySupport.java +++ b/src/main/java/org/dasein/cloud/ci/GoogleTopologySupport.java @@ -1,43 +1,18 @@ package org.dasein.cloud.ci; -import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.compute.Compute.InstanceTemplates; -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.InstanceProperties; import com.google.api.services.compute.model.InstanceTemplate; import com.google.api.services.compute.model.InstanceTemplateList; -import com.google.api.services.compute.model.Metadata; -import com.google.api.services.compute.model.Metadata.Items; -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; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; import org.dasein.cloud.CloudException; import org.dasein.cloud.GeneralCloudException; import org.dasein.cloud.InternalException; -import org.dasein.cloud.ci.Topology.VLANDevice; -import org.dasein.cloud.ci.Topology.VMDevice; -import org.dasein.cloud.ci.TopologyProvisionOptions.Disk; -import org.dasein.cloud.ci.TopologyProvisionOptions.Network; -import org.dasein.cloud.compute.Architecture; -import org.dasein.cloud.compute.MachineImage; -import org.dasein.cloud.compute.VirtualMachineProduct; import org.dasein.cloud.google.Google; -import org.dasein.cloud.google.GoogleException; -import org.dasein.cloud.google.GoogleMethod; -import org.dasein.cloud.google.GoogleOperationType; -import org.dasein.cloud.google.compute.server.ServerSupport; import javax.annotation.Nonnull; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.Locale; -import java.util.Map; public class GoogleTopologySupport extends AbstractTopologySupport { static private final Logger logger = Google.getLogger(GoogleTopologySupport.class); @@ -55,11 +30,6 @@ public GoogleTopologySupport(Google provider) { } } - @Override - public String getProviderTermForTopology(Locale locale) { - return "Instance Template"; - } - @Override public boolean isSubscribed() throws CloudException, InternalException { return true; @@ -72,34 +42,7 @@ public Iterable listTopologies(TopologyFilterOptions options) throws C InstanceTemplateList templateList = instanceTemplates.list(getContext().getAccountNumber()).execute(); if (templateList != null && templateList.getItems() != null) { for (InstanceTemplate template : templateList.getItems()) { - InstanceProperties templateProperties = template.getProperties(); - VMDevice vmDevices = null; - String machineType = templateProperties.getMachineType(); - ServerSupport server = new ServerSupport(getProvider()); - Iterable vmProducts = server.listProducts(Architecture.I64, "us-central1-f"); - for (VirtualMachineProduct vmProduct : vmProducts) { - if ( vmProduct.getName().equals(machineType) ) { - vmDevices = VMDevice.getInstance(machineType, machineType, vmProduct.getCpuCount(), vmProduct.getRamSize(), (String) null); - } - } - - List networkInterfaces = templateProperties.getNetworkInterfaces(); - String name = null; - String deviceId = null; - for (NetworkInterface networkInterface : networkInterfaces) { - deviceId = networkInterface.getNetwork(); - name = deviceId.replaceAll(".*/", ""); - } - - Topology topology = Topology.getInstance(getContext().getAccountNumber(), null, template.getName(), TopologyState.ACTIVE, template.getName(), template.getDescription()); - - if ( null != vmDevices ) { - topology = topology.withVirtualMachines(vmDevices); - } - - if ( (null != name) && (null != deviceId) ) { - topology = topology.withVLANs(VLANDevice.getInstance(deviceId, name)); - } + Topology topology = Topology.getInstance(getContext().getAccountNumber(), null, template.getName(), template.getName(), template.getDescription()); if ( (null == options) || (options.matches(topology)) ) { topologies.add(topology); @@ -107,146 +50,12 @@ public Iterable listTopologies(TopologyFilterOptions options) throws C } } } catch ( IOException e ) { - throw new GeneralCloudException("Problem listing topologies", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Problem listing topologies", e); } return topologies; } - @Override - public boolean createTopology(@Nonnull TopologyProvisionOptions withTopologyOptions) throws CloudException, InternalException { - InstanceTemplate newInstanceTemplate = new InstanceTemplate(); - - newInstanceTemplate.setName(getCapabilities().getTopologyNamingConstraints().convertToValidName(withTopologyOptions.getProductName(), Locale.US)); - newInstanceTemplate.setDescription(withTopologyOptions.getProductDescription()); - InstanceProperties instanceProperties = new InstanceProperties(); - instanceProperties.setCanIpForward(withTopologyOptions.getCanIpForward()); - instanceProperties.setDescription(withTopologyOptions.getProductDescription()); - - VirtualMachineProduct p = getProvider().getComputeServices().getVirtualMachineSupport().getProduct(withTopologyOptions.getMachineType()); - instanceProperties.setMachineType(p.getName()); - - List disks = withTopologyOptions.getDiskArray(); - List attachedDisks = new ArrayList(); - for (Disk topologyDisk : disks) { - AttachedDisk disk = new AttachedDisk(); - disk.setAutoDelete(topologyDisk.getAutoDelete()); - disk.setBoot(topologyDisk.getBootable()); - disk.setDeviceName(withTopologyOptions.getProductName()); - AttachedDiskInitializeParams attachedDiskInitializeParams = new AttachedDiskInitializeParams(); - MachineImage img = getProvider().getComputeServices().getImageSupport().getImage(topologyDisk.getDeviceSource()); - attachedDiskInitializeParams.setSourceImage(img.getTag("contentLink").toString()); - if (topologyDisk.getDeviceType() == TopologyProvisionOptions.DiskType.SSD_PERSISTENT_DISK) { - attachedDiskInitializeParams.setDiskType("pd-ssd"); - } else { - attachedDiskInitializeParams.setDiskType("pd-standard"); - } - - disk.setInitializeParams(attachedDiskInitializeParams); - attachedDisks.add(disk); - } - instanceProperties.setDisks(attachedDisks); //must provide at least one AttachedDisk definition. - - List topologyNetworksList = withTopologyOptions.getNetworkArray(); - List networks = new ArrayList(); - for (Network topologyNetwork : topologyNetworksList) { - NetworkInterface networkInterface = new NetworkInterface(); - networkInterface.setName(topologyNetwork.getNetworkName()); - - List topologyNetworksAccessConfig = topologyNetwork.getAccessConfig(); - List accessConfig = new ArrayList(); - - for (TopologyProvisionOptions.AccessConfig topologyAccessConfig : topologyNetworksAccessConfig) { - AccessConfig cfg = new AccessConfig(); - cfg.setName(topologyAccessConfig.getName()); - cfg.setKind("compute#accessConfig"); - cfg.setType(topologyAccessConfig.getType()); - accessConfig.add(cfg); - } - networkInterface.setAccessConfigs(accessConfig); - networks.add(networkInterface); - } - instanceProperties.setNetworkInterfaces(networks); - - Tags tags = new Tags(); - tags.setItems(withTopologyOptions.getTags()); - instanceProperties.setTags(tags); - - String[] sshKeys = withTopologyOptions.getSshKeys(); - Metadata metadata = new Metadata(); - List metadataItems = new ArrayList(); - for (String sshKey : sshKeys) { - Metadata.Items item = new Metadata.Items() ; - item.setKey("sshKeys"); - item.setValue(sshKey); - metadataItems.add(item); - } - - Map metaDataItems = withTopologyOptions.getMetadata(); - for (String itemKey : metaDataItems.keySet()) { - Metadata.Items item = new Metadata.Items() ; - item.setKey(itemKey); - item.setValue(metaDataItems.get(itemKey)); - metadataItems.add(item); - } - - metadata.setItems(metadataItems); - instanceProperties.setMetadata(metadata); - - Scheduling scheduling = new Scheduling(); - scheduling.setAutomaticRestart(withTopologyOptions.getAutomaticRestart()); - if (withTopologyOptions.getMaintenenceAction() == TopologyProvisionOptions.MaintenanceOption.MIGRATE_VM_INSTANCE) { - scheduling.setOnHostMaintenance("MIGRATE"); - } else { - scheduling.setOnHostMaintenance("TERMINATE"); - } - instanceProperties.setScheduling(scheduling); - -/* - List serviceAccounts = new ArrayList(); - ServiceAccount serviceAccount = new ServiceAccount(); - serviceAccount.setEmail("email"); - List scopes = new ArrayList(); - serviceAccount.setScopes(scopes); - serviceAccounts.add(serviceAccount); - instanceProperties.setServiceAccounts(serviceAccounts); - -*/ - newInstanceTemplate.setProperties(instanceProperties); - try { - Operation job = instanceTemplates.insert(getContext().getAccountNumber(), newInstanceTemplate).execute(); - GoogleMethod method = new GoogleMethod(getProvider()); - method.getOperationComplete(getContext(), job, GoogleOperationType.GLOBAL_OPERATION, "", ""); - } catch (IOException ex) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException(ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - return true; - } - - @Override - public boolean removeTopologies(@Nonnull String[] topologyIds) throws CloudException, InternalException { - for (String topologyName: topologyIds) { - try { - Operation job = instanceTemplates.delete(getContext().getAccountNumber(), topologyName).execute(); - GoogleMethod method = new GoogleMethod(getProvider()); - method.getOperationComplete(getContext(), job, GoogleOperationType.GLOBAL_OPERATION, "", ""); - } catch (IOException ex) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException(ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - } - return true; - } - private transient volatile GCETopologyCapabilities capabilities; @Override diff --git a/src/main/java/org/dasein/cloud/google/compute/server/ReplicapoolSupport.java b/src/main/java/org/dasein/cloud/ci/ReplicapoolSupport.java similarity index 68% rename from src/main/java/org/dasein/cloud/google/compute/server/ReplicapoolSupport.java rename to src/main/java/org/dasein/cloud/ci/ReplicapoolSupport.java index 57caf14..d4448f5 100644 --- a/src/main/java/org/dasein/cloud/google/compute/server/ReplicapoolSupport.java +++ b/src/main/java/org/dasein/cloud/ci/ReplicapoolSupport.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.dasein.cloud.google.compute.server; +package org.dasein.cloud.ci; import com.google.api.services.compute.Compute; import com.google.api.services.compute.model.Instance; @@ -28,16 +28,12 @@ import com.google.api.services.replicapool.model.InstanceGroupManagerList; import com.google.api.services.replicapool.model.Operation; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; import org.dasein.cloud.CloudException; import org.dasein.cloud.GeneralCloudException; import org.dasein.cloud.InternalException; +import org.dasein.cloud.OperationNotSupportedException; import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.ci.AbstractConvergedInfrastructureSupport; -import org.dasein.cloud.ci.CIFilterOptions; -import org.dasein.cloud.ci.CIProvisionOptions; -import org.dasein.cloud.ci.ConvergedInfrastructure; -import org.dasein.cloud.ci.ConvergedInfrastructureState; +import org.dasein.cloud.ResourceType; import org.dasein.cloud.dc.DataCenter; import org.dasein.cloud.dc.Region; import org.dasein.cloud.google.Google; @@ -47,6 +43,7 @@ import org.dasein.cloud.util.APITrace; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -87,7 +84,7 @@ public boolean isSubscribed() throws CloudException, InternalException { } @Override - public Iterable listConvergedInfrastructures(CIFilterOptions options) throws CloudException, InternalException { + public Iterable listConvergedInfrastructures(ConvergedInfrastructureFilterOptions options) throws CloudException, InternalException { APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.listConvergedInfrastructures"); List convergedInfrastrutures = new ArrayList(); try { @@ -102,10 +99,11 @@ public Iterable listConvergedInfrastructures(CIFilterOp result = rp.instanceGroupManagers().list(provider.getContext().getAccountNumber(), dataCenterId).execute(); //provider.getContext().getRegionId() if (null != result.getItems()) { for (InstanceGroupManager item : result.getItems()) { - ConvergedInfrastructure ci = ConvergedInfrastructure.getInstance(provider.getContext().getAccountNumber(), - regionName, dataCenterId, item.getName(), ConvergedInfrastructureState.RUNNING, item.getName(), item.getDescription(), item.getInstanceTemplate()); + ConvergedInfrastructure ci = ConvergedInfrastructure.getInstance(item.getName(), item.getName(), item.getDescription(), + ConvergedInfrastructureState.READY, System.currentTimeMillis(), dataCenterId, regionName, null); ci.setTag("selfLink", item.getSelfLink()); ci.setTag("instanceGroupLink", item.getGroup()); + loadResources(ci, dataCenterId); if (options != null) { if (options.matches(ci)) { convergedInfrastrutures.add(ci); @@ -119,7 +117,7 @@ public Iterable listConvergedInfrastructures(CIFilterOp } } } catch ( IOException e ) { - throw new GeneralCloudException("Error listing converged infrastructure", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Error listing converged infrastructure", e); } } finally{ APITrace.end(); @@ -127,68 +125,36 @@ public Iterable listConvergedInfrastructures(CIFilterOp return convergedInfrastrutures; } - @Override - public Iterable listVirtualMachines(String inCIId) throws InternalException, CloudException { - APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.listVirtualMachines"); - List vms = new ArrayList(); - try { - Replicapool rp = provider.getGoogleReplicapool(); - Compute gce = provider.getGoogleCompute(); - String datacenterId = null; - Iterable cis = listConvergedInfrastructures(null); - for (ConvergedInfrastructure ci : cis) { - if (ci.getName().equals(inCIId)) { - datacenterId = ci.getProviderDataCenterId(); - } - } - - InstanceGroupManager pool = rp.instanceGroupManagers().get(provider.getContext().getAccountNumber(), datacenterId, inCIId).execute(); - String baseInstanceName = pool.getBaseInstanceName(); - InstanceList result = gce.instances().list(provider.getContext().getAccountNumber(), datacenterId).execute(); - for (Instance instance : result.getItems()) { - if (instance.getName().startsWith(baseInstanceName + "-")) { - vms.add(instance.getName()); - } - } - return vms; - } catch ( IOException e ) { - throw new GeneralCloudException("Error listing virtual machines", e, CloudErrorType.GENERAL); - } finally{ - APITrace.end(); - } - } - - @Override - public Iterable listVLANs(String inCIId) throws CloudException, InternalException { - APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.listVLANs"); - List nets = new ArrayList(); + private void loadResources(ConvergedInfrastructure ci, String datacenterId) throws InternalException, CloudException { + APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.loadResources"); + List list = new ArrayList<>(); try { Replicapool rp = provider.getGoogleReplicapool(); Compute gce = provider.getGoogleCompute(); - String datacenterId = null; - Iterable cis = listConvergedInfrastructures(null); - for (ConvergedInfrastructure ci : cis) { - if (ci.getName().equals(inCIId)) { - datacenterId = ci.getProviderDataCenterId(); - } - } - - InstanceGroupManager pool = rp.instanceGroupManagers().get(provider.getContext().getAccountNumber(), datacenterId, inCIId).execute(); + InstanceGroupManager pool = rp.instanceGroupManagers().get(provider.getContext().getAccountNumber(), datacenterId, ci.getProviderCIId()).execute(); String baseInstanceName = pool.getBaseInstanceName(); InstanceList result = gce.instances().list(provider.getContext().getAccountNumber(), datacenterId).execute(); for (Instance instance : result.getItems()) { if (instance.getName().startsWith(baseInstanceName + "-")) { + ConvergedInfrastructureResource resource = ConvergedInfrastructureResource.getInstance(ResourceType.VIRTUAL_MACHINE, instance.getName()); + list.add(resource); if (null != instance.getNetworkInterfaces()) { for (NetworkInterface net : instance.getNetworkInterfaces()) { - nets.add(net.getNetwork().replaceAll(".*/", "")); + String vlan = net.getNetwork().replaceAll(".*/", ""); + resource = ConvergedInfrastructureResource.getInstance(ResourceType.VLAN, vlan); + list.add(resource); } } } } - return nets; + if (!list.isEmpty()){ + ConvergedInfrastructureResource[] resources = new ConvergedInfrastructureResource[list.size()]; + resources = list.toArray(resources); + ci.withResources(resources); + } } catch ( IOException e ) { - throw new GeneralCloudException("Error listing vlans", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Error listing virtual machines", e); } finally{ APITrace.end(); } @@ -199,24 +165,24 @@ public Iterable listVLANs(String inCIId) throws CloudException, Internal * @see org.dasein.cloud.ci.ConvergedInfrastructureSupport#provision(org.dasein.cloud.ci.CIProvisionOptions) */ @Override - public ConvergedInfrastructure provision(CIProvisionOptions options) throws CloudException, InternalException { + public ConvergedInfrastructure provision(ConvergedInfrastructureProvisionOptions options) throws CloudException, InternalException { APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.provision"); Replicapool rp = provider.getGoogleReplicapool(); try { ProviderContext ctx = provider.getContext(); InstanceGroupManager content = new InstanceGroupManager(); - content.setBaseInstanceName(getCapabilities().getConvergedInfrastructureNamingConstraints().convertToValidName(options.getBaseInstanceName(), Locale.US)); + content.setBaseInstanceName(getCapabilities().getConvergedInfrastructureNamingConstraints().convertToValidName(options.getBaseName(), Locale.US)); content.setDescription(options.getDescription()); - content.setInstanceTemplate("https://www.googleapis.com/compute/v1/projects/" + ctx.getAccountNumber() + "/global/instanceTemplates/" + options.getInstanceTemplate()); + content.setInstanceTemplate("https://www.googleapis.com/compute/v1/projects/" + ctx.getAccountNumber() + "/global/instanceTemplates/" + options.getTemplate()); content.setName(getCapabilities().getConvergedInfrastructureNamingConstraints().convertToValidName(options.getName(), Locale.US)); - String region = options.getZone().replaceFirst("-.$", ""); + String region = options.getProviderDatacenterId().replaceFirst("-.$", ""); //content.setTargetPools(targetPools); - Operation job = rp.instanceGroupManagers().insert(ctx.getAccountNumber(), options.getZone(), options.getSize(), content).execute(); + Operation job = rp.instanceGroupManagers().insert(ctx.getAccountNumber(), options.getProviderDatacenterId(), options.getInstanceCount(), content).execute(); GoogleMethod method = new GoogleMethod(provider); - method.getCIOperationComplete(ctx, job, GoogleOperationType.ZONE_OPERATION, region, options.getZone()); - return ConvergedInfrastructure.getInstance(ctx.getAccountNumber(), region, options.getZone(), options.getBaseInstanceName(), ConvergedInfrastructureState.RUNNING, options.getName(), options.getDescription(), options.getInstanceTemplate()); + method.getCIOperationComplete(ctx, job, GoogleOperationType.ZONE_OPERATION, region, options.getProviderDatacenterId()); + return ConvergedInfrastructure.getInstance(options.getName(), options.getName(), options.getDescription(), ConvergedInfrastructureState.READY, System.currentTimeMillis(), options.getProviderDatacenterId(), region, null); } catch ( IOException e ) { - throw new GeneralCloudException("Error provisioning", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Error provisioning", e); } finally{ APITrace.end(); } @@ -231,13 +197,13 @@ public void terminate(String ciId, String explanation) throws CloudException, In Replicapool rp = provider.getGoogleReplicapool(); for (ConvergedInfrastructure ci : listConvergedInfrastructures(null)) { if (ci.getName().equals(ciId)) { - Operation job = rp.instanceGroupManagers().delete(provider.getContext().getAccountNumber(), ci.getProviderDataCenterId(), ciId).execute(); + Operation job = rp.instanceGroupManagers().delete(provider.getContext().getAccountNumber(), ci.getProviderDatacenterId(), ciId).execute(); GoogleMethod method = new GoogleMethod(provider); - method.getCIOperationComplete(ctx, job, GoogleOperationType.ZONE_OPERATION, ctx.getRegionId(), ci.getProviderDataCenterId()); + method.getCIOperationComplete(ctx, job, GoogleOperationType.ZONE_OPERATION, ctx.getRegionId(), ci.getProviderDatacenterId()); } } } catch ( IOException e ) { - throw new GeneralCloudException("Error terminating", e, CloudErrorType.GENERAL); + throw new GeneralCloudException("Error terminating", e); } finally { APITrace.end(); @@ -245,7 +211,12 @@ public void terminate(String ciId, String explanation) throws CloudException, In } @Override - public boolean hasConvergedHttpLoadBalancerSupport() { - return true; + public void cancelDeployment(@Nonnull String ciId, @Nullable String explanation) throws CloudException, InternalException { + throw new OperationNotSupportedException("Cancelling deployment not supported in "+getProvider().getCloudName()); + } + + @Override + public ConvergedInfrastructure validateDeployment(@Nonnull ConvergedInfrastructureProvisionOptions options) throws CloudException, InternalException { + return null; } } diff --git a/src/main/java/org/dasein/cloud/ci/ReplicapoolTemplate.java b/src/main/java/org/dasein/cloud/ci/ReplicapoolTemplate.java deleted file mode 100644 index a240f23..0000000 --- a/src/main/java/org/dasein/cloud/ci/ReplicapoolTemplate.java +++ /dev/null @@ -1,174 +0,0 @@ -/** - * Copyright (C) 2012-2014 Dell, Inc - * See annotations for authorship information - * - * ==================================================================== - * 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 org.dasein.cloud.ci; - -import javax.annotation.Nonnull; - -import org.dasein.cloud.CloudProvider; -import org.dasein.cloud.Tag; -import org.dasein.cloud.compute.VirtualMachineProduct; - -import com.google.api.services.compute.model.Metadata; - -/** - * Implements the Replicapool Templates supported in the Google API. - * @author Roger Unwin - * @version 2015.03 initial version - * @since 2015.03 - */ - -public class ReplicapoolTemplate { - - private boolean automaticRestart = false; - private boolean maintenenceMigration = false; - private boolean ipForwarding = false; - private String[] readonlyDisks = new String[0]; - private Tag[] tags = new Tag[0]; - private String[] sshKeys = new String[0]; - private String poolName = null; - private Metadata metadata; - private boolean allowHttp = false; - private boolean allowHttps = false; - private VirtualMachineProduct vmProduct; - private String providerImageId; - private String bootDiskType; - private boolean deleteDiskOnTerminate; - private boolean assignEphemeralExternalIp; - - public ReplicapoolTemplate(@Nonnull String poolName, - @Nonnull Metadata metadata, - @Nonnull boolean allowHttp, - @Nonnull boolean allowHttps, - @Nonnull VirtualMachineProduct vmProduct, - @Nonnull String providerImageId, - @Nonnull String bootDiskType, // Standard persistent disk or SSD - @Nonnull boolean deleteDiskOnTerminate, - @Nonnull boolean assignEphemeralExternalIp) { - this.poolName = poolName; - this.metadata = metadata; - this.allowHttp = allowHttp; - this.allowHttps = allowHttps; - this.vmProduct = vmProduct; - this.providerImageId = providerImageId; - this.bootDiskType = bootDiskType; - this.deleteDiskOnTerminate = deleteDiskOnTerminate; - this.assignEphemeralExternalIp = assignEphemeralExternalIp; - } - - public ReplicapoolTemplate withSshKeys(@Nonnull String[] sshKeys) { - this.sshKeys = sshKeys; - return this; - } - - public String[] getSshKeys() { - return sshKeys; - } - - public ReplicapoolTemplate withTags(Tag... tags) { - this.tags = tags; - return this; - } - - public Tag[] getTags() { - return tags; - } - - public ReplicapoolTemplate withReadonlyDisks(String[] readonlyDisks) { - this.readonlyDisks = readonlyDisks; - return this; - } - - public String[] getReadonlyDisks() { - return readonlyDisks; - } - - public ReplicapoolTemplate withIpForwarding(boolean ipForwarding) { - this.ipForwarding = ipForwarding; - return this; - } - - public boolean hasIpForwarding() { - return ipForwarding; - } - - public ReplicapoolTemplate withAutomaticRestart(boolean automaticRestart) { - this.automaticRestart = automaticRestart; - return this; - } - - public boolean hasAutomaticRestart() { - return automaticRestart; - } - - public ReplicapoolTemplate withMaintenenceMigration(boolean maintenenceMigration) { - this.maintenenceMigration = maintenenceMigration; - return this; - } - - public boolean hasMaintenenceMigration() { - return maintenenceMigration; - } - - public String getPoolName() { - return poolName; - } - - public Metadata getMetadata() { - return metadata; - } - - public boolean getAllowHttp() { - return allowHttp; - } - - public boolean getAllowHttps() { - return allowHttps; - } - - public VirtualMachineProduct getVmProduct() { - return vmProduct; - } - - public String getProviderImageId() { - return providerImageId; - } - - public String getBootDiskType() { - return bootDiskType; - } - - public boolean getDeleteDiskOnTerminate() { - return deleteDiskOnTerminate; - } - - public boolean getAssignEphemeralExternalIp() { - return assignEphemeralExternalIp; - } - - public boolean create(CloudProvider provider) { - return false; - // TODO Auto-generated method stub - } - - public boolean remove(CloudProvider provider) { - return false; - // TODO Auto-generated method stub - } -} diff --git a/src/main/java/org/dasein/cloud/google/Google.java b/src/main/java/org/dasein/cloud/google/Google.java index efa9ab8..f0fb708 100755 --- a/src/main/java/org/dasein/cloud/google/Google.java +++ b/src/main/java/org/dasein/cloud/google/Google.java @@ -37,7 +37,7 @@ import org.dasein.cloud.ContextRequirements; import org.dasein.cloud.InternalException; import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.ci.CIServices; +import org.dasein.cloud.ci.ConvergedInfrastructureServices; import org.dasein.cloud.ci.GoogleCIServices; import org.dasein.cloud.google.compute.GoogleCompute; import org.dasein.cloud.google.network.GoogleNetwork; @@ -348,7 +348,7 @@ public SQLAdmin getGoogleSQLAdmin() throws CloudException, InternalException{ } @Override - public @Nullable CIServices getCIServices() { + public @Nullable ConvergedInfrastructureServices getConvergedInfrastructureServices() { return new GoogleCIServices(this); } diff --git a/src/main/java/org/dasein/cloud/google/capabilities/GCEHttpLoadBalancerCapabilities.java b/src/main/java/org/dasein/cloud/google/capabilities/GCEHttpLoadBalancerCapabilities.java deleted file mode 100644 index 5945a2a..0000000 --- a/src/main/java/org/dasein/cloud/google/capabilities/GCEHttpLoadBalancerCapabilities.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright (C) 2012-2014 Dell, Inc - * See annotations for authorship information - * - * ==================================================================== - * 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 org.dasein.cloud.google.capabilities; - -import org.dasein.cloud.AbstractCapabilities; -import org.dasein.cloud.ci.HttpLoadBalancerCapabilities; -import org.dasein.cloud.google.Google; -import org.dasein.cloud.util.NamingConstraints; - -import javax.annotation.Nonnull; -import java.util.Arrays; -import java.util.Collections; -import java.util.Locale; - -public class GCEHttpLoadBalancerCapabilities extends AbstractCapabilities implements HttpLoadBalancerCapabilities { - - public GCEHttpLoadBalancerCapabilities(Google provider) { - super(provider); - } - - @Override - public boolean supportsHttpTraffic() { - return true; - } - - @Override - public boolean supportsHttpsTraffic() { - return false; - } - - @Override - public boolean supportsHealthChecks() { - return true; - } - - @Override - public boolean supportsMoreThanOneHealthCheck() { - return false; - } - - @Override - public boolean supportsBackendServices() { - return true; - } - - @Override - public boolean supportsMoreThanOneBackendService() { - return true; - } - - @Override - public boolean supportsUrlSets() { - return true; - } - - @Override - public boolean supportsMoreThanOneUrlSet() { - return true; - } - - @Override - public boolean supportsTargetHttpProxies() { - return true; - } - - @Override - public boolean supportsMoreThanOneTargetHttpProxy() { - return true; - } - - @Override - public boolean supportsForwardingRules() { - return true; - } - - @Override - public boolean supportsMoreThanOneForwardingRule() { - return true; - } - - @Override - public String getProviderTermForHttpLoadBalancer(Locale locale) { - return "HTTP Load Balancer"; - } - - @Override - public Iterable listSupportedHttpPorts() { - return Collections.unmodifiableList(Arrays.asList("80", "8080")); - } - - @Override - public boolean supportsUsingExistingHealthCheck() { - return true; - } - - @Override - public boolean supportsUsingExistingBackendService() { - return true; - } - - @Override - public @Nonnull NamingConstraints getConvergedHttpLoadBalancerNamingConstraints() { - return NamingConstraints.getAlphaNumeric(1, 63) - .withRegularExpression("^[a-z][-a-z0-9]{0,61}[a-z0-9]$") - .lowerCaseOnly() - .withNoSpaces() - .withLastCharacterSymbolAllowed(false) - .constrainedBy('-'); - } -} diff --git a/src/main/java/org/dasein/cloud/google/capabilities/GCEReplicapoolCapabilities.java b/src/main/java/org/dasein/cloud/google/capabilities/GCEReplicapoolCapabilities.java index 8af9412..be9d172 100644 --- a/src/main/java/org/dasein/cloud/google/capabilities/GCEReplicapoolCapabilities.java +++ b/src/main/java/org/dasein/cloud/google/capabilities/GCEReplicapoolCapabilities.java @@ -20,6 +20,7 @@ package org.dasein.cloud.google.capabilities; import org.dasein.cloud.AbstractCapabilities; +import org.dasein.cloud.Requirement; import org.dasein.cloud.ci.ConvergedInfrastructureCapabilities; import org.dasein.cloud.google.Google; import org.dasein.cloud.util.NamingConstraints; @@ -37,66 +38,6 @@ public GCEReplicapoolCapabilities(Google provider) { // TODO Auto-generated constructor stub } - public boolean supportsHttpTraffic() { - return true; - } - - public boolean supportsHttpsTraffic() { - return true; - } - - public boolean supportsMetadata() { - return true; - } - - public boolean supportsSshKeys() { - return true; - } - - public boolean supportsTags() { - return true; - } - - public boolean supportsSsdDisk() { - return true; - } - - public boolean supportsStandardDisk() { - return true; - } - - public boolean supportsDeleteDiskOnTerminate() { - return true; - } - - public boolean supportsReadOnlySharedDisks() { - return true; - } - - public boolean supportsVmAutomaticRestart() { - return true; - } - - public boolean supportsMigrateVmOnMaintenance() { - return true; - } - - public boolean supportsTemplates() { - return true; - } - - public boolean supportsRegions() { // Zone - return true; - } - - public boolean supportsCreateFromInstance() { - return true; - } - - public boolean supportsAutoScaling() { - return true; - } - @Override public @Nonnull NamingConstraints getConvergedInfrastructureNamingConstraints() { return NamingConstraints.getAlphaNumeric(1, 63) @@ -106,4 +47,16 @@ public boolean supportsAutoScaling() { .withLastCharacterSymbolAllowed(false) .constrainedBy('-'); } + + @Nonnull + @Override + public Requirement identifyResourcePoolLaunchRequirement() { + return Requirement.NONE; + } + + @Nonnull + @Override + public Requirement identifyTemplateContentLaunchRequirement() { + return Requirement.NONE; + } } diff --git a/src/main/java/org/dasein/cloud/google/network/CIHttpLoadBalancerSupport.java b/src/main/java/org/dasein/cloud/google/network/CIHttpLoadBalancerSupport.java deleted file mode 100644 index cb50b23..0000000 --- a/src/main/java/org/dasein/cloud/google/network/CIHttpLoadBalancerSupport.java +++ /dev/null @@ -1,641 +0,0 @@ -package org.dasein.cloud.google.network; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.services.compute.Compute; -import com.google.api.services.compute.model.Backend; -import com.google.api.services.compute.model.BackendService; -import com.google.api.services.compute.model.ForwardingRule; -import com.google.api.services.compute.model.ForwardingRuleList; -import com.google.api.services.compute.model.HostRule; -import com.google.api.services.compute.model.HttpHealthCheck; -import com.google.api.services.compute.model.Operation; -import com.google.api.services.compute.model.PathMatcher; -import com.google.api.services.compute.model.PathRule; -import com.google.api.services.compute.model.TargetHttpProxy; -import com.google.api.services.compute.model.TargetHttpProxyList; -import com.google.api.services.compute.model.UrlMap; -import com.google.api.services.compute.model.UrlMapList; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.GeneralCloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.Tag; -import org.dasein.cloud.ci.AbstractConvergedHttpLoadBalancer; -import org.dasein.cloud.ci.ConvergedHttpLoadBalancer; -import org.dasein.cloud.ci.HttpLoadBalancerCapabilities; -import org.dasein.cloud.google.Google; -import org.dasein.cloud.google.GoogleException; -import org.dasein.cloud.google.GoogleMethod; -import org.dasein.cloud.google.GoogleOperationType; -import org.dasein.cloud.google.capabilities.GCEHttpLoadBalancerCapabilities; -import org.dasein.cloud.identity.ServiceAction; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -public class CIHttpLoadBalancerSupport extends AbstractConvergedHttpLoadBalancer { - - private Google provider; - private ProviderContext ctx; - - public CIHttpLoadBalancerSupport(Google provider) { - super(provider); - this.provider = provider; - - ctx = provider.getContext(); - } - - @Override - public HttpLoadBalancerCapabilities getCapabilities() { - return new GCEHttpLoadBalancerCapabilities(provider); - } - - @Override - public String getProviderTermForConvergedHttpLoadBalancer(Locale locale) { - return "HTTP load balancer"; - } - - @Override - public boolean isSubscribed() throws CloudException, InternalException { - return true; // TODO punt! - } - - @Override - public Iterable listConvergedHttpLoadBalancers() throws CloudException, InternalException { - List httpLoadBalancers = new ArrayList(); - - Compute gce = provider.getGoogleCompute(); - - try { - UrlMapList urlMaps = gce.urlMaps().list(ctx.getAccountNumber()).execute(); - if ((null != urlMaps) && (null != urlMaps.getItems())) { - for (UrlMap urlMap: urlMaps.getItems()) { - httpLoadBalancers.add(urlMap.getName()); - } - } - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred listing convergedHttpLoadBalancers " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - return httpLoadBalancers; - } - - @Override - public @Nullable ConvergedHttpLoadBalancer getConvergedHttpLoadBalancer(@Nonnull String convergedHttpLoadBalancerName) throws CloudException, InternalException { - return toConvergedHttpLoadBalancer(convergedHttpLoadBalancerName); - } - - private String flatten(List items) { - String flattened = ""; - for (String item : items) { - flattened += item + ", "; - } - return flattened.replaceFirst(", $", ""); - } - - public ConvergedHttpLoadBalancer toConvergedHttpLoadBalancer(@Nonnull String urlMap) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - ConvergedHttpLoadBalancer convergedHttpLoadBalancer; - urlMap = urlMap.replaceAll(".*/", ""); - try { - UrlMap um = gce.urlMaps().get(ctx.getAccountNumber(), urlMap).execute(); - convergedHttpLoadBalancer = ConvergedHttpLoadBalancer.getInstance(um.getName(), um.getDescription(), um.getSelfLink(), um.getCreationTimestamp(), um.getDefaultService().replaceAll(".*/", "")); - - List hostRules = um.getHostRules(); - Map descriptionMap = new HashMap(); - Map hostMatchPatternMap = new HashMap(); - for (HostRule hostRule: hostRules) { - descriptionMap.put(hostRule.getPathMatcher(), hostRule.getDescription()); - hostMatchPatternMap.put(hostRule.getPathMatcher(), flatten(hostRule.getHosts())); - } - - List pathMatchers = um.getPathMatchers(); - for (PathMatcher pathMatcher: pathMatchers) { - Map pathMap = new HashMap(); - String defaultService = pathMatcher.getDefaultService().replaceAll(".*/", ""); - pathMap.put("/*", defaultService); - if (null != pathMatcher.getPathRules()) { - for (PathRule pathRule: pathMatcher.getPathRules()) { - pathMap.put(flatten(pathRule.getPaths()), pathRule.getService().replaceAll(".*/", "")); - } - } - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withUrlSet(pathMatcher.getName(), descriptionMap.get(pathMatcher.getName()), hostMatchPatternMap.get(pathMatcher.getName()), pathMap); - } - - // um.getTests() List object unknown - - TargetHttpProxyList targetHttpProxyList = gce.targetHttpProxies().list(ctx.getAccountNumber()).execute(); - for (TargetHttpProxy targetProxy: targetHttpProxyList.getItems()) { - if (targetProxy.getUrlMap().endsWith(urlMap)) { - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withTargetHttpProxy(targetProxy.getName(), targetProxy.getDescription(), targetProxy.getCreationTimestamp(), targetProxy.getSelfLink()); - ForwardingRuleList forwardingRuleList = gce.globalForwardingRules().list(ctx.getAccountNumber()).execute(); - for (ForwardingRule forwardingRule: forwardingRuleList.getItems()) { - if (forwardingRule.getTarget().endsWith(targetProxy.getName())) { - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withForwardingRule(forwardingRule.getName(), forwardingRule.getDescription(), forwardingRule.getCreationTimestamp(), forwardingRule.getIPAddress(), forwardingRule.getIPProtocol(), forwardingRule.getPortRange(), forwardingRule.getSelfLink(), forwardingRule.getTarget().replaceAll(".*/", "")); - } - } - } - } - - List backendServices = new ArrayList(); - backendServices.add(um.getDefaultService().replaceAll(".*/", "")); - - List allHealthChecks = new ArrayList(); - for (String backendService : new HashSet(backendServices)) { // use HashSet to make it unique list - BackendService bes = gce.backendServices().get(ctx.getAccountNumber(), backendService).execute(); - - List healthChecks = bes.getHealthChecks(); - List instanceGroups = new ArrayList(); - for (Backend backend : bes.getBackends()) { - instanceGroups.add(backend.getGroup().replaceAll(".*/", "")); - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withBackendServiceBackend(bes.getName(), backend.getDescription(), backend.getBalancingMode(), backend.getCapacityScaler(), backend.getGroup(), backend.getMaxRate(), backend.getMaxRatePerInstance(), backend.getMaxUtilization()); - } - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withBackendService(bes.getName(), bes.getDescription(), bes.getCreationTimestamp(), bes.getPort(), bes.getPortName(), bes.getProtocol(), healthChecks.toArray(new String[healthChecks.size()]), instanceGroups.toArray(new String[instanceGroups.size()]), bes.getSelfLink(), bes.getTimeoutSec()); - - for (String healthCheck : bes.getHealthChecks()) { - allHealthChecks.add(healthCheck.replaceAll(".*/", "")); - } - } - - for (String healthCheck : new HashSet(allHealthChecks)) { // use HashSet to make it unique list - HttpHealthCheck hc = gce.httpHealthChecks().get(ctx.getAccountNumber(), healthCheck).execute(); - convergedHttpLoadBalancer = convergedHttpLoadBalancer.withHealthCheck(hc.getName(), hc.getDescription(), hc.getCreationTimestamp(), hc.getHost(), hc.getPort(), hc.getRequestPath(), hc.getCheckIntervalSec(), hc.getTimeoutSec(), hc.getHealthyThreshold(), hc.getUnhealthyThreshold(), hc.getSelfLink()); - } - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else - throw new GeneralCloudException("An error occurred listing convergedHttpLoadBalancers " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } catch (Exception ex) { - throw new GeneralCloudException("Error listing Converged Http Load Balancers " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - return convergedHttpLoadBalancer; - } - - /* - * takes either a globalForwardingRule name or url - */ - public void removeGlobalForwardingRule(@Nonnull String globalForwardingRule) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - Operation job = gce.globalForwardingRules().delete(ctx.getAccountNumber(), globalForwardingRule.replaceAll(".*/", "")).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (!ex.getMessage().contains("is already being used by")) { - return; - } // its ok not to remove resources in use elsewhere. - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing global forwarding rule " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - } - - /* - * takes either a targetHttpProxy name or url - */ - public void removeTargetHttpProxy(@Nonnull String targetHttpProxy) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - Operation job = gce.targetHttpProxies().delete(ctx.getAccountNumber(), targetHttpProxy.replaceAll(".*/", "")).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (!ex.getMessage().contains("is already being used by")) { - return; - } - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing target http proxy " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - } - - /* - * takes either a urlMap name or url - */ - public void removeUrlMap(@Nonnull String urlMap) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - Operation job = gce.urlMaps().delete(ctx.getAccountNumber(), urlMap.replaceAll(".*/", "")).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing url map " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error removing url map " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - /* - * takes either a backendService name or url - */ - public void removeBackendService(@Nonnull String backendService) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - Operation job = gce.backendServices().delete(ctx.getAccountNumber(), backendService.replaceAll(".*/", "")).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (!ex.getMessage().contains("is already being used by")) { - return; - } // its ok not to remove resources in use elsewhere. - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing backend service " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - } - - /* - * takes either a httpHealthCheck name or url - */ - public void removeHttpHealthCheck(@Nonnull String httpHealthCheck) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - Operation job = gce.httpHealthChecks().delete(ctx.getAccountNumber(), httpHealthCheck.replaceAll(".*/", "")).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (!ex.getMessage().contains("is already being used by")) { - return; - } // its ok not to remove resources in use elsewhere. - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing http health check " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - } - - @Override - public void removeConvergedHttpLoadBalancers(@Nonnull String urlMap) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - urlMap = urlMap.replaceAll(".*/", ""); - try { - ForwardingRuleList forwardingRuleList = gce.globalForwardingRules().list(ctx.getAccountNumber()).execute(); - TargetHttpProxyList targetHttpProxyList = gce.targetHttpProxies().list(ctx.getAccountNumber()).execute(); - - for (TargetHttpProxy targetProxy: targetHttpProxyList.getItems()) { - if (targetProxy.getUrlMap().endsWith(urlMap)) { - for (ForwardingRule forwardingRule: forwardingRuleList.getItems()) { - if (forwardingRule.getTarget().endsWith(targetProxy.getName())) { - removeGlobalForwardingRule(forwardingRule.getName()); - } - } - removeTargetHttpProxy(targetProxy.getName()); - } - } - - UrlMap um = gce.urlMaps().get(ctx.getAccountNumber(), urlMap).execute(); - - List backendServices = new ArrayList(); - backendServices.add(um.getDefaultService().replaceAll(".*/", "")); - List pathMatchers = um.getPathMatchers(); - for (PathMatcher pathMatcher: pathMatchers) { - backendServices.add(pathMatcher.getDefaultService().replaceAll(".*/", "")); - if (null != pathMatcher.getPathRules()) { - for (PathRule pathRule: pathMatcher.getPathRules()) { - backendServices.add(pathRule.getService().replaceAll(".*/", "")); - } - } - } - - removeUrlMap(um.getName()); - - List healthChecks = new ArrayList(); - for (String backendService : new HashSet(backendServices)) { // use HashSet to make it unique list - BackendService bes = gce.backendServices().get(ctx.getAccountNumber(), backendService).execute(); - for (String healthCheck : bes.getHealthChecks()) { - healthChecks.add(healthCheck); - } - removeBackendService(backendService); - } - - for (String healthCheck : new HashSet(healthChecks)) { // use HashSet to make it unique list - removeHttpHealthCheck(healthCheck); - } - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred removing convergedHttpLoadBalancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error removing Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - public void createBackendService(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - GoogleMethod method = new GoogleMethod(provider); - - List backendServices = withConvergedHttpLoadBalancerOptions.getBackendServices(); - for (ConvergedHttpLoadBalancer.BackendService backendService : backendServices) { - if (null == backendService.getSelfLink()) { - BackendService beContent = new BackendService(); - beContent.setName(getCapabilities().getConvergedHttpLoadBalancerNamingConstraints().convertToValidName(backendService.getName(), Locale.US)); - beContent.setDescription(backendService.getDescription()); - beContent.setPort(backendService.getPort()); - beContent.setPortName(backendService.getPortName()); - beContent.setTimeoutSec(backendService.getTimeoutSec()); - - List healthCheckSelfUrls = new ArrayList(); - for (String healthCheckName : backendService.getHealthChecks()) { - healthCheckSelfUrls.add(withConvergedHttpLoadBalancerOptions.getHealthCheckSelfUrl(healthCheckName)); - } - beContent.setHealthChecks(healthCheckSelfUrls); - - List backends = new ArrayList(); - - for (String backendServiceInstranceGroupSelfUrl : backendService.getBackendServiceBackends()) { - Backend backend = new Backend(); - backend.setGroup(backendServiceInstranceGroupSelfUrl); - backends.add(backend); - } - - beContent.setBackends(backends); - - try { - Operation foo = gce.backendServices().insert(ctx.getAccountNumber(), beContent ).execute(); - method.getOperationComplete(provider.getContext(), foo, GoogleOperationType.GLOBAL_OPERATION, null, null); - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred creating backend service " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch ( Exception ex ) { - throw new GeneralCloudException("Error creating backend service " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - backendService.setServiceUrl(gce.getBaseUrl() + ctx.getAccountNumber() + "/global/backendServices/" + backendService.getName()); - } - } - } - - public void createURLMap(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - GoogleMethod method = new GoogleMethod(provider); - - String origName = withConvergedHttpLoadBalancerOptions.getName(); - String validName = getCapabilities().getConvergedHttpLoadBalancerNamingConstraints().convertToValidName(origName, Locale.US); - - try { - List urlSets = withConvergedHttpLoadBalancerOptions.getUrlSets(); - - UrlMap urlMap = new UrlMap(); - - List pathMatchers = new ArrayList(); - List hostRules = new ArrayList(); - - for (ConvergedHttpLoadBalancer.UrlSet urlSet : urlSets) { - HostRule hostRule = new HostRule(); - List hosts = new ArrayList(); - String hostMatchPatterns = urlSet.getHostMatchPatterns(); - if (hostMatchPatterns.contains(",")) { - for (String hostMatchPattern : hostMatchPatterns.split(", ?")) { - hosts.add(hostMatchPattern); - } - } else { - hosts.add(hostMatchPatterns); - } - hostRule.setHosts(hosts); - hostRule.setPathMatcher(urlSet.getName()); - hostRules.add(hostRule); - - PathMatcher pathMatcher = new PathMatcher(); - pathMatcher.setName(urlSet.getName()); - //pathMatcher.setDescription(urlSet.getDescription()); // GCE does not support - - List pathRules = new ArrayList(); - - Map pathMap = urlSet.getPathMap(); - for (String key : pathMap.keySet()) { - PathRule pathRule = new PathRule(); - List paths = new ArrayList(); - if (key.equals("/*")) { - pathMatcher.setDefaultService(withConvergedHttpLoadBalancerOptions.getBackendServiceSelfUrl(pathMap.get(key))); - } else { - if (key.contains(",")) { - for (String path : key.split(", *")) { - paths.add(path); - } - } else { - paths.add(key); - } - pathRule.setPaths(paths); - pathRule.setService(withConvergedHttpLoadBalancerOptions.getBackendServiceSelfUrl(pathMap.get(key))); - pathRules.add(pathRule); - } - } - pathMatcher.setPathRules(pathRules); - pathMatchers.add(pathMatcher); - } - - urlMap.setHostRules(hostRules); - urlMap.setName(validName); - urlMap.setPathMatchers(pathMatchers); - urlMap.setDescription(withConvergedHttpLoadBalancerOptions.getDescription()); // GCE does not support - urlMap.setDefaultService(withConvergedHttpLoadBalancerOptions.getBackendServiceSelfUrl(withConvergedHttpLoadBalancerOptions.getDefaultBackendService())); - Operation job = gce.urlMaps().insert(ctx.getAccountNumber(), urlMap ).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred creating url map " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error creating url map " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - - withConvergedHttpLoadBalancerOptions.setUrlMapSelfUrl(gce.getBaseUrl() + ctx.getAccountNumber() + "/global/urlMaps/" + validName); - } - - public void createTargetProxy(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - GoogleMethod method = new GoogleMethod(provider); - TargetHttpProxy content = new TargetHttpProxy(); - - List targetHttpProxies = withConvergedHttpLoadBalancerOptions.getTargetHttpProxies(); - try { - for (ConvergedHttpLoadBalancer.TargetHttpProxy targetHttpProxy : targetHttpProxies) { - content.setName(getCapabilities().getConvergedHttpLoadBalancerNamingConstraints().convertToValidName(targetHttpProxy.getName(), Locale.US)); - content.setDescription(targetHttpProxy.getDescription()); - content.setUrlMap(withConvergedHttpLoadBalancerOptions.getSelfLink()); - Operation job = gce.targetHttpProxies().insert(ctx.getAccountNumber(), content ).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - targetHttpProxy.setTargetProxySelfUrl(gce.getBaseUrl() + ctx.getAccountNumber() + "/global/targetHttpProxies/" + targetHttpProxy.getName()); - } - } catch (IOException ex) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred creating target proxy " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error creating target proxy " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - public void createGlobalForwardingRule(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - GoogleMethod method = new GoogleMethod(provider); - ForwardingRule gfwContent = new ForwardingRule(); - - List forwardingRules = withConvergedHttpLoadBalancerOptions.getForwardingRules(); - try { - for (ConvergedHttpLoadBalancer.ForwardingRule forwardingRule : forwardingRules) { - gfwContent.setName(getCapabilities().getConvergedHttpLoadBalancerNamingConstraints().convertToValidName(forwardingRule.getName(), Locale.US)); - gfwContent.setDescription(forwardingRule.getDescription()); - if (null != forwardingRule.getIpAddress()) { - gfwContent.setIPAddress(forwardingRule.getIpAddress()); - } - gfwContent.setIPProtocol(forwardingRule.getIpProtocol()); - gfwContent.setPortRange(forwardingRule.getPortRange()); - gfwContent.setTarget(withConvergedHttpLoadBalancerOptions.getTargetProxySelfUrl(forwardingRule.getTarget())); - Operation job = gce.globalForwardingRules().insert(ctx.getAccountNumber(), gfwContent ).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - forwardingRule.setGlobalForwardingRuleSelfUrl(gce.getBaseUrl() + ctx.getAccountNumber() + "/global/httpHealthChecks/" + forwardingRule.getName()); - } - } catch (IOException ex) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred creating GlobalForwardingRule: " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error occurred creating GlobalForwardingRule: " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - @Override - public String createConvergedHttpLoadBalancer(@Nonnull ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - try { - createHttpHealthChecks(withConvergedHttpLoadBalancerOptions); - } catch (Exception ex) { - throw new GeneralCloudException("Error creating Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - try { - createBackendService(withConvergedHttpLoadBalancerOptions); - } catch (Exception ex) { - throw new GeneralCloudException("Error creating Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - try { - createURLMap(withConvergedHttpLoadBalancerOptions); - } catch (Exception ex) { - throw new GeneralCloudException("Error creating Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - try { - createTargetProxy(withConvergedHttpLoadBalancerOptions); - } catch (Exception ex) { - throw new GeneralCloudException("Error creating Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - try { - createGlobalForwardingRule(withConvergedHttpLoadBalancerOptions); - } catch (Exception ex) { - throw new GeneralCloudException("Error creating Converged Http Load Balancer " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - - return withConvergedHttpLoadBalancerOptions.getSelfLink(); - } - - private void createHttpHealthChecks(ConvergedHttpLoadBalancer withConvergedHttpLoadBalancerOptions) throws CloudException, InternalException { - Compute gce = provider.getGoogleCompute(); - - GoogleMethod method = new GoogleMethod(provider); - try { - List healthChecks = withConvergedHttpLoadBalancerOptions.getHealthChecks(); - for (ConvergedHttpLoadBalancer.HealthCheck healthCheck : healthChecks) { - if (null == healthCheck.getSelfLink()) { - HttpHealthCheck httpHealthCheck = new HttpHealthCheck(); - httpHealthCheck.setName(getCapabilities().getConvergedHttpLoadBalancerNamingConstraints().convertToValidName(healthCheck.getName(), Locale.US)); - httpHealthCheck.setDescription(healthCheck.getDescription()); - httpHealthCheck.setCheckIntervalSec(healthCheck.getCheckIntervalSec()); - httpHealthCheck.setHealthyThreshold(healthCheck.getHealthyThreshold()); - httpHealthCheck.setUnhealthyThreshold(healthCheck.getUnHealthyThreshold()); - httpHealthCheck.setTimeoutSec(healthCheck.getTimeoutSec()); - httpHealthCheck.setHost(healthCheck.getHost()); // optional i think - httpHealthCheck.setPort(healthCheck.getPort()); - httpHealthCheck.setRequestPath(healthCheck.getRequestPath()); - Operation job = gce.httpHealthChecks().insert(ctx.getAccountNumber(), httpHealthCheck).execute(); - method.getOperationComplete(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, null, null); - healthCheck.setSelfLink(gce.getBaseUrl() + ctx.getAccountNumber() + "/global/httpHealthChecks/" + healthCheck.getName()); - } - } - } catch ( IOException ex ) { - if (ex.getClass() == GoogleJsonResponseException.class) { - GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex; - throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); - } else { - throw new GeneralCloudException("An error occurred creating http health checks " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } catch (Exception ex) { - throw new GeneralCloudException("Error creating http health checks " + ex.getMessage(), ex, CloudErrorType.GENERAL); - } - } - - @Override - public void updateTags(String convergedHttpLoadbalancerId, Tag... tags) throws CloudException, InternalException { - // TODO Auto-generated method stub - } - - @Override - public void updateTags(String[] convergedHttpLoadbalancerIds, Tag... tags) throws CloudException, InternalException { - // TODO Auto-generated method stub - } - - @Override - public void removeTags(String convergedHttpLoadbalancerId, Tag... tags) throws CloudException, InternalException { - // TODO Auto-generated method stub - } - - @Override - public void removeTags(String[] convergedHttpLoadbalancerIds, Tag... tags) throws CloudException, InternalException { - // TODO Auto-generated method stub - } - - @Override - public String[] mapServiceAction(ServiceAction action) { - // TODO Auto-generated method stub - return null; - } -} From bf5980dfbb44b4e54a1e68531d4726385bf3328c Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Thu, 19 May 2016 14:42:26 +0100 Subject: [PATCH 04/15] unit tests (dc and server support) --- pom.xml | 16 +- .../org/dasein/cloud/google/DataCenters.java | 3 +- .../dasein/cloud/google/DatacentersTest.java | 146 ++++ .../dasein/cloud/google/GoogleTestBase.java | 59 ++ .../cloud/google/ServerSupportTest.java | 628 ++++++++++++++++++ 5 files changed, 846 insertions(+), 6 deletions(-) create mode 100644 src/test/java/org/dasein/cloud/google/DatacentersTest.java create mode 100644 src/test/java/org/dasein/cloud/google/GoogleTestBase.java create mode 100644 src/test/java/org/dasein/cloud/google/ServerSupportTest.java diff --git a/pom.xml b/pom.xml index 3d84700..8c313ee 100644 --- a/pom.xml +++ b/pom.xml @@ -149,19 +149,27 @@ test + + org.jmockit + jmockit + 1.19 + test + + junit junit 4.9 test - - org.jmockit - jmockit - 1.19 + commons-collections + commons-collections + 3.2.1 test + + diff --git a/src/main/java/org/dasein/cloud/google/DataCenters.java b/src/main/java/org/dasein/cloud/google/DataCenters.java index 1c19995..76b5339 100755 --- a/src/main/java/org/dasein/cloud/google/DataCenters.java +++ b/src/main/java/org/dasein/cloud/google/DataCenters.java @@ -190,8 +190,7 @@ public Collection listRegions() throws InternalException, CloudException Compute gce = provider.getGoogleCompute(); Compute.Regions.List gceRegions = null; try { - gceRegions = gce.regions().list(ctx.getAccountNumber()); - RegionList regionList = gceRegions.execute(); + RegionList regionList = gce.regions().list(ctx.getAccountNumber()).execute(); if ((null != regionList) && (null != regionList.getItems())) { List regionListItems = regionList.getItems(); for(int i=0;i + * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.model.Region; +import com.google.api.services.compute.model.RegionList; +import com.google.api.services.compute.model.Zone; +import com.google.api.services.compute.model.ZoneList; +import mockit.NonStrictExpectations; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.dc.DataCenter; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * User: daniellemayne + * Date: 16/05/2016 + * Time: 09:20 + */ +@RunWith(JUnit4.class) +public class DatacentersTest extends GoogleTestBase{ + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + } + + private ZoneList getTestDataCenterList() { + List zoneList = new ArrayList(); + + Zone dc1 = new Zone(); + dc1.setName(TEST_DATACENTER); + dc1.setRegion(TEST_REGION); + dc1.setStatus("UP"); + zoneList.add(dc1); + + Zone dc2 = new Zone(); + dc2.setName("TEST_DC_2"); + dc2.setRegion(TEST_REGION); + dc2.setStatus("UP"); + zoneList.add(dc2); + + ZoneList dcList = new ZoneList(); + dcList.setItems(zoneList); + return dcList; + } + + private RegionList getTestRegionList() { + List regionList = new ArrayList(); + + Region region = new Region(); + region.setName(TEST_REGION);; + regionList.add(region); + + Region region1 = new Region(); + region1.setName("TEST_REGION_2"); + regionList.add(region1); + + RegionList regionList1 = new RegionList(); + regionList1.setItems(regionList); + return regionList1; + } + + @Test + public void listDatacenters_shouldReturnAllAvailableDCs() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.zones().list(anyString).execute(); + result = getTestDataCenterList();} + + }; + DataCenters dc = new DataCenters(googleProviderMock); + Collection list = dc.listDataCenters(TEST_REGION); + assertNotNull("Datacenter list can be empty but not null", list); + assertTrue(list.size() == 2); + } + + @Test + public void getDatacenter_shouldReturnCorrectDC() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.zones().get(TEST_ACCOUNT_NO, TEST_DATACENTER).execute(); + result = getTestDataCenterList().getItems().get(0);} + + }; + DataCenters dc = new DataCenters(googleProviderMock); + DataCenter list = dc.getDataCenter(TEST_DATACENTER); + assertNotNull(list); + assertTrue(list.getName().equals(TEST_DATACENTER)); + assertTrue(list.getProviderDataCenterId().equals(TEST_DATACENTER)); + assertTrue(list.getRegionId().equals(TEST_REGION)); + } + + @Test + public void getRegion_shouldReturnCorrectRegion() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.regions().get(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestRegionList().getItems().get(0);} + + }; + DataCenters dc = new DataCenters(googleProviderMock); + org.dasein.cloud.dc.Region list = dc.getRegion(TEST_REGION); + assertNotNull(list); + assertTrue(list.getName().equals(TEST_REGION)); + assertTrue(list.getProviderRegionId().equals(TEST_REGION)); + assertTrue(list.getJurisdiction().equals("US")); + } + + @Test + public void listRegions_shouldReturnAllAvailableRegions() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.regions().list(anyString).execute(); + result = getTestRegionList(); + } + }; + DataCenters dc = new DataCenters(googleProviderMock); + Collection list = dc.listRegions(); + assertNotNull("Region list can be empty but not null", list); + assertTrue(list.size() == 2); + } +} diff --git a/src/test/java/org/dasein/cloud/google/GoogleTestBase.java b/src/test/java/org/dasein/cloud/google/GoogleTestBase.java new file mode 100644 index 0000000..c00c413 --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/GoogleTestBase.java @@ -0,0 +1,59 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.Compute; +import mockit.Mocked; +import mockit.NonStrictExpectations; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.ProviderContext; +import org.junit.Before; + +/** + * User: daniellemayne + * Date: 16/05/2016 + * Time: 12:02 + */ +public class GoogleTestBase { + @Mocked + Google googleProviderMock; + @Mocked + ProviderContext providerContextMock; + @Mocked + Compute googleComputeMock; + @Mocked + GoogleMethod googleMethodMock; + + final String TEST_ACCOUNT_NO = "12323232323"; + final String TEST_REGION = "us-central1"; + final String TEST_DATACENTER = "us-central1-a"; + final String TEST_VM_ID = "VMNAME_111122223333"; + + @Before + public void setUp() throws CloudException, InternalException { + new NonStrictExpectations() { + { googleProviderMock.getContext(); result = providerContextMock; } + { providerContextMock.getAccountNumber(); result = TEST_ACCOUNT_NO; } + { providerContextMock.getRegionId(); result = TEST_REGION; } + { googleProviderMock.getGoogleCompute(); result = googleComputeMock; } + }; + } +} diff --git a/src/test/java/org/dasein/cloud/google/ServerSupportTest.java b/src/test/java/org/dasein/cloud/google/ServerSupportTest.java new file mode 100644 index 0000000..30f3ba7 --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/ServerSupportTest.java @@ -0,0 +1,628 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.model.Image; +import com.google.api.services.compute.model.Instance; +import com.google.api.services.compute.model.InstanceAggregatedList; +import com.google.api.services.compute.model.InstancesScopedList; +import com.google.api.services.compute.model.MachineType; +import com.google.api.services.compute.model.MachineTypeAggregatedList; +import com.google.api.services.compute.model.MachineTypeList; +import com.google.api.services.compute.model.MachineTypesScopedList; +import com.google.api.services.compute.model.NetworkInterface; +import com.google.api.services.compute.model.Operation; +import com.google.api.services.compute.model.SerialPortOutput; +import mockit.NonStrictExpectations; +import org.apache.commons.collections.IteratorUtils; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.OperationNotSupportedException; +import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.VisibleScope; +import org.dasein.cloud.compute.Architecture; +import org.dasein.cloud.compute.ImageClass; +import org.dasein.cloud.compute.MachineImage; +import org.dasein.cloud.compute.MachineImageState; +import org.dasein.cloud.compute.Platform; +import org.dasein.cloud.compute.VMFilterOptions; +import org.dasein.cloud.compute.VMLaunchOptions; +import org.dasein.cloud.compute.VirtualMachine; +import org.dasein.cloud.compute.VirtualMachineProduct; +import org.dasein.cloud.compute.VmState; +import org.dasein.cloud.compute.Volume; +import org.dasein.cloud.google.compute.server.ServerSupport; +import org.dasein.cloud.network.VLAN; +import org.joda.time.DateTime; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * User: daniellemayne + * Date: 16/05/2016 + * Time: 11:53 + */ +@RunWith(JUnit4.class) +public class ServerSupportTest extends GoogleTestBase { + private ServerSupport support = null; + + final String TEST_PRODUCT_ID = "g1-small+"+TEST_DATACENTER; + final String TEST_MACHINE_IMAGE_ID = "TEST_MACHINE_IMAGE_ID"; + final String TEST_HOST_NAME = "TEST_HOST_NAME"; + final String TEST_FRIENDLY_NAME = "TEST_FRIENDLY_NAME"; + final String TEST_DESCRIPTION = "TEST_DESCRIPTION"; + final String TEST_VLAN_ID = "TEST_VLAN_ID"; + + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + support = new ServerSupport(googleProviderMock); + } + + private Iterable getTestVirtualMachineList() { + List list = new ArrayList(); + VirtualMachine vm = new VirtualMachine(); + vm.setProviderVirtualMachineId(TEST_VM_ID); + vm.setName("name"); + vm.setProviderDataCenterId(TEST_DATACENTER); + list.add(vm); + + VirtualMachine vm2 = new VirtualMachine(); + vm2.setProviderVirtualMachineId("name2_id2"); + vm2.setName("name2"); + vm.setProviderDataCenterId(TEST_DATACENTER); + list.add(vm); + + return list; + } + + private MachineTypeList getTestMachineTypeList() { + MachineType type = new MachineType(); + type.setName("g1-small"); + type.setZone(TEST_DATACENTER); + type.setSelfLink("https://www.googleapis.com/compute/v1/projects/qa-project-2/zones/us-central1-a/machineTypes/g1-small"); + type.setGuestCpus(1); + type.setMemoryMb(1740); + + MachineType type2 = new MachineType(); + type2.setName("g1-medium"); + type2.setZone(TEST_DATACENTER); + type2.setSelfLink("https://www.googleapis.com/compute/v1/projects/qa-project-2/zones/us-central1-a/machineTypes/g1-medium"); + type2.setGuestCpus(2); + type2.setMemoryMb(3440); + + List types = new ArrayList<>(); + types.add(type); + types.add(type2); + + MachineTypeList list = new MachineTypeList(); + list.setItems(types); + return list; + } + + private InstanceAggregatedList getTestInstanceAggregatedList() { + Instance instance = new Instance(); + instance.setName("VMNAME"); + instance.setId(new BigInteger("111122223333")); + instance.setDescription("VM_DESCRIPTION"); + instance.setStatus("RUNNING"); + instance.setStatusMessage("SUCCESS"); + instance.setZone(TEST_DATACENTER); + instance.setCreationTimestamp("2016-05-16T12:57:34.123+00:00"); //yyyy-MM-dd'T'HH:mm:ss.SSSZZ + instance.setMachineType("g1-small"); + instance.setSelfLink("https://www.googleapis.com/compute/v1/projects/qa-project-2/zones/us-central1-a/instances/VM_NAME"); + NetworkInterface net = new NetworkInterface(); + net.setNetwork("TEST_NET"); + List netList = new ArrayList<>(); + netList.add(net); + instance.setNetworkInterfaces(netList); + List list = new ArrayList<>(); + list.add(instance); + + + Instance instance2 = new Instance(); + instance2.setName("VMNAME2"); + instance2.setId(new BigInteger("111122224444")); + instance2.setDescription("VM_DESCRIPTION2"); + instance2.setStatus("TERMINATED"); + instance2.setStatusMessage("SUCCESS"); + instance2.setZone(TEST_DATACENTER); + instance2.setCreationTimestamp("2016-05-17T15:57:34.123+00:00"); //yyyy-MM-dd'T'HH:mm:ss.SSSZZ + instance2.setMachineType("g1-small"); + instance2.setSelfLink("https://www.googleapis.com/compute/v1/projects/qa-project-2/zones/us-central1-a/instances/VM_NAME2"); + NetworkInterface net2 = new NetworkInterface(); + net2.setNetwork("TEST_NET2"); + List netList2 = new ArrayList<>(); + netList2.add(net2); + instance2.setNetworkInterfaces(netList2); + list.add(instance2); + InstancesScopedList isl = new InstancesScopedList(); + isl.setInstances(list); + Map map = new HashMap<>(); + map.put(TEST_DATACENTER, isl); + InstanceAggregatedList ial = new InstanceAggregatedList(); + ial.setItems(map); + return ial; + } + + private MachineTypeAggregatedList getTestMachineTypeAggregatedList() { + List list = getTestMachineTypeList().getItems(); + List list2 = new ArrayList<>(); + + MachineType type = new MachineType(); + type.setName("g1-small"); + type.setZone("us-central-1b"); + type.setSelfLink("https://www.googleapis.com/compute/v1/projects/qa-project-2/zones/us-central1-b/machineTypes/g1-small"); + type.setGuestCpus(1); + type.setMemoryMb(1740); + list2.add(type); + + MachineTypesScopedList mtsl = new MachineTypesScopedList(); + mtsl.setMachineTypes(list); + MachineTypesScopedList mtsl2 = new MachineTypesScopedList(); + mtsl2.setMachineTypes(list2); + + Map map = new HashMap<>(); + map.put(TEST_DATACENTER, mtsl); + map.put("us-central-1b", mtsl2); + + MachineTypeAggregatedList mtal = new MachineTypeAggregatedList(); + mtal.setItems(map); + + return mtal; + } + + @Test(expected = OperationNotSupportedException.class) + public void clone_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.clone("", "", "", "", true); + + } + + @Test(expected = OperationNotSupportedException.class) + public void getPassword_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.getPassword(""); + } + + @Test + public void getVmNameFromId() throws CloudException, InternalException { + String name = support.getVmNameFromId("name_id"); + assertTrue(name.equals("name")); + } + + @Test + public void getVmIdFromName() throws CloudException, InternalException { + new NonStrictExpectations(ServerSupport.class) { + {support.getVirtualMachine(anyString); + result = getTestVirtualMachineList().iterator().next(); + } + }; + String id = support.getVmIdFromName("name"); + assertTrue(id.equals(TEST_VM_ID)); + } + + @Test + public void getConsoleOutput_shouldReturnOutputForCorrectVm() throws CloudException, InternalException, IOException { + final SerialPortOutput output = new SerialPortOutput(); + output.setContents("content"); + + new NonStrictExpectations(ServerSupport.class) { + {support.listVirtualMachines(); + result = getTestVirtualMachineList(); + } + {googleComputeMock.instances().getSerialPortOutput(TEST_ACCOUNT_NO, TEST_DATACENTER, "VMNAME").execute(); + result = output; + } + }; + + String consoleOutput = support.getConsoleOutput(TEST_VM_ID); + assertTrue(consoleOutput.equals("content")); + } + + + @Test + public void getProduct_shouldReturnCorrectProduct() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.machineTypes().list(TEST_ACCOUNT_NO, TEST_DATACENTER).setFilter(anyString).execute(); + result = getTestMachineTypeList(); + } + }; + VirtualMachineProduct product = support.getProduct(TEST_PRODUCT_ID); + assertNotNull(product); + assertTrue(product.getProviderProductId().equals(TEST_PRODUCT_ID)); + assertTrue(product.getName().equals("g1-small")); + assertTrue(product.getDescription().equals("https://www.googleapis.com/compute/v1/projects/qa-project-2/zones/us-central1-a/machineTypes/g1-small")); + assertTrue(product.getCpuCount() == 1); + assertTrue(product.getRamSize().intValue() == 1740); + assertTrue(product.getRootVolumeSize().intValue() == 0); + assertTrue(product.getVisibleScope().equals(VisibleScope.ACCOUNT_DATACENTER)); + } + + @Test + public void getVirtualMachine_shouldReturnCorrectVM() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.instances().aggregatedList(TEST_ACCOUNT_NO).setFilter(anyString).execute(); + result = getTestInstanceAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(anyString); + result = TEST_REGION; + } + }; + + VirtualMachine vm = support.getVirtualMachine(TEST_VM_ID); + assertNotNull(vm); + assertTrue(vm.getProviderVirtualMachineId().equals(TEST_VM_ID)); + assertTrue(vm.getName().equals("VMNAME")); + assertTrue(vm.getDescription().equals("VM_DESCRIPTION")); + assertTrue(vm.getProviderOwnerId().equals(TEST_ACCOUNT_NO)); + assertTrue(vm.getCurrentState().equals(VmState.RUNNING)); + assertTrue(vm.getProviderRegionId().equals(TEST_REGION)); + assertTrue(vm.getProviderDataCenterId().equals(TEST_DATACENTER)); + + DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); + DateTime dt = DateTime.parse("2016-05-16T12:57:34.123+00:00", fmt); + assertTrue(vm.getCreationTimestamp() == dt.toDate().getTime()); + assertTrue(vm.getProductId().equals(TEST_PRODUCT_ID)); + assertTrue(vm.getProviderVlanId().equals("TEST_NET")); + } + + @Test(expected = InternalException.class) + public void validateLaunchOptions_shouldThrowExceptionWhenDatacenterNotSpecified() throws CloudException, InternalException { + VMLaunchOptions options = VMLaunchOptions.getInstance(TEST_PRODUCT_ID, TEST_MACHINE_IMAGE_ID, TEST_HOST_NAME, TEST_FRIENDLY_NAME, TEST_DESCRIPTION); + options = options.inVlan(null, TEST_DATACENTER, TEST_VLAN_ID) + .inDataCenter(null); + + final VLAN network = new VLAN(); + network.setTag("contentLink", "vlanContentLink"); + + new NonStrictExpectations() { + {googleProviderMock.getNetworkServices().getVlanSupport().getVlan(TEST_VLAN_ID); + result = network; + } + {googleProviderMock.getComputeServices().getVolumeSupport().getVolume(anyString); + result = null; + } + }; + + support.validateLaunchOptions(options); + } + + @Test(expected = InternalException.class) + public void validateLaunchOptions_shouldThrowExceptionWhenMachineImageNotSpecified() throws CloudException, InternalException { + VMLaunchOptions options = VMLaunchOptions.getInstance(TEST_PRODUCT_ID, null, TEST_HOST_NAME, TEST_FRIENDLY_NAME, TEST_DESCRIPTION); + options = options.inVlan(null, TEST_DATACENTER, TEST_VLAN_ID); + + final VLAN network = new VLAN(); + network.setTag("contentLink", "vlanContentLink"); + + new NonStrictExpectations() { + {googleProviderMock.getNetworkServices().getVlanSupport().getVlan(TEST_VLAN_ID); + result = network; + } + {googleProviderMock.getComputeServices().getVolumeSupport().getVolume(anyString); + result = null; + } + }; + + support.validateLaunchOptions(options); + } + + @Test(expected = InternalException.class) + public void validateLaunchOptions_shouldThrowExceptionWhenHostnameNotSpecified() throws CloudException, InternalException { + VMLaunchOptions options = VMLaunchOptions.getInstance(TEST_PRODUCT_ID, TEST_MACHINE_IMAGE_ID, null, TEST_FRIENDLY_NAME, TEST_DESCRIPTION); + options = options.inVlan(null, TEST_DATACENTER, TEST_VLAN_ID); + + final VLAN network = new VLAN(); + network.setTag("contentLink", "vlanContentLink"); + + new NonStrictExpectations() { + {googleProviderMock.getNetworkServices().getVlanSupport().getVlan(TEST_VLAN_ID); + result = network; + } + {googleProviderMock.getComputeServices().getVolumeSupport().getVolume(anyString); + result = null; + } + }; + + support.validateLaunchOptions(options); + } + + @Test(expected = InternalException.class) + public void validateLaunchOptions_shouldThrowExceptionWhenVlanNotSpecified() throws CloudException, InternalException { + VMLaunchOptions options = VMLaunchOptions.getInstance(TEST_PRODUCT_ID, TEST_MACHINE_IMAGE_ID, TEST_HOST_NAME, TEST_FRIENDLY_NAME, TEST_DESCRIPTION); + final VLAN network = new VLAN(); + network.setTag("contentLink", "vlanContentLink"); + + new NonStrictExpectations() { + {googleProviderMock.getNetworkServices().getVlanSupport().getVlan(TEST_VLAN_ID); + result = network; + } + {googleProviderMock.getComputeServices().getVolumeSupport().getVolume(anyString); + result = null; + } + }; + + support.validateLaunchOptions(options); + } + + @Test(expected = InternalException.class) + public void validateLaunchOptions_shouldThrowExceptionWhenDuplicateHostnameSpecified() throws CloudException, InternalException { + VMLaunchOptions options = VMLaunchOptions.getInstance(TEST_PRODUCT_ID, TEST_MACHINE_IMAGE_ID, TEST_HOST_NAME, TEST_FRIENDLY_NAME, TEST_DESCRIPTION); + options = options.inVlan(null, TEST_DATACENTER, TEST_VLAN_ID); + + final VLAN network = new VLAN(); + network.setTag("contentLink", "vlanContentLink"); + + new NonStrictExpectations() { + {googleProviderMock.getNetworkServices().getVlanSupport().getVlan(TEST_VLAN_ID); + result = network; + } + {googleProviderMock.getComputeServices().getVolumeSupport().getVolume(anyString); + result = new Volume(); + } + }; + + support.validateLaunchOptions(options); + } + + @Test + public void launch_shouldReturnVm() throws CloudException, InternalException, IOException { + VMLaunchOptions options = VMLaunchOptions.getInstance(TEST_PRODUCT_ID, TEST_MACHINE_IMAGE_ID, TEST_HOST_NAME, TEST_FRIENDLY_NAME, TEST_DESCRIPTION); + options = options.inVlan(null, TEST_DATACENTER, TEST_VLAN_ID); + + final VLAN network = new VLAN(); + network.setTag("contentLink", "vlanContentLink"); + + final MachineImage image = MachineImage.getInstance("OWNER", TEST_REGION, TEST_MACHINE_IMAGE_ID, ImageClass.MACHINE, MachineImageState.ACTIVE, + "IMAGE_NAME", "IMAGE_DESCRIPTION", Architecture.I64, Platform.CENT_OS); + image.setTag("contentLink", "imageContentLink"); + + final Image gceImage = new Image(); + gceImage.setLicenses(Collections.singletonList("LICENSE")); + gceImage.setDescription("DESCRIPTION"); + gceImage.setName("GCE_IMAGE_NAME"); + gceImage.setDiskSizeGb(10l); + + new NonStrictExpectations(ServerSupport.class) { + {googleProviderMock.getNetworkServices().getVlanSupport().getVlan(TEST_VLAN_ID); + result = network; + } + {googleProviderMock.getComputeServices().getVolumeSupport().getVolume(anyString); + result = null; + } + {support.getProduct(anyString).getDescription(); + result = TEST_PRODUCT_ID; + } + {googleProviderMock.getComputeServices().getImageSupport().getImage(TEST_MACHINE_IMAGE_ID); + result = image; + } + {googleComputeMock.images().get(anyString, anyString).execute(); + result = gceImage; + } + {googleComputeMock.instances().insert(TEST_ACCOUNT_NO, TEST_DATACENTER, (Instance)any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationTarget(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, "", TEST_DATACENTER, false); + result = TEST_VM_ID; + } + {support.getVirtualMachine(TEST_VM_ID); + result = new VirtualMachine(); + } + }; + + VirtualMachine vm = support.launch(options); + assertNotNull(vm); + } + + @Test + public void listProducts_shouldReturnProductsForSpecifiedDatacenter() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.machineTypes().aggregatedList(TEST_ACCOUNT_NO).execute(); + result = getTestMachineTypeAggregatedList(); + } + }; + + Iterable products = support.listProducts(Architecture.I64, TEST_DATACENTER); + assertNotNull(products); + List actualResultAsList = IteratorUtils.toList(products.iterator()); + assertTrue(actualResultAsList.size() == 2); + } + + @Test + public void listVirtualMachines_noFilterShouldReturnAllVMs() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.instances().aggregatedList(TEST_ACCOUNT_NO).execute(); + result = getTestInstanceAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(anyString); + result = TEST_REGION; + } + }; + + Iterable vms = support.listVirtualMachines(null); + assertNotNull(vms); + List resultAsList = IteratorUtils.toList(vms.iterator()); + assertTrue(resultAsList.size() == 2); + } + + @Test + public void listVirtualMachines_DCFilterShouldReturn1VM() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.instances().aggregatedList(TEST_ACCOUNT_NO).execute(); + result = getTestInstanceAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(anyString); + result = TEST_REGION; + } + }; + + Iterable vms = support.listVirtualMachines(VMFilterOptions.getInstance().matchingRegex("VMNAME2")); + assertNotNull(vms); + List resultAsList = IteratorUtils.toList(vms.iterator()); + assertTrue(resultAsList.size() == 1); + } + + @Test + public void listVirtualMachines_shouldReturnAllVMs() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.instances().aggregatedList(TEST_ACCOUNT_NO).execute(); + result = getTestInstanceAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(anyString); + result = TEST_REGION; + } + }; + + Iterable vms = support.listVirtualMachines(); + assertNotNull(vms); + List resultAsList = IteratorUtils.toList(vms.iterator()); + assertTrue(resultAsList.size() == 2); + } + + @Test + public void listVirtualMachinesStatus_shouldReturnCorrectStatusForEachVM() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.instances().aggregatedList(TEST_ACCOUNT_NO).execute(); + result = getTestInstanceAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(anyString); + result = TEST_REGION; + } + }; + + Iterable vms = support.listVirtualMachineStatus(); + assertNotNull(vms); + List resultAsList = IteratorUtils.toList(vms.iterator()); + assertTrue(resultAsList.size() == 2); + ResourceStatus rs = resultAsList.get(0); + assertTrue(rs.getResourceStatus().equals(VmState.RUNNING)); + rs = resultAsList.get(1); + assertTrue(rs.getResourceStatus().equals(VmState.STOPPED)); + } + + @Test(expected = OperationNotSupportedException.class) + public void pause_shouldThrowOperationNotSupportedException() throws CloudException, InternalException{ + support.pause(TEST_VM_ID); + } + + @Test + public void reboot_shouldCreateASuccessfulOperation() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.instances().reset(TEST_ACCOUNT_NO, TEST_DATACENTER, "VMNAME").execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, null, TEST_DATACENTER); + result = true; + } + {googleComputeMock.instances().aggregatedList(TEST_ACCOUNT_NO).execute(); + result = getTestInstanceAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(anyString); + result = TEST_REGION; + } + }; + + support.reboot(TEST_VM_ID); + } + + @Test(expected = OperationNotSupportedException.class) + public void resume_shouldThrowOperationNotSupportedException() throws CloudException, InternalException{ + support.resume(TEST_VM_ID); + } + + @Test(expected = OperationNotSupportedException.class) + public void suspend_shouldThrowOperationNotSupportedException() throws CloudException, InternalException{ + support.suspend(TEST_VM_ID); + } + + @Test + public void start() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.instances().start(TEST_ACCOUNT_NO, TEST_DATACENTER, "VMNAME").execute(); + result = new Operation(); + } + {googleComputeMock.instances().aggregatedList(TEST_ACCOUNT_NO).setFilter(anyString).execute(); + result = getTestInstanceAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(anyString); + result = TEST_REGION; + } + }; + support.start(TEST_VM_ID); + } + + @Test + public void stop() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.instances().stop(TEST_ACCOUNT_NO, TEST_DATACENTER, "VMNAME").execute(); + result = new Operation(); + } + {googleComputeMock.instances().aggregatedList(TEST_ACCOUNT_NO).setFilter(anyString).execute(); + result = getTestInstanceAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(anyString); + result = TEST_REGION; + } + }; + support.stop(TEST_VM_ID, true); + } + + @Test + public void terminate() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.instances().aggregatedList(TEST_ACCOUNT_NO).setFilter(anyString).execute(); + result = getTestInstanceAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(anyString); + result = TEST_REGION; + } + {googleComputeMock.instances().delete(TEST_ACCOUNT_NO, TEST_DATACENTER, "VMNAME").execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, null, TEST_DATACENTER); + result = true; + } + {googleComputeMock.disks().delete(TEST_ACCOUNT_NO, TEST_DATACENTER, anyString).execute(); + result = new Operation(); + } + }; + support.terminate(TEST_VM_ID, "terminate test"); + } + + @Test(expected = OperationNotSupportedException.class) + public void unpause_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.unpause(TEST_VM_ID); + } +} + From 08db4399736d7f5c234e4999b250fdda39d52175 Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Mon, 23 May 2016 14:19:25 +0100 Subject: [PATCH 05/15] diskSupport unit tests --- .../dasein/cloud/google/DatacentersTest.java | 6 +- .../dasein/cloud/google/DiskSupportTest.java | 318 ++++++++++++++++++ 2 files changed, 320 insertions(+), 4 deletions(-) create mode 100644 src/test/java/org/dasein/cloud/google/DiskSupportTest.java diff --git a/src/test/java/org/dasein/cloud/google/DatacentersTest.java b/src/test/java/org/dasein/cloud/google/DatacentersTest.java index e9f8be5..d153555 100644 --- a/src/test/java/org/dasein/cloud/google/DatacentersTest.java +++ b/src/test/java/org/dasein/cloud/google/DatacentersTest.java @@ -47,9 +47,11 @@ */ @RunWith(JUnit4.class) public class DatacentersTest extends GoogleTestBase{ + private DataCenters dc = null; @Before public void setUp() throws CloudException, InternalException { super.setUp(); + dc = new DataCenters(googleProviderMock); } private ZoneList getTestDataCenterList() { @@ -95,7 +97,6 @@ public void listDatacenters_shouldReturnAllAvailableDCs() throws CloudException, result = getTestDataCenterList();} }; - DataCenters dc = new DataCenters(googleProviderMock); Collection list = dc.listDataCenters(TEST_REGION); assertNotNull("Datacenter list can be empty but not null", list); assertTrue(list.size() == 2); @@ -108,7 +109,6 @@ public void getDatacenter_shouldReturnCorrectDC() throws CloudException, Interna result = getTestDataCenterList().getItems().get(0);} }; - DataCenters dc = new DataCenters(googleProviderMock); DataCenter list = dc.getDataCenter(TEST_DATACENTER); assertNotNull(list); assertTrue(list.getName().equals(TEST_DATACENTER)); @@ -123,7 +123,6 @@ public void getRegion_shouldReturnCorrectRegion() throws CloudException, Interna result = getTestRegionList().getItems().get(0);} }; - DataCenters dc = new DataCenters(googleProviderMock); org.dasein.cloud.dc.Region list = dc.getRegion(TEST_REGION); assertNotNull(list); assertTrue(list.getName().equals(TEST_REGION)); @@ -138,7 +137,6 @@ public void listRegions_shouldReturnAllAvailableRegions() throws CloudException, result = getTestRegionList(); } }; - DataCenters dc = new DataCenters(googleProviderMock); Collection list = dc.listRegions(); assertNotNull("Region list can be empty but not null", list); assertTrue(list.size() == 2); diff --git a/src/test/java/org/dasein/cloud/google/DiskSupportTest.java b/src/test/java/org/dasein/cloud/google/DiskSupportTest.java new file mode 100644 index 0000000..6978ea5 --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/DiskSupportTest.java @@ -0,0 +1,318 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.model.AttachedDisk; +import com.google.api.services.compute.model.Disk; +import com.google.api.services.compute.model.DiskAggregatedList; +import com.google.api.services.compute.model.DisksScopedList; +import com.google.api.services.compute.model.Instance; +import com.google.api.services.compute.model.InstanceList; +import com.google.api.services.compute.model.Operation; +import mockit.NonStrictExpectations; +import org.apache.commons.collections.IteratorUtils; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.compute.VirtualMachine; +import org.dasein.cloud.compute.Volume; +import org.dasein.cloud.compute.VolumeCreateOptions; +import org.dasein.cloud.compute.VolumeFilterOptions; +import org.dasein.cloud.compute.VolumeFormat; +import org.dasein.cloud.compute.VolumeState; +import org.dasein.cloud.compute.VolumeType; +import org.dasein.cloud.google.compute.server.DiskSupport; +import org.dasein.util.uom.storage.Storage; +import org.dasein.util.uom.storage.StorageUnit; +import org.joda.time.DateTime; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * User: daniellemayne + * Date: 19/05/2016 + * Time: 12:41 + */ +public class DiskSupportTest extends GoogleTestBase { + private DiskSupport support = null; + final String TEST_VOLUME_ID = "TEST_VOLUME"; + + private DiskAggregatedList getTestDiskAggregatedList() { + Disk disk = new Disk(); + disk.setName(TEST_VOLUME_ID); + disk.setDescription("DESCRIPTION"); + disk.setSelfLink("SELFLINK"); + disk.setZone(TEST_DATACENTER); + disk.setCreationTimestamp("2016-05-23T09:57:34.123+00:00"); //yyyy-MM-dd'T'HH:mm:ss.SSSZZ + disk.setStatus("READY"); + disk.setSizeGb(2l); + + Disk disk2 = new Disk(); + disk2.setName("VOLUMENAME2"); + disk2.setDescription("DESCRIPTION2"); + disk2.setSelfLink("SELFLINK2"); + disk2.setZone(TEST_DATACENTER); + disk2.setCreationTimestamp("2016-05-23T12:57:34.123+00:00"); //yyyy-MM-dd'T'HH:mm:ss.SSSZZ + disk2.setStatus("FAILED"); + disk2.setSizeGb(3l); + + List list = new ArrayList<>(); + list.add(disk); + list.add(disk2); + + DisksScopedList dsl = new DisksScopedList(); + dsl.setDisks(list); + + DiskAggregatedList dal = new DiskAggregatedList(); + Map map = new HashMap<>(); + map.put(TEST_DATACENTER, dsl); + dal.setItems(map); + return dal; + } + + private InstanceList getTestInstanceList() { + Instance instance = new Instance(); + instance.setName("VMNAME"); + instance.setId(new BigInteger("111122223333")); + + AttachedDisk disk = new AttachedDisk(); + disk.setSource("SELFLINK"); + disk.setDeviceName("1"); + List list = new ArrayList<>(); + list.add(disk); + instance.setDisks(list); + + List instanceList = new ArrayList<>(); + instanceList.add(instance); + InstanceList il = new InstanceList(); + il.setItems(instanceList); + return il; + } + + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + support = new DiskSupport(googleProviderMock); + } + + @Test + public void attach_shouldHaveSuccessfulOperationComplete() throws CloudException, InternalException, IOException { + final VirtualMachine vm = new VirtualMachine(); + vm.setProviderVirtualMachineId(TEST_VM_ID); + vm.setName("name"); + vm.setProviderDataCenterId(TEST_DATACENTER); + + final Volume volume = new Volume(); + volume.setTag("contentLink", "CONTENT_LINK"); + + new NonStrictExpectations(DiskSupport.class) { + {googleProviderMock.getComputeServices().getVirtualMachineSupport().getVmNameFromId(TEST_VM_ID); + result = "VMNAME"; + } + {googleProviderMock.getComputeServices().getVirtualMachineSupport().getVirtualMachine("VMNAME"); + result = vm; + } + {support.getVolume(TEST_VOLUME_ID); + result = volume; + } + {googleComputeMock.instances().attachDisk(TEST_ACCOUNT_NO, TEST_DATACENTER, TEST_VM_ID, (AttachedDisk) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, "", TEST_DATACENTER); + result = true; + } + }; + + support.attach(TEST_VOLUME_ID, TEST_VM_ID, "0"); + } + + @Test + public void createVolume_shouldReturnNewVolumeId() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.disks().insert(TEST_ACCOUNT_NO, TEST_DATACENTER, (Disk) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationTarget(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, "", TEST_DATACENTER, false); + result = TEST_VOLUME_ID; + } + }; + + VolumeCreateOptions options = VolumeCreateOptions.getInstance(new Storage(2, Storage.GIGABYTE), "myNewDisk", "myNewDiskDescription"); + options.inDataCenter(TEST_DATACENTER); + + String volumeId = support.createVolume(options); + assertNotNull(volumeId); + assertTrue(volumeId.equals(TEST_VOLUME_ID)); + } + + @Test + public void detach_shouldResultInSuccessfulOperation() throws CloudException, InternalException, IOException { + final Volume volume = new Volume(); + volume.setTag("contentLink", "CONTENT_LINK"); + volume.setProviderDataCenterId(TEST_DATACENTER); + volume.setProviderVirtualMachineId(TEST_VM_ID); + volume.setDeviceId("1"); + + new NonStrictExpectations(DiskSupport.class) { + {googleProviderMock.getComputeServices().getVirtualMachineSupport().getVmNameFromId(TEST_VM_ID); + result = "VMNAME"; + } + {support.getVolume(TEST_VOLUME_ID); + result = volume; + } + {googleComputeMock.instances().detachDisk(TEST_ACCOUNT_NO, TEST_DATACENTER, TEST_VM_ID, volume.getDeviceId()).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, "", TEST_DATACENTER); + result = true; + } + }; + + support.detach(TEST_VOLUME_ID, false); + } + + @Test + public void getVolume_shouldReturnTheCorrectAttributes() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.disks().aggregatedList(TEST_ACCOUNT_NO).setFilter(anyString).execute(); + result = getTestDiskAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(TEST_DATACENTER); + result = TEST_REGION; + } + {googleComputeMock.instances().list(TEST_ACCOUNT_NO, TEST_DATACENTER).execute(); + result = getTestInstanceList(); + } + }; + + Volume volume = support.getVolume(TEST_VOLUME_ID); + assertNotNull(volume); + assertTrue(volume.getProviderVolumeId().equals(TEST_VOLUME_ID)); + assertTrue(volume.getName().equals(TEST_VOLUME_ID)); + assertTrue(volume.getMediaLink().equals("SELFLINK")); + assertTrue(volume.getDescription().equals("DESCRIPTION")); + assertTrue(volume.getProviderRegionId().equals(TEST_REGION)); + + DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); + DateTime dt = DateTime.parse("2016-05-23T09:57:34.123+00:00", fmt); + assertTrue(volume.getCreationTimestamp() == dt.toDate().getTime()); + assertTrue(volume.getProviderDataCenterId().equals(TEST_DATACENTER)); + assertTrue(volume.getCurrentState().equals(VolumeState.AVAILABLE)); + assertTrue(volume.getType().equals(VolumeType.HDD)); + assertTrue(volume.getFormat().equals(VolumeFormat.BLOCK)); + assertTrue(volume.getSizeInGigabytes() == 2); + assertTrue(volume.getTag("contentLink").equals("SELFLINK")); + assertTrue(volume.getDeviceId().equals("1")); + assertTrue(volume.getProviderVirtualMachineId().equals(TEST_VM_ID)); + } + + @Test + public void listVolumeStatus_shouldReturnCorrectStatus() throws CloudException, InternalException, IOException { + new NonStrictExpectations(){ + {googleComputeMock.disks().aggregatedList(TEST_ACCOUNT_NO).execute(); + result = getTestDiskAggregatedList(); + } + }; + + Iterable list = support.listVolumeStatus(); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 2); + ResourceStatus rs = resultAsList.get(0); + assertTrue(rs.getResourceStatus().equals(VolumeState.AVAILABLE)); + rs = resultAsList.get(1); + assertTrue(rs.getResourceStatus().equals(VolumeState.ERROR)); + } + + @Test + public void listVolumes_shouldReturnAllAvailableVolumes() throws CloudException, InternalException, IOException { + new NonStrictExpectations(){ + {googleComputeMock.disks().aggregatedList(TEST_ACCOUNT_NO).execute(); + result = getTestDiskAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(TEST_DATACENTER); + result = TEST_REGION; + } + {googleComputeMock.instances().list(TEST_ACCOUNT_NO, TEST_DATACENTER).execute(); + result = getTestInstanceList(); + } + }; + + Iterable list = support.listVolumes(); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 2); + } + + @Test + public void listVolumesWithVMFilter_shouldReturnNoVolumes() throws CloudException, InternalException, IOException { + new NonStrictExpectations(){ + {googleComputeMock.disks().aggregatedList(TEST_ACCOUNT_NO).execute(); + result = getTestDiskAggregatedList(); + } + {googleProviderMock.getDataCenterServices().getRegionFromZone(TEST_DATACENTER); + result = TEST_REGION; + } + {googleComputeMock.instances().list(TEST_ACCOUNT_NO, TEST_DATACENTER).execute(); + result = getTestInstanceList(); + } + }; + + VolumeFilterOptions options = VolumeFilterOptions.getInstance().attachedTo("myFakeVMId"); + + Iterable list = support.listVolumes(options); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 0); + } + + @Test + public void remove_shouldResultInSuccessfulOperation() throws CloudException, InternalException, IOException { + final Volume volume = new Volume(); + volume.setProviderVolumeId(TEST_VOLUME_ID); + volume.setProviderDataCenterId(TEST_DATACENTER); + + new NonStrictExpectations(DiskSupport.class) { + {support.getVolume(TEST_VOLUME_ID); + result = volume; + } + {googleComputeMock.disks().delete(TEST_ACCOUNT_NO, TEST_DATACENTER, TEST_VOLUME_ID).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, "", TEST_DATACENTER); + result = true; + } + }; + + support.remove(TEST_VOLUME_ID); + } +} \ No newline at end of file From f9dd5da1aa42747e860d98e6be2812c897dcdeb9 Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Wed, 25 May 2016 14:22:15 +0100 Subject: [PATCH 06/15] image support tests --- .../google/compute/server/ImageSupport.java | 8 +- .../dasein/cloud/google/GoogleTestBase.java | 2 + .../dasein/cloud/google/ImageSupportTest.java | 362 ++++++++++++++++++ 3 files changed, 369 insertions(+), 3 deletions(-) create mode 100644 src/test/java/org/dasein/cloud/google/ImageSupportTest.java diff --git a/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java b/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java index 805e0d2..010f133 100644 --- a/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java +++ b/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java @@ -197,8 +197,10 @@ public boolean isSubscribed() throws CloudException, InternalException { if(imgList.getItems() != null){ for(Image img : imgList.getItems()){ MachineImage image = toMachineImage(img); - if(image != null && options.matches(image)) { - images.add(image); + if(image != null) { + if (options == null || options.matches(image)) { + images.add(image); + } } } } @@ -507,7 +509,7 @@ else if(imageStatus.equalsIgnoreCase("PENDING")) { @Override public MachineImage capture(@Nonnull ImageCreateOptions options, @Nullable AsynchronousTask task) throws CloudException, InternalException { Compute gce = provider.getGoogleCompute(); - ServerSupport server = new ServerSupport(provider); + ServerSupport server = provider.getComputeServices().getVirtualMachineSupport(); Image imageContent = new Image(); try { diff --git a/src/test/java/org/dasein/cloud/google/GoogleTestBase.java b/src/test/java/org/dasein/cloud/google/GoogleTestBase.java index c00c413..dc5988a 100644 --- a/src/test/java/org/dasein/cloud/google/GoogleTestBase.java +++ b/src/test/java/org/dasein/cloud/google/GoogleTestBase.java @@ -42,6 +42,7 @@ public class GoogleTestBase { @Mocked GoogleMethod googleMethodMock; + final String CLOUD_NAME = "GCE"; final String TEST_ACCOUNT_NO = "12323232323"; final String TEST_REGION = "us-central1"; final String TEST_DATACENTER = "us-central1-a"; @@ -54,6 +55,7 @@ public void setUp() throws CloudException, InternalException { { providerContextMock.getAccountNumber(); result = TEST_ACCOUNT_NO; } { providerContextMock.getRegionId(); result = TEST_REGION; } { googleProviderMock.getGoogleCompute(); result = googleComputeMock; } + { googleProviderMock.getCloudName(); result = CLOUD_NAME; } }; } } diff --git a/src/test/java/org/dasein/cloud/google/ImageSupportTest.java b/src/test/java/org/dasein/cloud/google/ImageSupportTest.java new file mode 100644 index 0000000..1a1a345 --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/ImageSupportTest.java @@ -0,0 +1,362 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.model.Disk; +import com.google.api.services.compute.model.Image; +import com.google.api.services.compute.model.ImageList; +import com.google.api.services.compute.model.Operation; +import mockit.Mocked; +import mockit.NonStrictExpectations; +import org.apache.commons.collections.IteratorUtils; +import org.dasein.cloud.AsynchronousTask; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.OperationNotSupportedException; +import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.VisibleScope; +import org.dasein.cloud.compute.Architecture; +import org.dasein.cloud.compute.ImageClass; +import org.dasein.cloud.compute.ImageCreateOptions; +import org.dasein.cloud.compute.ImageFilterOptions; +import org.dasein.cloud.compute.MachineImage; +import org.dasein.cloud.compute.MachineImageFormat; +import org.dasein.cloud.compute.MachineImageState; +import org.dasein.cloud.compute.Platform; +import org.dasein.cloud.compute.VirtualMachine; +import org.dasein.cloud.google.compute.server.ImageSupport; +import org.dasein.cloud.google.compute.server.ServerSupport; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * User: daniellemayne + * Date: 23/05/2016 + * Time: 14:24 + */ +public class ImageSupportTest extends GoogleTestBase { + private ImageSupport support = null; + + @Mocked + ServerSupport serverSupport; + + final String TEST_IMAGE_ID = "MYPROJ_TESTIMAGE"; + + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + support = new ImageSupport(googleProviderMock); + } + + private ImageList getTestImageList() { + Image image = new Image(); + image.setStatus("READY"); + image.setName("TESTIMAGE"); + image.setDescription("CENTOS"); + image.setSelfLink("/projects/12323232323/global/images/TESTIMAGE"); + image.set("diskSizeGb", new Long(2)); + + Image image2 = new Image(); + image2.setStatus("PENDING"); + image2.setName("TESTIMAGE2"); + image2.setDescription("windows"); + image2.setSelfLink("/projects/MYPROJ/global/images/TESTIMAGE2"); + image2.set("diskSizeGb", new Long(4)); + + List list = new ArrayList<>(); + list.add(image); + list.add(image2); + + ImageList il = new ImageList(); + il.setItems(list); + + return il; + } + + private ImageList getTestPublicImageList() { + Image image = new Image(); + image.setStatus("READY"); + image.setName("TESTPUBLICIMAGE"); + image.setDescription("CENTOS"); + image.setSelfLink("/projects/centos-cloud/global/images/TESTCENTOSIMAGE"); + image.set("diskSizeGb", new Long(2)); + + List list = new ArrayList<>(); + list.add(image); + + ImageList il = new ImageList(); + il.setItems(list); + + return il; + } + + @Test(expected = OperationNotSupportedException.class) + public void addImageShare_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.addImageShare(TEST_IMAGE_ID, TEST_ACCOUNT_NO); + } + + @Test(expected = OperationNotSupportedException.class) + public void addPublicShare_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.addPublicShare(TEST_IMAGE_ID); + } + + @Test(expected = OperationNotSupportedException.class) + public void bundleVirtualMachine_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.bundleVirtualMachine(TEST_VM_ID, MachineImageFormat.OVF, "", ""); + } + + @Test(expected = OperationNotSupportedException.class) + public void bundleVirtualMachineAsync_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.bundleVirtualMachineAsync(TEST_VM_ID, MachineImageFormat.OVF, "", "", new AsynchronousTask()); + } + + @Test + public void getImage_shouldReturnCorrectAttributes() throws CloudException, InternalException, IOException { + final Image image = new Image(); + image.setStatus("READY"); + image.setName("TESTIMAGE"); + image.setDescription("CENTOS"); + image.setSelfLink("/projects/MYPROJ/global/images/TESTIMAGE"); + image.set("diskSizeGb", new Long(2)); + + new NonStrictExpectations() { + {googleComputeMock.images().get("MYPROJ", "TESTIMAGE").execute(); + result = image; + } + }; + + MachineImage img = support.getImage(TEST_IMAGE_ID); + assertNotNull(img); + assertTrue(img.getName().equals("TESTIMAGE")); + assertTrue(img.getDescription().equals("CENTOS")); + assertTrue(img.getProviderMachineImageId().equals(TEST_IMAGE_ID)); + assertTrue(img.getProviderOwnerId().equals("GCE")); + assertTrue(img.getProviderRegionId().equals("")); + assertTrue(img.getImageClass().equals(ImageClass.MACHINE)); + assertTrue(img.getCurrentState().equals(MachineImageState.ACTIVE)); + assertTrue(img.getArchitecture().equals(Architecture.I64)); + assertTrue(img.getPlatform().equals(Platform.CENT_OS)); + assertTrue(img.getStorageFormat().equals(MachineImageFormat.RAW)); + assertTrue(img.getVisibleScope().equals(VisibleScope.ACCOUNT_GLOBAL)); + assertTrue(img.isPublic()); + assertTrue(img.getTag("contentLink").toString().equals("/projects/MYPROJ/global/images/TESTIMAGE")); + assertTrue(img.getTag("project").toString().equals("MYPROJ")); + assertTrue(img.getMinimumDiskSizeGb() == 2); + } + + @Test + public void listImageStatus_shouldReturnCorrectStatusOfEachImage() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.images().list(TEST_ACCOUNT_NO).execute(); + result = getTestImageList(); + } + }; + + Iterable list = support.listImageStatus(ImageClass.MACHINE); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 2); + ResourceStatus status = resultAsList.get(0); + assertTrue(status.getResourceStatus().equals(MachineImageState.ACTIVE)); + status = resultAsList.get(1); + assertTrue(status.getResourceStatus().equals(MachineImageState.PENDING)); + } + + @Test + public void listImagesNullFilter_shouldReturnAllAvailableImages() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.images().list(TEST_ACCOUNT_NO).execute(); + result = getTestImageList(); + } + }; + + Iterable list = support.listImages((ImageFilterOptions) null); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 2); + } + + @Test + public void listImagesPlatformFilter_shouldReturnOnlyCentosImage() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.images().list(TEST_ACCOUNT_NO).execute(); + result = getTestImageList(); + } + }; + + Iterable list = support.listImages(ImageFilterOptions.getInstance().onPlatform(Platform.CENT_OS)); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + } + + @Test + public void listMachineImages_shouldReturnAllAvailableImages() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.images().list(TEST_ACCOUNT_NO).execute(); + result = getTestImageList(); + } + }; + + Iterable list = support.listMachineImages(); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 2); + } + + @Test + public void listMachineImagesOwnedBy_shouldReturnOnlyPrivateImage() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.images().list(TEST_ACCOUNT_NO).execute(); + result = getTestImageList(); + } + }; + + Iterable list = support.listMachineImagesOwnedBy(TEST_ACCOUNT_NO); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + MachineImage img = resultAsList.get(0); + assertTrue(img.getTag("project").toString().equals(TEST_ACCOUNT_NO)); + } + + @Test + public void listShares_shouldReturnEmptyList() throws CloudException, InternalException { + Iterable list = support.listShares(TEST_IMAGE_ID); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.isEmpty()); + } + + @Test(expected = OperationNotSupportedException.class) + public void registerImageBundle_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.registerImageBundle(ImageCreateOptions.getInstance(new VirtualMachine(), "NAME", "DESCRIPTION", false)); + } + + @Test + public void remove_shouldResultInSuccessfulOperation() throws CloudException, InternalException, IOException { + final Image image = new Image(); + image.setStatus("READY"); + image.setName("TESTIMAGE"); + image.setDescription("CENTOS"); + image.setSelfLink("/projects/MYPROJ/global/images/TESTIMAGE"); + image.set("diskSizeGb", new Long(2)); + + new NonStrictExpectations() { + {googleComputeMock.images().get("MYPROJ", "TESTIMAGE").execute(); + result = image; + } + {googleComputeMock.images().delete(TEST_ACCOUNT_NO, "TESTIMAGE").execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, "", ""); + result = true; + } + }; + + support.remove(TEST_IMAGE_ID); + } + + @Test + public void searchImagesNoFiltering_shouldReturnPublicAndPrivateImages() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.images().list(TEST_ACCOUNT_NO).execute(); + result = getTestImageList(); + } + {googleComputeMock.images().list("centos-cloud").execute(); + result = getTestPublicImageList(); + } + }; + + Iterable list = support.searchImages(null, null, Platform.CENT_OS, null); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 2); + } + + @Test + public void searchPublicImagesRegexFilter_shouldReturnEmptyList() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.images().list("centos-cloud").execute(); + result = getTestPublicImageList(); + } + }; + + Iterable list = support.searchPublicImages(ImageFilterOptions.getInstance("myimage").onPlatform(Platform.CENT_OS)); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.isEmpty()); + } + + @Test + public void capture_shouldReturnNewImage() throws CloudException, InternalException, IOException { + final VirtualMachine vm = new VirtualMachine(); + vm.setProviderVirtualMachineId(TEST_VM_ID); + vm.setProviderDataCenterId(TEST_DATACENTER); + vm.setProviderVolumeIds("TEST_VOLUME"); + + final Disk disk = new Disk(); + disk.setName("TEST_VOLUME"); + disk.setDescription("DESCRIPTION"); + disk.setSelfLink("SELFLINK"); + disk.setZone(TEST_DATACENTER); + disk.setCreationTimestamp("2016-05-23T09:57:34.123+00:00"); //yyyy-MM-dd'T'HH:mm:ss.SSSZZ + disk.setStatus("READY"); + disk.setSizeGb(2l); + disk.setSourceImage("SOURCEIMAGE_CENTOS"); + + new NonStrictExpectations(ImageSupport.class) { + {googleProviderMock.getComputeServices().getVirtualMachineSupport(); + result = serverSupport; + } + {serverSupport.getVirtualMachine(anyString); + result = vm; + } + {serverSupport.terminateVm(anyString); + result = null; + } + {googleComputeMock.disks().get(TEST_ACCOUNT_NO, TEST_DATACENTER, "TEST_VOLUME").execute(); + result = disk; + } + {googleComputeMock.images().insert(TEST_ACCOUNT_NO, (Image) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, "", ""); + result = true; + } + {googleComputeMock.disks().delete(TEST_ACCOUNT_NO, TEST_DATACENTER, "TEST_VOLUME").execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, "", TEST_DATACENTER); + result = true; + } + {support.getImage(anyString); + result = null; + } + }; + + support.capture(ImageCreateOptions.getInstance(vm, "NEWIMAGE", "NEWDESCRIPTION", false), null); + } +} From 8b68e1d29bc48291c9cf8b0cbed13a293f98eb99 Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Thu, 26 May 2016 15:51:49 +0100 Subject: [PATCH 07/15] snapshot tests --- .../cloud/google/SnapshotSupportTest.java | 260 ++++++++++++++++++ 1 file changed, 260 insertions(+) create mode 100644 src/test/java/org/dasein/cloud/google/SnapshotSupportTest.java diff --git a/src/test/java/org/dasein/cloud/google/SnapshotSupportTest.java b/src/test/java/org/dasein/cloud/google/SnapshotSupportTest.java new file mode 100644 index 0000000..65309c1 --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/SnapshotSupportTest.java @@ -0,0 +1,260 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.model.Operation; +import com.google.api.services.compute.model.Snapshot; +import com.google.api.services.compute.model.SnapshotList; +import mockit.NonStrictExpectations; +import org.apache.commons.collections.IteratorUtils; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.OperationNotSupportedException; +import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.Tag; +import org.dasein.cloud.compute.SnapshotCreateOptions; +import org.dasein.cloud.compute.SnapshotFilterOptions; +import org.dasein.cloud.compute.SnapshotState; +import org.dasein.cloud.compute.Volume; +import org.dasein.cloud.google.compute.server.SnapshotSupport; +import org.joda.time.DateTime; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.*; + +/** + * User: daniellemayne + * Date: 25/05/2016 + * Time: 14:23 + */ +public class SnapshotSupportTest extends GoogleTestBase { + private SnapshotSupport support = null; + final String TEST_SNAPSHOT_ID = "TESTSNAPSHOT_112233"; + final String TEST_VOLUME_ID = "TESTVOLUME_112233"; + + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + support = new SnapshotSupport(googleProviderMock); + } + + private SnapshotList getTestSnapshotList() { + Snapshot snapshot = new Snapshot(); + snapshot.setName(TEST_SNAPSHOT_ID); + snapshot.setDescription("SNAPSHOT_DESCRIPTION"); + snapshot.setStatus("READY"); + snapshot.setDiskSizeGb(new Long(3)); + snapshot.setCreationTimestamp("2016-05-25T14:57:34.123+00:00"); //yyyy-MM-dd'T'HH:mm:ss.SSSZZ + snapshot.setSourceDisk("/disks/"+TEST_VOLUME_ID); + + Snapshot snapshot2 = new Snapshot(); + snapshot2.setName("SNAPSHOT2"); + snapshot2.setDescription("SNAPSHOT2_DESCRIPTION"); + snapshot2.setStatus("DELETING"); + snapshot2.setDiskSizeGb(new Long(2)); + snapshot2.setCreationTimestamp("2016-05-25T15:07:34.123+00:00"); //yyyy-MM-dd'T'HH:mm:ss.SSSZZ + snapshot2.setSourceDisk("/disks/"+TEST_VOLUME_ID+"2"); + + List list = new ArrayList<>(); + list.add(snapshot); + list.add(snapshot2); + + SnapshotList sl = new SnapshotList(); + sl.setItems(list); + return sl; + } + + @Test(expected = OperationNotSupportedException.class) + public void addSnapshotShare_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.addSnapshotShare(TEST_SNAPSHOT_ID, TEST_ACCOUNT_NO); + } + + @Test(expected = OperationNotSupportedException.class) + public void addPublicShare_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.addPublicShare(TEST_SNAPSHOT_ID); + } + + @Test + public void createSnapshot_shouldReturnNewSnapshotName() throws CloudException, InternalException, IOException { + final Volume volume = new Volume(); + volume.setProviderDataCenterId(TEST_DATACENTER); + + new NonStrictExpectations() { + {googleProviderMock.getComputeServices().getVolumeSupport().getVolume(anyString); + result = volume; + } + {googleComputeMock.disks().createSnapshot(TEST_ACCOUNT_NO, TEST_DATACENTER, TEST_VOLUME_ID, (Snapshot) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, "", TEST_DATACENTER); + result = true; + } + {googleComputeMock.snapshots().list(TEST_ACCOUNT_NO).setFilter("name eq "+TEST_SNAPSHOT_ID).execute(); + result = getTestSnapshotList(); + } + }; + + SnapshotCreateOptions options = SnapshotCreateOptions.getInstanceForCreate(TEST_VOLUME_ID, TEST_SNAPSHOT_ID, "TESTDESCRIPTION"); + + String newSnapshotID = support.createSnapshot(options); + assertTrue(newSnapshotID.equals(TEST_SNAPSHOT_ID)); + } + + @Test + public void getSnapshot_shouldReturnCorrectAttributes() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.snapshots().get(TEST_ACCOUNT_NO, "SNAPSHOT2").execute(); + result = getTestSnapshotList().getItems().get(1); + } + }; + + org.dasein.cloud.compute.Snapshot snapshot = support.getSnapshot("SNAPSHOT2"); + assertTrue(snapshot.getName().equals("SNAPSHOT2")); + assertTrue(snapshot.getProviderSnapshotId().equals("SNAPSHOT2")); + assertTrue(snapshot.getDescription().equals("SNAPSHOT2_DESCRIPTION")); + assertTrue(snapshot.getOwner().equals(TEST_ACCOUNT_NO)); + assertTrue(snapshot.getCurrentState().equals(SnapshotState.DELETED)); + assertTrue(snapshot.getSizeInGb() == 2); + + DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); + DateTime dt = DateTime.parse("2016-05-25T15:07:34.123+00:00", fmt); + assertTrue(snapshot.getSnapshotTimestamp() == dt.toDate().getTime()); + assertTrue(snapshot.getVolumeId().equals(TEST_VOLUME_ID+"2")); + } + + @Test + public void listShares_shouldReturnEmptyList() throws CloudException, InternalException { + Iterable shares = support.listShares(TEST_SNAPSHOT_ID); + List resultAsList = IteratorUtils.toList(shares.iterator()); + assertTrue(resultAsList.isEmpty()); + } + + @Test + public void listSnapshotStatus_shouldReturnCorrectStatusForEachSnapshot() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.snapshots().list(TEST_ACCOUNT_NO).execute(); + result = getTestSnapshotList(); + } + }; + Iterable list = support.listSnapshotStatus(); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 2); + ResourceStatus status = resultAsList.get(0); + assertTrue(status.getResourceStatus().equals(SnapshotState.AVAILABLE)); + status = resultAsList.get(1); + assertTrue(status.getResourceStatus().equals(SnapshotState.DELETED)); + } + + @Test + public void listSnapshots_shouldReturnAllAvailableSnapshots() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.snapshots().list(TEST_ACCOUNT_NO).execute(); + result = getTestSnapshotList(); + } + }; + + Iterable list = support.listSnapshots(); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 2); + } + + @Test + public void listSnapshotsWithNameFilter_shouldOnlyReturnFilteredSnapshot() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.snapshots().list(TEST_ACCOUNT_NO).execute(); + result = getTestSnapshotList(); + } + }; + + Iterable list = support.listSnapshots(SnapshotFilterOptions.getInstance("SNAPSHOT2")); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + assertTrue(resultAsList.get(0).getName().equals("SNAPSHOT2")); + } + + @Test + public void remove_shouldResultInSuccessfulOperation() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.snapshots().delete(TEST_ACCOUNT_NO, TEST_SNAPSHOT_ID).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, "", ""); + result = true; + } + }; + + support.remove(TEST_SNAPSHOT_ID); + } + + @Test(expected = OperationNotSupportedException.class) + public void removeSnapshotShare_shouldThrowOperationNotSupportedException() throws CloudException, InternalException, IOException { + support.removeSnapshotShare(TEST_SNAPSHOT_ID, TEST_ACCOUNT_NO); + } + + @Test(expected = OperationNotSupportedException.class) + public void removePublicShare_shouldThrowOperationNotSupportedException() throws CloudException, InternalException, IOException { + support.removePublicShare(TEST_SNAPSHOT_ID); + } + + @Test(expected = OperationNotSupportedException.class) + public void removeTagsFromSingleSnapshot_shouldThrowOperationNotSupportedException() throws CloudException, InternalException, IOException { + support.removeTags(TEST_SNAPSHOT_ID, new Tag()); + } + + @Test(expected = OperationNotSupportedException.class) + public void removeTagsFromMultipleSnapshots_shouldThrowOperationNotSupportedException() throws CloudException, InternalException, IOException { + support.removeTags(new String[]{TEST_SNAPSHOT_ID, "anothersnapshotid"}, new Tag()); + } + + @Test + public void searchSnapshotsWithNameFilter_shouldOnlyReturnFilteredSnapshot() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.snapshots().list(TEST_ACCOUNT_NO).execute(); + result = getTestSnapshotList(); + } + }; + + Iterable list = support.searchSnapshots(SnapshotFilterOptions.getInstance("SNAPSHOT2")); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + assertTrue(resultAsList.get(0).getName().equals("SNAPSHOT2")); + } + + @Test(expected = OperationNotSupportedException.class) + public void updateTagsFromSingleSnapshot_shouldThrowOperationNotSupportedException() throws CloudException, InternalException, IOException { + support.updateTags(TEST_SNAPSHOT_ID, new Tag()); + } + + @Test(expected = OperationNotSupportedException.class) + public void updateTagsFromMultipleSnapshots_shouldThrowOperationNotSupportedException() throws CloudException, InternalException, IOException { + support.updateTags(new String[]{TEST_SNAPSHOT_ID, "anothersnapshotid"}, new Tag()); + } +} From 4aafe437058df2683dd132acfa7e5bb3043802bd Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Thu, 26 May 2016 15:52:16 +0100 Subject: [PATCH 08/15] converged infrastructure tests --- .../dasein/cloud/ci/ReplicaPoolSupport.java | 6 +- .../dasein/cloud/google/DatacentersTest.java | 1 + .../cloud/google/ReplicapoolSupportTest.java | 209 ++++++++++++++++++ 3 files changed, 212 insertions(+), 4 deletions(-) create mode 100644 src/test/java/org/dasein/cloud/google/ReplicapoolSupportTest.java diff --git a/src/main/java/org/dasein/cloud/ci/ReplicaPoolSupport.java b/src/main/java/org/dasein/cloud/ci/ReplicaPoolSupport.java index fbe22a1..e8e2e3f 100644 --- a/src/main/java/org/dasein/cloud/ci/ReplicaPoolSupport.java +++ b/src/main/java/org/dasein/cloud/ci/ReplicaPoolSupport.java @@ -103,7 +103,7 @@ public Iterable listConvergedInfrastructures(ConvergedI ConvergedInfrastructureState.READY, System.currentTimeMillis(), dataCenterId, regionName, null); ci.setTag("selfLink", item.getSelfLink()); ci.setTag("instanceGroupLink", item.getGroup()); - loadResources(ci, dataCenterId); + loadResources(item, ci, dataCenterId); if (options != null) { if (options.matches(ci)) { convergedInfrastrutures.add(ci); @@ -125,14 +125,12 @@ public Iterable listConvergedInfrastructures(ConvergedI return convergedInfrastrutures; } - private void loadResources(ConvergedInfrastructure ci, String datacenterId) throws InternalException, CloudException { + private void loadResources(InstanceGroupManager pool, ConvergedInfrastructure ci, String datacenterId) throws InternalException, CloudException { APITrace.begin(getProvider(), "GoogleConvergedInfrastructure.loadResources"); List list = new ArrayList<>(); try { - Replicapool rp = provider.getGoogleReplicapool(); Compute gce = provider.getGoogleCompute(); - InstanceGroupManager pool = rp.instanceGroupManagers().get(provider.getContext().getAccountNumber(), datacenterId, ci.getProviderCIId()).execute(); String baseInstanceName = pool.getBaseInstanceName(); InstanceList result = gce.instances().list(provider.getContext().getAccountNumber(), datacenterId).execute(); for (Instance instance : result.getItems()) { diff --git a/src/test/java/org/dasein/cloud/google/DatacentersTest.java b/src/test/java/org/dasein/cloud/google/DatacentersTest.java index d153555..f6b5e3b 100644 --- a/src/test/java/org/dasein/cloud/google/DatacentersTest.java +++ b/src/test/java/org/dasein/cloud/google/DatacentersTest.java @@ -48,6 +48,7 @@ @RunWith(JUnit4.class) public class DatacentersTest extends GoogleTestBase{ private DataCenters dc = null; + @Before public void setUp() throws CloudException, InternalException { super.setUp(); diff --git a/src/test/java/org/dasein/cloud/google/ReplicapoolSupportTest.java b/src/test/java/org/dasein/cloud/google/ReplicapoolSupportTest.java new file mode 100644 index 0000000..a8cf2b5 --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/ReplicapoolSupportTest.java @@ -0,0 +1,209 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.model.Instance; +import com.google.api.services.compute.model.InstanceList; +import com.google.api.services.compute.model.NetworkInterface; +import com.google.api.services.replicapool.Replicapool; +import com.google.api.services.replicapool.model.InstanceGroupManager; +import com.google.api.services.replicapool.model.InstanceGroupManagerList; +import com.google.api.services.replicapool.model.Operation; +import mockit.Mocked; +import mockit.NonStrictExpectations; +import org.apache.commons.collections.IteratorUtils; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.OperationNotSupportedException; +import org.dasein.cloud.ResourceType; +import org.dasein.cloud.ci.ConvergedInfrastructure; +import org.dasein.cloud.ci.ConvergedInfrastructureProvisionOptions; +import org.dasein.cloud.ci.ConvergedInfrastructureResource; +import org.dasein.cloud.ci.ConvergedInfrastructureState; +import org.dasein.cloud.ci.ReplicapoolSupport; +import org.dasein.cloud.dc.DataCenter; +import org.dasein.cloud.dc.Region; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * User: daniellemayne + * Date: 26/05/2016 + * Time: 10:40 + */ +public class ReplicapoolSupportTest extends GoogleTestBase { + private ReplicapoolSupport support = null; + + final String TEST_REPLICAPOOL = "TEST_REPLICAPOOL"; + + @Mocked + Replicapool rp; + + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + support = new ReplicapoolSupport(googleProviderMock); + + new NonStrictExpectations(){ + {googleProviderMock.getGoogleReplicapool(); + result = rp; + } + }; + } + + private InstanceGroupManagerList getTestInstanceGroupManagerList() { + InstanceGroupManager igm = new InstanceGroupManager(); + igm.setName(TEST_REPLICAPOOL); + igm.setId(new BigInteger("112233")); + igm.setDescription("DESCRIPTION"); + igm.setSelfLink("SELFLINK"); + igm.setGroup("GROUP"); + igm.setBaseInstanceName("BASEINSTANCE"); + + List list = new ArrayList<>(); + list.add(igm); + + InstanceGroupManagerList igml = new InstanceGroupManagerList(); + igml.setItems(list); + return igml; + } + + private InstanceList getTestInstanceList() { + Instance instance = new Instance(); + instance.setName("BASEINSTANCE-"+TEST_VM_ID); + + NetworkInterface net = new NetworkInterface(); + net.setNetwork("NETWORK"); + List netList = new ArrayList<>(); + netList.add(net); + instance.setNetworkInterfaces(netList); + + List instanceList = new ArrayList<>(); + instanceList.add(instance); + + InstanceList il = new InstanceList(); + il.setItems(instanceList); + return il; + } + + @Test + public void listConvergedInfrastructuresNoFilter_shouldReturnAllAvailableCIs() throws CloudException, InternalException, IOException { + final List regions = new ArrayList<>(); + Region region = new Region(); + region.setProviderRegionId(TEST_REGION); + regions.add(region); + + final List dataCenters = new ArrayList<>(); + DataCenter dc = new DataCenter(TEST_DATACENTER, TEST_REGION, TEST_REGION, true, true); + dataCenters.add(dc); + + new NonStrictExpectations() { + {googleProviderMock.getDataCenterServices().listRegions(); + result = regions; + } + {googleProviderMock.getDataCenterServices().listDataCenters(TEST_REGION); + result = dataCenters; + } + {rp.instanceGroupManagers().list(TEST_ACCOUNT_NO, TEST_DATACENTER).execute(); + result = getTestInstanceGroupManagerList(); + } + {googleComputeMock.instances().list(TEST_ACCOUNT_NO, TEST_DATACENTER).execute(); + result = getTestInstanceList(); + } + }; + + Iterable list = support.listConvergedInfrastructures(null); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + + ConvergedInfrastructure ci = resultAsList.get(0); + assertTrue(ci.getName().equals(TEST_REPLICAPOOL)); + assertTrue(ci.getProviderCIId().equals(TEST_REPLICAPOOL)); + assertTrue(ci.getDescription().equals("DESCRIPTION")); + assertTrue(ci.getCiState().equals(ConvergedInfrastructureState.READY)); + assertTrue(ci.getProviderRegionId().equals(TEST_REGION)); + assertTrue(ci.getProviderDatacenterId().equals(TEST_DATACENTER)); + List cirList = ci.getResources(); + assertNotNull(cirList); + assertTrue(cirList.size() == 2); + ConvergedInfrastructureResource r = cirList.get(0); + assertTrue(r.getResourceId().equals("BASEINSTANCE-"+TEST_VM_ID)); + assertTrue(r.getResourceType().equals(ResourceType.VIRTUAL_MACHINE)); + r = cirList.get(1); + assertTrue(r.getResourceId().equals("NETWORK")); + assertTrue(r.getResourceType().equals(ResourceType.VLAN)); + + assertTrue(ci.getTags().size() == 2); + assertTrue(ci.getTag("selfLink").toString().equals("SELFLINK")); + assertTrue(ci.getTag("instanceGroupLink").toString().equals("GROUP")); + } + + @Test + public void provision_shouldReturnNewConvergedInfrastructure() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {rp.instanceGroupManagers().insert(TEST_ACCOUNT_NO, TEST_DATACENTER, 2, (InstanceGroupManager) any).execute(); + result = new Operation(); + } + {googleMethodMock.getCIOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, TEST_REGION, TEST_DATACENTER); + result = true; + } + }; + + ConvergedInfrastructure ci = support.provision(ConvergedInfrastructureProvisionOptions.getInstance(TEST_REPLICAPOOL, "DESCRIPTION", null, null, "TESTTEMPLATE", null, false) + .inDatacenter(TEST_DATACENTER).withBaseName("BASENAME").withInstanceCount(2)); + assertNotNull(ci); + } + + @Test + public void terminate_shouldResultInSuccessfulOperation() throws CloudException, InternalException, IOException { + final ConvergedInfrastructure ci = ConvergedInfrastructure.getInstance(TEST_REPLICAPOOL, TEST_REPLICAPOOL, "DESCRIPTION", ConvergedInfrastructureState.READY, + System.currentTimeMillis(), TEST_DATACENTER, TEST_REGION, null); + final List ciList = new ArrayList<>(); + ciList.add(ci); + + new NonStrictExpectations(ReplicapoolSupport.class) { + {support.listConvergedInfrastructures(null); + result = ciList; + } + {rp.instanceGroupManagers().delete(TEST_ACCOUNT_NO, TEST_DATACENTER, TEST_REPLICAPOOL).execute(); + result = new Operation(); + } + {googleMethodMock.getCIOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, TEST_REGION, TEST_DATACENTER); + result = true; + } + }; + + support.terminate(TEST_REPLICAPOOL, "terminateTest"); + } + + @Test(expected = OperationNotSupportedException.class) + public void cancelDeployment_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.cancelDeployment(TEST_REPLICAPOOL, "TEST"); + } +} From 6ac94dc429d0a2c905a4bdc958a79a630ec8b50e Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Thu, 26 May 2016 16:24:31 +0100 Subject: [PATCH 09/15] topology unit test --- .../cloud/google/TopologySupportTest.java | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 src/test/java/org/dasein/cloud/google/TopologySupportTest.java diff --git a/src/test/java/org/dasein/cloud/google/TopologySupportTest.java b/src/test/java/org/dasein/cloud/google/TopologySupportTest.java new file mode 100644 index 0000000..7f712f5 --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/TopologySupportTest.java @@ -0,0 +1,96 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.Compute; +import com.google.api.services.compute.model.InstanceTemplate; +import com.google.api.services.compute.model.InstanceTemplateList; +import mockit.Mocked; +import mockit.NonStrictExpectations; +import org.apache.commons.collections.IteratorUtils; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.ci.GoogleTopologySupport; +import org.dasein.cloud.ci.Topology; +import org.dasein.cloud.ci.TopologyFilterOptions; +import org.junit.Before; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * User: daniellemayne + * Date: 26/05/2016 + * Time: 15:53 + */ +public class TopologySupportTest extends GoogleTestBase { + private GoogleTopologySupport support = null; + final String TEST_INSTANCE_TEMPLATE = "TEST_INSTANCE_TEMPLATE"; + + @Mocked + Compute.InstanceTemplates instanceTemplates; + + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + support = new GoogleTopologySupport(googleProviderMock); + new NonStrictExpectations(){ + {googleComputeMock.instanceTemplates(); + result = instanceTemplates; + } + }; + } + + private InstanceTemplateList getTestInstanceTemplateList() { + InstanceTemplate it = new InstanceTemplate(); + it.setName(TEST_INSTANCE_TEMPLATE); + it.setCreationTimestamp(TEST_INSTANCE_TEMPLATE); + it.setDescription("DESCRIPTION"); + + List list = new ArrayList<>(); + list.add(it); + InstanceTemplateList itl = new InstanceTemplateList(); + itl.setItems(list); + return itl; + } + + public void listTopologies_shouldReturnAllAvailableTopologies() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {instanceTemplates.list(TEST_ACCOUNT_NO).execute(); + result = getTestInstanceTemplateList(); + } + }; + + Iterable list = support.listTopologies(TopologyFilterOptions.getInstance()); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + Topology topology = resultAsList.get(0); + assertTrue(topology.getName().equals(TEST_INSTANCE_TEMPLATE)); + assertTrue(topology.getProviderRegionId().equals(TEST_REGION)); + assertTrue(topology.getDescription().equals("DESCRIPTION")); + assertTrue(topology.getProviderDataCenterId().equals(TEST_DATACENTER)); + assertTrue(topology.getProviderOwnerId(),equals(TEST_ACCOUNT_NO)); + } +} From be39e5cff0306cf02548baa27d4a44fc1797fade Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Thu, 2 Jun 2016 15:49:18 +0100 Subject: [PATCH 10/15] exceptions tests --- .../google/compute/server/DiskSupport.java | 14 +- .../google/compute/server/ImageSupport.java | 3 +- .../google/compute/server/ServerSupport.java | 4 +- .../dasein/cloud/google/DiskSupportTest.java | 45 +++++ .../dasein/cloud/google/ImageSupportTest.java | 19 ++ .../cloud/google/ReplicapoolSupportTest.java | 3 + .../cloud/google/ServerSupportTest.java | 166 ++++++++++++++++++ .../cloud/google/SnapshotSupportTest.java | 3 + .../cloud/google/TopologySupportTest.java | 12 +- 9 files changed, 260 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java b/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java index e9493ad..1825556 100644 --- a/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java +++ b/src/main/java/org/dasein/cloud/google/compute/server/DiskSupport.java @@ -118,7 +118,12 @@ public void attach(@Nonnull String volumeId, @Nonnull String toServerId, @Nonnul throw new GeneralCloudException("An error occurred while attaching the disk: " + ex.getMessage(), ex); } } catch (Exception ex) { - throw new GeneralCloudException("An error occurred while attaching the disk: " + ex.getMessage(), ex); + if (ex instanceof ResourceNotFoundException) { + throw ex; + } + else { + throw new GeneralCloudException("An error occurred while attaching the disk: " + ex.getMessage(), ex); + } } } finally{ @@ -193,7 +198,12 @@ public void detach(@Nonnull String volumeId, boolean force) throws InternalExcep throw new GeneralCloudException("An error occurred while detaching the volume: " + ex.getMessage(), ex); } } catch (Exception ex) { - throw new GeneralCloudException("An error occurred while detaching the volume", ex); + if (ex instanceof InvalidStateException) { + throw ex; + } + else { + throw new GeneralCloudException("An error occurred while detaching the volume", ex); + } } } finally{ diff --git a/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java b/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java index 010f133..7b668da 100644 --- a/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java +++ b/src/main/java/org/dasein/cloud/google/compute/server/ImageSupport.java @@ -33,7 +33,6 @@ import org.dasein.cloud.GeneralCloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; -import org.dasein.cloud.ResourceNotFoundException; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.Tag; import org.dasein.cloud.VisibleScope; @@ -252,7 +251,7 @@ public void remove(@Nonnull String providerImageId, boolean checkState) throws C try{ MachineImage image = getImage(providerImageId); if ((null == image) || (null == image.getCurrentState())) { - throw new ResourceNotFoundException("Image", providerImageId); + return; } if (image.getCurrentState().equals(MachineImageState.ACTIVE)) { job = gce.images().delete(provider.getContext().getAccountNumber(), image.getName()).execute(); diff --git a/src/main/java/org/dasein/cloud/google/compute/server/ServerSupport.java b/src/main/java/org/dasein/cloud/google/compute/server/ServerSupport.java index 6e9691f..f214e75 100644 --- a/src/main/java/org/dasein/cloud/google/compute/server/ServerSupport.java +++ b/src/main/java/org/dasein/cloud/google/compute/server/ServerSupport.java @@ -177,7 +177,7 @@ public String getPassword(@Nonnull String vmId) throws InternalException, CloudE if (vmId.contains("_")) { String[] parts = vmId.split("_"); - if (null == parts[0]) { + if ("".equals(parts[0])) { //todo //should we have a new exception for errors caused by user/client provided data? throw new InternalException("vmId cannot begin with '_'"); @@ -811,7 +811,7 @@ public void terminateVm(@Nonnull String vmId, String reason) throws InternalExce VirtualMachine vm = getVirtualMachine(vmId); if (null == vm) { - throw new ResourceNotFoundException("Virtual Machine", vmId); + return; } try { diff --git a/src/test/java/org/dasein/cloud/google/DiskSupportTest.java b/src/test/java/org/dasein/cloud/google/DiskSupportTest.java index 6978ea5..fcb07ad 100644 --- a/src/test/java/org/dasein/cloud/google/DiskSupportTest.java +++ b/src/test/java/org/dasein/cloud/google/DiskSupportTest.java @@ -30,6 +30,9 @@ import org.apache.commons.collections.IteratorUtils; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; +import org.dasein.cloud.InvalidStateException; +import org.dasein.cloud.OperationNotSupportedException; +import org.dasein.cloud.ResourceNotFoundException; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.compute.Volume; @@ -46,6 +49,8 @@ import org.joda.time.format.ISODateTimeFormat; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.IOException; import java.math.BigInteger; @@ -62,6 +67,7 @@ * Date: 19/05/2016 * Time: 12:41 */ +@RunWith(JUnit4.class) public class DiskSupportTest extends GoogleTestBase { private DiskSupport support = null; final String TEST_VOLUME_ID = "TEST_VOLUME"; @@ -155,6 +161,20 @@ public void attach_shouldHaveSuccessfulOperationComplete() throws CloudException support.attach(TEST_VOLUME_ID, TEST_VM_ID, "0"); } + @Test(expected = ResourceNotFoundException.class) + public void attach_shouldThrowExceptionIfVmNotFound() throws CloudException, InternalException { + new NonStrictExpectations() { + {googleProviderMock.getComputeServices().getVirtualMachineSupport().getVmNameFromId(TEST_VM_ID); + result = "VMNAME"; + } + {googleProviderMock.getComputeServices().getVirtualMachineSupport().getVirtualMachine(anyString); + result = null; + } + }; + + support.attach(TEST_VOLUME_ID, TEST_VM_ID, "0"); + } + @Test public void createVolume_shouldReturnNewVolumeId() throws CloudException, InternalException, IOException { new NonStrictExpectations() { @@ -174,6 +194,15 @@ public void createVolume_shouldReturnNewVolumeId() throws CloudException, Intern assertTrue(volumeId.equals(TEST_VOLUME_ID)); } + @Test(expected = OperationNotSupportedException.class) + public void createVolume_shouldThrowOperationNotSupportedExceptionIfVolumeFormatIsNFS() throws CloudException, InternalException { + VolumeCreateOptions options = VolumeCreateOptions.getInstance(new Storage(2, Storage.GIGABYTE), "myNewDisk", "myNewDiskDescription"); + options.inDataCenter(TEST_DATACENTER); + options.setFormat(VolumeFormat.NFS); + + support.createVolume(options); + } + @Test public void detach_shouldResultInSuccessfulOperation() throws CloudException, InternalException, IOException { final Volume volume = new Volume(); @@ -200,6 +229,22 @@ public void detach_shouldResultInSuccessfulOperation() throws CloudException, In support.detach(TEST_VOLUME_ID, false); } + @Test(expected = InvalidStateException.class) + public void detach_shouldThrowExceptionIfVolumeIsNotAttached() throws CloudException, InternalException { + final Volume volume = new Volume(); + volume.setTag("contentLink", "CONTENT_LINK"); + volume.setProviderDataCenterId(TEST_DATACENTER); + volume.setDeviceId("1"); + + new NonStrictExpectations(DiskSupport.class) { + {support.getVolume(TEST_VOLUME_ID); + result = volume; + } + }; + + support.detach(TEST_VOLUME_ID, true); + } + @Test public void getVolume_shouldReturnTheCorrectAttributes() throws CloudException, InternalException, IOException { new NonStrictExpectations() { diff --git a/src/test/java/org/dasein/cloud/google/ImageSupportTest.java b/src/test/java/org/dasein/cloud/google/ImageSupportTest.java index 1a1a345..6762e8e 100644 --- a/src/test/java/org/dasein/cloud/google/ImageSupportTest.java +++ b/src/test/java/org/dasein/cloud/google/ImageSupportTest.java @@ -45,6 +45,8 @@ import org.dasein.cloud.google.compute.server.ServerSupport; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.IOException; import java.util.ArrayList; @@ -58,6 +60,7 @@ * Date: 23/05/2016 * Time: 14:24 */ +@RunWith(JUnit4.class) public class ImageSupportTest extends GoogleTestBase { private ImageSupport support = null; @@ -168,6 +171,11 @@ public void getImage_shouldReturnCorrectAttributes() throws CloudException, Inte assertTrue(img.getMinimumDiskSizeGb() == 2); } + @Test(expected = InternalException.class) + public void getImage_shouldThrowExceptionIfImageIdDoesNotContain_() throws CloudException, InternalException { + support.getImage("IMAGE"); + } + @Test public void listImageStatus_shouldReturnCorrectStatusOfEachImage() throws CloudException, InternalException, IOException { new NonStrictExpectations() { @@ -280,6 +288,17 @@ public void remove_shouldResultInSuccessfulOperation() throws CloudException, In support.remove(TEST_IMAGE_ID); } + @Test + public void remove_shouldJustReturnIfImageNotFound() throws CloudException, InternalException { + new NonStrictExpectations(ImageSupport.class) { + {support.getImage(anyString); + result = null; + } + }; + + support.remove(TEST_IMAGE_ID); + } + @Test public void searchImagesNoFiltering_shouldReturnPublicAndPrivateImages() throws CloudException, InternalException, IOException { new NonStrictExpectations() { diff --git a/src/test/java/org/dasein/cloud/google/ReplicapoolSupportTest.java b/src/test/java/org/dasein/cloud/google/ReplicapoolSupportTest.java index a8cf2b5..49f854f 100644 --- a/src/test/java/org/dasein/cloud/google/ReplicapoolSupportTest.java +++ b/src/test/java/org/dasein/cloud/google/ReplicapoolSupportTest.java @@ -42,6 +42,8 @@ import org.dasein.cloud.dc.Region; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.IOException; import java.math.BigInteger; @@ -56,6 +58,7 @@ * Date: 26/05/2016 * Time: 10:40 */ +@RunWith(JUnit4.class) public class ReplicapoolSupportTest extends GoogleTestBase { private ReplicapoolSupport support = null; diff --git a/src/test/java/org/dasein/cloud/google/ServerSupportTest.java b/src/test/java/org/dasein/cloud/google/ServerSupportTest.java index 30f3ba7..d7837c0 100644 --- a/src/test/java/org/dasein/cloud/google/ServerSupportTest.java +++ b/src/test/java/org/dasein/cloud/google/ServerSupportTest.java @@ -35,6 +35,7 @@ import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; +import org.dasein.cloud.ResourceNotFoundException; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.VisibleScope; import org.dasein.cloud.compute.Architecture; @@ -221,6 +222,16 @@ public void getVmNameFromId() throws CloudException, InternalException { assertTrue(name.equals("name")); } + @Test(expected = InternalException.class) + public void getVmNameFromId_shouldThrowExceptionIfIdIsNull() throws CloudException, InternalException { + support.getVmNameFromId(null); + } + + @Test(expected = InternalException.class) + public void getVmNameFromId_shouldThrowExceptionIfIdStartsWith_() throws CloudException, InternalException { + support.getVmNameFromId("_BLAH"); + } + @Test public void getVmIdFromName() throws CloudException, InternalException { new NonStrictExpectations(ServerSupport.class) { @@ -232,6 +243,21 @@ public void getVmIdFromName() throws CloudException, InternalException { assertTrue(id.equals(TEST_VM_ID)); } + @Test(expected = InternalException.class) + public void getVmIdFromName_shouldThrowExceptionIfNameIsNull() throws CloudException, InternalException { + support.getVmIdFromName(null); + } + + @Test(expected = ResourceNotFoundException.class) + public void getVmIdFromName_shouldThrowExceptionIfVmNotFound() throws CloudException, InternalException { + new NonStrictExpectations(ServerSupport.class) { + {support.getVirtualMachine(anyString); + result = null; + } + }; + support.getVmIdFromName("name"); + } + @Test public void getConsoleOutput_shouldReturnOutputForCorrectVm() throws CloudException, InternalException, IOException { final SerialPortOutput output = new SerialPortOutput(); @@ -250,6 +276,15 @@ public void getConsoleOutput_shouldReturnOutputForCorrectVm() throws CloudExcept assertTrue(consoleOutput.equals("content")); } + @Test(expected = ResourceNotFoundException.class) + public void getConsoleOutput_shouldThrowExceptionIfVmNotFound() throws CloudException, InternalException { + new NonStrictExpectations(ServerSupport.class) { + {support.listVirtualMachines(); + result = Collections.emptyList(); + } + }; + support.getConsoleOutput(TEST_VM_ID); + } @Test public void getProduct_shouldReturnCorrectProduct() throws CloudException, InternalException, IOException { @@ -445,6 +480,122 @@ public void launch_shouldReturnVm() throws CloudException, InternalException, IO assertNotNull(vm); } + @Test(expected = ResourceNotFoundException.class) + public void launch_shouldThrowExceptionIfImageNotFound() throws CloudException, InternalException, IOException { + VMLaunchOptions options = VMLaunchOptions.getInstance(TEST_PRODUCT_ID, TEST_MACHINE_IMAGE_ID, TEST_HOST_NAME, TEST_FRIENDLY_NAME, TEST_DESCRIPTION); + options = options.inVlan(null, TEST_DATACENTER, TEST_VLAN_ID); + + final VLAN network = new VLAN(); + network.setTag("contentLink", "vlanContentLink"); + + final MachineImage image = MachineImage.getInstance("OWNER", TEST_REGION, TEST_MACHINE_IMAGE_ID, ImageClass.MACHINE, MachineImageState.ACTIVE, + "IMAGE_NAME", "IMAGE_DESCRIPTION", Architecture.I64, Platform.CENT_OS); + + final Image gceImage = new Image(); + gceImage.setLicenses(Collections.singletonList("LICENSE")); + gceImage.setDescription("DESCRIPTION"); + gceImage.setName("GCE_IMAGE_NAME"); + gceImage.setDiskSizeGb(10l); + + new NonStrictExpectations(ServerSupport.class) { + {googleProviderMock.getNetworkServices().getVlanSupport().getVlan(TEST_VLAN_ID); + result = network; + } + {googleProviderMock.getComputeServices().getVolumeSupport().getVolume(anyString); + result = null; + } + {support.getProduct(anyString).getDescription(); + result = TEST_PRODUCT_ID; + } + {googleProviderMock.getComputeServices().getImageSupport().getImage(TEST_MACHINE_IMAGE_ID); + result = image; + } + {googleComputeMock.images().get(anyString, anyString).execute(); + result = gceImage; + } + }; + support.launch(options); + } + + @Test(expected = ResourceNotFoundException.class) + public void launch_shouldThrowExceptionIfImageContentLinkNotFound() throws CloudException, InternalException, IOException { + VMLaunchOptions options = VMLaunchOptions.getInstance(TEST_PRODUCT_ID, TEST_MACHINE_IMAGE_ID, TEST_HOST_NAME, TEST_FRIENDLY_NAME, TEST_DESCRIPTION); + options = options.inVlan(null, TEST_DATACENTER, TEST_VLAN_ID); + + final VLAN network = new VLAN(); + network.setTag("contentLink", "vlanContentLink"); + + final Image gceImage = new Image(); + gceImage.setLicenses(Collections.singletonList("LICENSE")); + gceImage.setDescription("DESCRIPTION"); + gceImage.setName("GCE_IMAGE_NAME"); + gceImage.setDiskSizeGb(10l); + + new NonStrictExpectations(ServerSupport.class) { + {googleProviderMock.getNetworkServices().getVlanSupport().getVlan(TEST_VLAN_ID); + result = network; + } + {googleProviderMock.getComputeServices().getVolumeSupport().getVolume(anyString); + result = null; + } + {support.getProduct(anyString).getDescription(); + result = TEST_PRODUCT_ID; + } + {googleProviderMock.getComputeServices().getImageSupport().getImage(TEST_MACHINE_IMAGE_ID); + result = null; + } + {googleComputeMock.images().get(anyString, anyString).execute(); + result = gceImage; + } + }; + support.launch(options); + } + + @Test(expected = ResourceNotFoundException.class) + public void launch_shouldThrowExceptionIfNewVmIdNotReturned() throws CloudException, InternalException, IOException { + VMLaunchOptions options = VMLaunchOptions.getInstance(TEST_PRODUCT_ID, TEST_MACHINE_IMAGE_ID, TEST_HOST_NAME, TEST_FRIENDLY_NAME, TEST_DESCRIPTION); + options = options.inVlan(null, TEST_DATACENTER, TEST_VLAN_ID); + + final VLAN network = new VLAN(); + network.setTag("contentLink", "vlanContentLink"); + + final MachineImage image = MachineImage.getInstance("OWNER", TEST_REGION, TEST_MACHINE_IMAGE_ID, ImageClass.MACHINE, MachineImageState.ACTIVE, + "IMAGE_NAME", "IMAGE_DESCRIPTION", Architecture.I64, Platform.CENT_OS); + image.setTag("contentLink", "imageContentLink"); + + final Image gceImage = new Image(); + gceImage.setLicenses(Collections.singletonList("LICENSE")); + gceImage.setDescription("DESCRIPTION"); + gceImage.setName("GCE_IMAGE_NAME"); + gceImage.setDiskSizeGb(10l); + + new NonStrictExpectations(ServerSupport.class) { + {googleProviderMock.getNetworkServices().getVlanSupport().getVlan(TEST_VLAN_ID); + result = network; + } + {googleProviderMock.getComputeServices().getVolumeSupport().getVolume(anyString); + result = null; + } + {support.getProduct(anyString).getDescription(); + result = TEST_PRODUCT_ID; + } + {googleProviderMock.getComputeServices().getImageSupport().getImage(TEST_MACHINE_IMAGE_ID); + result = image; + } + {googleComputeMock.images().get(anyString, anyString).execute(); + result = gceImage; + } + {googleComputeMock.instances().insert(TEST_ACCOUNT_NO, TEST_DATACENTER, (Instance)any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationTarget(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, "", TEST_DATACENTER, false); + result = ""; + } + }; + + support.launch(options); + } + @Test public void listProducts_shouldReturnProductsForSpecifiedDatacenter() throws CloudException, InternalException, IOException { new NonStrictExpectations() { @@ -620,9 +771,24 @@ public void terminate() throws CloudException, InternalException, IOException { support.terminate(TEST_VM_ID, "terminate test"); } + @Test + public void terminateVm_shouldNotCallDeleteFunctionIfVmNotFound() throws CloudException, InternalException, IOException { + new NonStrictExpectations(ServerSupport.class) { + {support.getVirtualMachine(TEST_VM_ID); + result = null; + } + }; + support.terminateVm(TEST_VM_ID); + } + @Test(expected = OperationNotSupportedException.class) public void unpause_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { support.unpause(TEST_VM_ID); } + + @Test(expected = InternalException.class) + public void launchMany_shouldThrowExceptionIfCountLessthanZero() throws CloudException, InternalException { + support.launchMany(VMLaunchOptions.getInstance(TEST_PRODUCT_ID, TEST_MACHINE_IMAGE_ID, "NAME", "DESCRIPTION"), 0); + } } diff --git a/src/test/java/org/dasein/cloud/google/SnapshotSupportTest.java b/src/test/java/org/dasein/cloud/google/SnapshotSupportTest.java index 65309c1..c0fd35c 100644 --- a/src/test/java/org/dasein/cloud/google/SnapshotSupportTest.java +++ b/src/test/java/org/dasein/cloud/google/SnapshotSupportTest.java @@ -39,6 +39,8 @@ import org.joda.time.format.ISODateTimeFormat; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.IOException; import java.util.ArrayList; @@ -51,6 +53,7 @@ * Date: 25/05/2016 * Time: 14:23 */ +@RunWith(JUnit4.class) public class SnapshotSupportTest extends GoogleTestBase { private SnapshotSupport support = null; final String TEST_SNAPSHOT_ID = "TESTSNAPSHOT_112233"; diff --git a/src/test/java/org/dasein/cloud/google/TopologySupportTest.java b/src/test/java/org/dasein/cloud/google/TopologySupportTest.java index 7f712f5..cd75c41 100644 --- a/src/test/java/org/dasein/cloud/google/TopologySupportTest.java +++ b/src/test/java/org/dasein/cloud/google/TopologySupportTest.java @@ -31,12 +31,16 @@ import org.dasein.cloud.ci.Topology; import org.dasein.cloud.ci.TopologyFilterOptions; import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** @@ -44,6 +48,7 @@ * Date: 26/05/2016 * Time: 15:53 */ +@RunWith(JUnit4.class) public class TopologySupportTest extends GoogleTestBase { private GoogleTopologySupport support = null; final String TEST_INSTANCE_TEMPLATE = "TEST_INSTANCE_TEMPLATE"; @@ -75,6 +80,7 @@ private InstanceTemplateList getTestInstanceTemplateList() { return itl; } + @Test public void listTopologies_shouldReturnAllAvailableTopologies() throws CloudException, InternalException, IOException { new NonStrictExpectations() { {instanceTemplates.list(TEST_ACCOUNT_NO).execute(); @@ -88,9 +94,9 @@ public void listTopologies_shouldReturnAllAvailableTopologies() throws CloudExce assertTrue(resultAsList.size() == 1); Topology topology = resultAsList.get(0); assertTrue(topology.getName().equals(TEST_INSTANCE_TEMPLATE)); - assertTrue(topology.getProviderRegionId().equals(TEST_REGION)); + assertNull(topology.getProviderRegionId()); assertTrue(topology.getDescription().equals("DESCRIPTION")); - assertTrue(topology.getProviderDataCenterId().equals(TEST_DATACENTER)); - assertTrue(topology.getProviderOwnerId(),equals(TEST_ACCOUNT_NO)); + assertNull(topology.getProviderDataCenterId()); + assertTrue(topology.getProviderOwnerId().equals(TEST_ACCOUNT_NO)); } } From 43be911c0bcfc2bdd07f99869d06426be7c5a98a Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Thu, 2 Jun 2016 15:49:31 +0100 Subject: [PATCH 11/15] firewall tests --- .../cloud/google/network/FirewallSupport.java | 2 +- .../cloud/google/FirewallSupportTest.java | 302 ++++++++++++++++++ 2 files changed, 303 insertions(+), 1 deletion(-) create mode 100644 src/test/java/org/dasein/cloud/google/FirewallSupportTest.java diff --git a/src/main/java/org/dasein/cloud/google/network/FirewallSupport.java b/src/main/java/org/dasein/cloud/google/network/FirewallSupport.java index 2e25318..bf5a918 100644 --- a/src/main/java/org/dasein/cloud/google/network/FirewallSupport.java +++ b/src/main/java/org/dasein/cloud/google/network/FirewallSupport.java @@ -79,7 +79,7 @@ public class FirewallSupport extends AbstractFirewallSupport { private Google provider = null; - FirewallSupport(Google provider) { + public FirewallSupport(Google provider) { super(provider); this.provider = provider; } diff --git a/src/test/java/org/dasein/cloud/google/FirewallSupportTest.java b/src/test/java/org/dasein/cloud/google/FirewallSupportTest.java new file mode 100644 index 0000000..eb54e7a --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/FirewallSupportTest.java @@ -0,0 +1,302 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.model.Firewall; +import com.google.api.services.compute.model.FirewallList; +import com.google.api.services.compute.model.Network; +import com.google.api.services.compute.model.NetworkList; +import com.google.api.services.compute.model.Operation; +import mockit.NonStrictExpectations; +import org.apache.commons.collections.IteratorUtils; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.OperationNotSupportedException; +import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.VisibleScope; +import org.dasein.cloud.google.network.FirewallSupport; +import org.dasein.cloud.network.Direction; +import org.dasein.cloud.network.FirewallCreateOptions; +import org.dasein.cloud.network.FirewallRule; +import org.dasein.cloud.network.Permission; +import org.dasein.cloud.network.Protocol; +import org.dasein.cloud.network.RuleTarget; +import org.dasein.cloud.network.RuleTargetType; +import org.dasein.cloud.network.VLAN; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * User: daniellemayne + * Date: 31/05/2016 + * Time: 11:19 + */ +@RunWith(JUnit4.class) +public class FirewallSupportTest extends GoogleTestBase { + private FirewallSupport support = null; + static String TEST_FIREWALL_ID = "fw-TEST_FIREWALL_ID"; + + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + support = new FirewallSupport(googleProviderMock); + } + + private FirewallList getTestFirewallList() { + Firewall.Allowed allowed = new Firewall.Allowed(); + allowed.setIPProtocol("tcp"); + allowed.setPorts(Collections.singletonList("22")); + + Firewall firewall = new Firewall(); + firewall.setAllowed(Collections.singletonList(allowed)); + firewall.setCreationTimestamp("2016-06-01T08:57:34.123+00:00"); //yyyy-MM-dd'T'HH:mm:ss.SSSZZ + firewall.setDescription("TEST_DESCRIPTION"); + firewall.setName("TEST_FIREWALL_ID"); + firewall.setNetwork("https://www.googleapis.com/compute/v1/projects/myproject/global/networks/default"); + firewall.setSourceRanges(Collections.singletonList("0.0.0.0/0")); + + FirewallList list = new FirewallList(); + list.setItems(Collections.singletonList(firewall)); + return list; + } + + private NetworkList getTestNetworkList() { + Network net = new Network(); + net.setName("TEST_NETWORK"); + net.setSelfLink("https://www.googleapis.com/compute/v1/projects/myproject/global/networks/TEST_NETWORK"); + + Network net2 = new Network(); + net2.setName("default"); + net2.setSelfLink("https://www.googleapis.com/compute/v1/projects/myproject/global/networks/default"); + + List list = new ArrayList<>(); + list.add(net); + list.add(net2); + + NetworkList nl = new NetworkList(); + nl.setItems(list); + return nl; + } + + @Test + public void authorize_shouldReturnNewFirewallRule() throws CloudException, InternalException, IOException { + final VLAN vlan = new VLAN(); + vlan.setTag("contentLink", "TESTNETWORKLINK"); + + new NonStrictExpectations() { + {googleProviderMock.getNetworkServices().getVlanSupport().getVlan(anyString); + result = vlan; + } + {googleProviderMock.getComputeServices().getVirtualMachineSupport().getVmNameFromId(anyString); + result = TEST_VM_ID; + } + {googleComputeMock.firewalls().insert(TEST_ACCOUNT_NO, (Firewall) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationTarget(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, "", "", false); + result = "TEST_FIREWALL_RULE"; + } + }; + + String ruleId = support.authorize(TEST_FIREWALL_ID, Direction.INGRESS, Permission.ALLOW, RuleTarget.getCIDR("192.168.1.0"), Protocol.TCP, + RuleTarget.getVirtualMachine(TEST_VM_ID), 80, 80, 0); + assertTrue(ruleId.equals("TEST_FIREWALL_RULE")); + } + + @Test(expected = OperationNotSupportedException.class) + public void authorize_shouldThrowExceptionIfPermissionIsDeny() throws CloudException, InternalException { + support.authorize(TEST_FIREWALL_ID, Direction.INGRESS, Permission.DENY, RuleTarget.getCIDR("0.0.0.0/0"), Protocol.TCP, RuleTarget.getVlan("VLAN"), + 22, 22, 0); + } + + @Test(expected = OperationNotSupportedException.class) + public void authorize_shouldThrowExceptionIfDirectionIsEgress() throws CloudException, InternalException { + support.authorize(TEST_FIREWALL_ID, Direction.EGRESS, Permission.ALLOW, RuleTarget.getCIDR("0.0.0.0/0"), Protocol.TCP, RuleTarget.getVlan("VLAN"), + 22, 22, 0); + } + + @Test(expected = OperationNotSupportedException.class) + public void authorize_shouldThrowExceptionIfSourceEndpointIsGlobal() throws CloudException, InternalException { + support.authorize(TEST_FIREWALL_ID, Direction.INGRESS, Permission.ALLOW, RuleTarget.getGlobal(TEST_FIREWALL_ID), Protocol.TCP, RuleTarget.getVlan("VLAN"), + 22, 22, 0); + } + + @Test(expected = OperationNotSupportedException.class) + public void create_shouldThrowOperationNotSupportException() throws CloudException, InternalException { + support.create(FirewallCreateOptions.getInstance("NAME", "DESCRIPTION")); + } + + @Test(expected = OperationNotSupportedException.class) + public void delete_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.delete(TEST_FIREWALL_ID); + } + + @Test + public void getFirewall_shouldReturnFirewallWithCorrectAttributes() throws CloudException, InternalException, IOException { + final Network vlan = new Network(); + vlan.setName("TEST_FIREWALL_ID"); + vlan.setDescription("TEST_DESCRIPTION"); + + new NonStrictExpectations() { + {googleComputeMock.networks().get(TEST_ACCOUNT_NO, "TEST_FIREWALL_ID").execute(); + result = vlan; + } + {googleComputeMock.firewalls().list(TEST_ACCOUNT_NO).setFilter(anyString).execute(); + result = getTestFirewallList(); + } + }; + + org.dasein.cloud.network.Firewall fw = support.getFirewall(TEST_FIREWALL_ID); + assertNotNull(fw); + assertTrue(fw.getName().equals("TEST_FIREWALL_ID Firewall")); + assertTrue(fw.getProviderFirewallId().equals(TEST_FIREWALL_ID)); + assertTrue(fw.getVisibleScope().equals(VisibleScope.ACCOUNT_GLOBAL)); + assertTrue(fw.isActive()); + assertTrue(fw.isAvailable()); + assertTrue(fw.getDescription().equals("TEST_DESCRIPTION")); + assertTrue(fw.getProviderVlanId().equals("TEST_FIREWALL_ID")); + assertNotNull(fw.getRules()); + Iterable rules = fw.getRules(); + List list = IteratorUtils.toList(rules.iterator()); + assertTrue(list.size() == 1); + FirewallRule rule = list.get(0); + assertTrue(rule.getProviderRuleId().equals("TEST_FIREWALL_ID")); + assertTrue(rule.getFirewallId().equals("fw-default")); + assertTrue(rule.getSourceEndpoint().getRuleTargetType().equals(RuleTargetType.CIDR)); + assertTrue(rule.getSourceEndpoint().getCidr().equals("0.0.0.0/0")); + assertTrue(rule.getDirection().equals(Direction.INGRESS)); + assertTrue(rule.getProtocol().equals(Protocol.TCP)); + assertTrue(rule.getPermission().equals(Permission.ALLOW)); + assertTrue(rule.getDestinationEndpoint().getRuleTargetType().equals(RuleTargetType.VLAN)); + assertTrue(rule.getDestinationEndpoint().getProviderVlanId().equals("default")); + assertTrue(rule.getStartPort() == 22); + assertTrue(rule.getEndPort() == 22); + } + + @Test + public void getFirewall_shouldReturnNullIfFirewallIdDoesNotStartWith_fw() throws CloudException, InternalException, IOException { + org.dasein.cloud.network.Firewall fw = support.getFirewall("test"); + assertNull(fw); + } + + @Test + public void getRules_shouldReturnOnlyRulesForSpecifiedFirewallId() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.firewalls().list(TEST_ACCOUNT_NO).setFilter(anyString).execute(); + result = getTestFirewallList(); + } + }; + + Iterable rules = support.getRules(TEST_FIREWALL_ID); + assertNotNull(rules); + List list = IteratorUtils.toList(rules.iterator()); + assertTrue(list.size() == 1); + } + + @Test + public void list_shouldReturnFirewallForEachNetwork() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.networks().list(TEST_ACCOUNT_NO).execute(); + result = getTestNetworkList(); + } + {googleComputeMock.firewalls().list(TEST_ACCOUNT_NO).execute(); + result = getTestFirewallList(); + } + }; + + Iterable list = support.list(); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 2); + Iterable ruleList = resultAsList.get(0).getRules(); + Iterable ruleList2 = resultAsList.get(1).getRules(); + List firewallRuleList = IteratorUtils.toList(ruleList.iterator()); + firewallRuleList.addAll(IteratorUtils.toList(ruleList2.iterator())); + assertTrue(firewallRuleList.size() == 1); + } + + @Test + public void listFirewallStatus_shoudreturnCorrectNumberOfStatusObjects() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.networks().list(TEST_ACCOUNT_NO).execute(); + result = getTestNetworkList(); + } + {googleComputeMock.firewalls().list(TEST_ACCOUNT_NO).execute(); + result = getTestFirewallList(); + } + }; + + Iterable list = support.listFirewallStatus(); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertNotNull(resultAsList); + assertTrue(resultAsList.size() == 2); + assertTrue(resultAsList.get(0).getResourceStatus().equals(true)); + assertTrue(resultAsList.get(1).getResourceStatus().equals(true)); + } + + @Test + public void revoke_shouldResultInSuccessfulOperation() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.firewalls().delete(TEST_ACCOUNT_NO, TEST_FIREWALL_ID).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, "", ""); + result = true; + } + }; + support.revoke(TEST_FIREWALL_ID); + } + + @Test(expected = OperationNotSupportedException.class) + public void revoke_shouldThrowOperationNotSupportedExceptionIfDirectionIsEgress() throws CloudException, InternalException { + support.revoke(TEST_FIREWALL_ID, Direction.EGRESS, "0.0.0.0/0", Protocol.TCP, 22, 22); + } + + @Test(expected = OperationNotSupportedException.class) + public void revoke_shouldThrowOperationNotSupportedExceptionIfPermissionIsDeny() throws CloudException, InternalException { + support.revoke(TEST_FIREWALL_ID, Direction.INGRESS, Permission.DENY, "0.0.0.0/0", Protocol.TCP, 22, 22); + } + + @Test(expected = OperationNotSupportedException.class) + public void revoke_shouldThrowOperationNotSupportedExceptionIfCIDRIsNotIPv4() throws CloudException, InternalException { + support.revoke(TEST_FIREWALL_ID, Direction.INGRESS, Permission.ALLOW, "0.0.0/0", Protocol.TCP, RuleTarget.getVlan("VLAN"), 22, 22); + } + + @Test(expected = OperationNotSupportedException.class) + public void revoke_shouldThrowOperationNotSupportedExceptionIfSourceIsNotIPv4() throws CloudException, InternalException { + support.revoke(TEST_FIREWALL_ID, Direction.INGRESS, Permission.ALLOW, "0.0.0", Protocol.TCP, RuleTarget.getVlan("VLAN"), 22, 22); + } + + @Test(expected = OperationNotSupportedException.class) + public void revoke_shouldThrowOperationNotSupportedExceptionIfTargetTypeIsCIDR() throws CloudException, InternalException { + support.revoke(TEST_FIREWALL_ID, Direction.INGRESS, Permission.ALLOW, "0.0.0.0/0", Protocol.TCP, RuleTarget.getCIDR("0.0.0.0/0"), 22, 22); + } +} From 2695440dc15fd4ae76281b19d109b9acfda81118 Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Wed, 8 Jun 2016 10:08:26 +0100 Subject: [PATCH 12/15] ip address tests --- .../google/network/IPAddressSupport.java | 4 +- .../cloud/google/IPAddressSupportTest.java | 354 ++++++++++++++++++ 2 files changed, 356 insertions(+), 2 deletions(-) create mode 100644 src/test/java/org/dasein/cloud/google/IPAddressSupportTest.java diff --git a/src/main/java/org/dasein/cloud/google/network/IPAddressSupport.java b/src/main/java/org/dasein/cloud/google/network/IPAddressSupport.java index 9bf6fcb..3d29b3a 100644 --- a/src/main/java/org/dasein/cloud/google/network/IPAddressSupport.java +++ b/src/main/java/org/dasein/cloud/google/network/IPAddressSupport.java @@ -68,7 +68,7 @@ public class IPAddressSupport extends AbstractIpAddressSupport { static private final ExecutorService threadPool = Executors.newFixedThreadPool(10); static private final Logger logger = Google.getLogger(IPAddressSupport.class); - protected IPAddressSupport(Google provider) { + public IPAddressSupport(Google provider) { super(provider); } @@ -425,7 +425,7 @@ private IpAddress toIpAddress(Address address){ ipAddress.setForVlan(false); if(address.getUsers() != null && address.getUsers().size() > 0){ for(String user : address.getUsers()){ - if (user.contains("instances")) { + if (user.contains("instances") && (ipAddress.getServerId() == null || ipAddress.getServerId().equals("")) ) { user = user.substring(user.lastIndexOf("/") + 1); //we need to get the full server name_id so that ids match up user = getServerIdForName(user); diff --git a/src/test/java/org/dasein/cloud/google/IPAddressSupportTest.java b/src/test/java/org/dasein/cloud/google/IPAddressSupportTest.java new file mode 100644 index 0000000..4cfe759 --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/IPAddressSupportTest.java @@ -0,0 +1,354 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.model.AccessConfig; +import com.google.api.services.compute.model.Address; +import com.google.api.services.compute.model.AddressAggregatedList; +import com.google.api.services.compute.model.AddressList; +import com.google.api.services.compute.model.AddressesScopedList; +import com.google.api.services.compute.model.Operation; +import mockit.Mocked; +import mockit.NonStrictExpectations; +import org.apache.commons.collections.IteratorUtils; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.OperationNotSupportedException; +import org.dasein.cloud.ResourceNotFoundException; +import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.compute.VirtualMachine; +import org.dasein.cloud.google.compute.server.ServerSupport; +import org.dasein.cloud.google.network.IPAddressSupport; +import org.dasein.cloud.network.AddressType; +import org.dasein.cloud.network.IPVersion; +import org.dasein.cloud.network.IpAddress; +import org.dasein.cloud.network.Protocol; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * User: daniellemayne + * Date: 02/06/2016 + * Time: 11:34 + */ +public class IPAddressSupportTest extends GoogleTestBase { + private IPAddressSupport support = null; + static String TEST_IP_ADDRESS = "192.168.101.1"; + static String TEST_IP_ADDRESS_ID = "TEST_IP_ADDRESS_ID"; + + @Mocked + ServerSupport serverSupport; + + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + support = new IPAddressSupport(googleProviderMock); + } + + private AddressAggregatedList getTestAddressAggregatedList() { + Address address = new Address(); + address.setName(TEST_IP_ADDRESS_ID); + address.setAddress(TEST_IP_ADDRESS); + address.setRegion("/"+TEST_REGION); + List users = new ArrayList<>(); + users.add("/instances/"+TEST_VM_ID); + users.add("/instances/vm2"); + address.setUsers(users); + address.setStatus("RESERVED"); + + AddressesScopedList addressesScopedList = new AddressesScopedList(); + addressesScopedList.setAddresses(Collections.singletonList(address)); + + AddressAggregatedList agl = new AddressAggregatedList(); + Map map = new HashMap<>(); + map.put(TEST_REGION, addressesScopedList); + agl.setItems(map); + return agl; + + } + + @Test + public void assign_shouldResultInSuccessfulOperation() throws CloudException, InternalException, IOException { + final IpAddress ipAddress = new IpAddress(); + ipAddress.setAddress(TEST_IP_ADDRESS); + ipAddress.setVersion(IPVersion.IPV4); + + final VirtualMachine vm = new VirtualMachine(); + vm.setName("VMNAME"); + vm.setProviderDataCenterId(TEST_DATACENTER); + + new NonStrictExpectations(IPAddressSupport.class) { + {support.getIpAddress(anyString); + result = ipAddress; + } + {googleProviderMock.getComputeServices().getVirtualMachineSupport().getVirtualMachine(anyString); + result = vm; + } + {googleComputeMock.instances().deleteAccessConfig(TEST_ACCOUNT_NO, TEST_DATACENTER, "VMNAME", "External NAT", "nic0").execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, "", TEST_DATACENTER); + result = true; + } + {googleComputeMock.instances().addAccessConfig(TEST_ACCOUNT_NO, TEST_DATACENTER, "VMNAME", "nic0", (AccessConfig) any).execute(); + result = new Operation(); + } + }; + + support.assign(TEST_IP_ADDRESS, TEST_VM_ID); + } + + @Test(expected = OperationNotSupportedException.class) + public void assignToNetworkInterface_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.assignToNetworkInterface(TEST_IP_ADDRESS, TEST_VM_ID); + } + + @Test(expected = OperationNotSupportedException.class) + public void forward_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.forward(TEST_IP_ADDRESS, 22, Protocol.TCP, 22, TEST_VM_ID); + } + + @Test + public void getIpAddress_shouldReturnObjectWithCorrectAttributes() throws CloudException, InternalException, IOException { + final VirtualMachine vm = new VirtualMachine(); + vm.setProviderVirtualMachineId(TEST_VM_ID); + + new NonStrictExpectations() { + {googleComputeMock.addresses().aggregatedList(TEST_ACCOUNT_NO).setFilter(anyString).execute(); + result = getTestAddressAggregatedList(); + } + {googleProviderMock.getComputeServices().getVirtualMachineSupport(); + result = serverSupport; + } + {serverSupport.getVirtualMachine(TEST_VM_ID); + result = vm; + } + }; + IpAddress address = support.getIpAddress(TEST_IP_ADDRESS_ID); + assertNotNull(address); + assertTrue(address.getProviderIpAddressId().equals(TEST_IP_ADDRESS_ID)); + assertTrue(address.getRawAddress().getIpAddress().equals(TEST_IP_ADDRESS)); + assertTrue(address.getRegionId().equals(TEST_REGION)); + assertTrue(address.getAddressType().equals(AddressType.PUBLIC)); + assertTrue(address.getVersion().equals(IPVersion.IPV4)); + assertTrue(!address.isForVlan()); + assertTrue(address.getServerId().equals(TEST_VM_ID)); + } + + @Test + public void getIpAddressIpFromIP_shouldReturnCorrectName() throws CloudException, InternalException, IOException { + final AddressList list = new AddressList(); + list.setItems(getTestAddressAggregatedList().getItems().get(TEST_REGION).getAddresses()); + + new NonStrictExpectations() { + {googleComputeMock.addresses().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = list; + } + }; + + String name = support.getIpAddressIdFromIP(TEST_IP_ADDRESS, TEST_REGION); + assertTrue(name.equals(TEST_IP_ADDRESS_ID)); + } + + @Test(expected = ResourceNotFoundException.class) + public void getIpAddressFromIP_shouldThrowExceptionIfCloudReturnsNullList() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.addresses().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = null; + } + }; + support.getIpAddressIdFromIP(TEST_IP_ADDRESS, TEST_REGION); + } + + @Test + public void listIpPool_shouldReturnEmptyListIfVersionIsNotIPv4() throws CloudException, InternalException { + Iterable list = support.listIpPool(IPVersion.IPV6, false); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 0); + } + + @Test + public void listIpPool_shouldReturnAllAvailableIpAddresses() throws CloudException, InternalException, IOException { + final AddressList list = new AddressList(); + list.setItems(getTestAddressAggregatedList().getItems().get(TEST_REGION).getAddresses()); + + new NonStrictExpectations() { + {googleComputeMock.addresses().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = list; + } + }; + + Iterable pool = support.listIpPool(IPVersion.IPV4, false); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(pool.iterator()); + assertTrue(resultAsList.size() == 1); + } + + @Test + public void listIpPoolUnassignedOnly_shoudlReturnEmptyList() throws CloudException, InternalException, IOException { + final AddressList list = new AddressList(); + list.setItems(getTestAddressAggregatedList().getItems().get(TEST_REGION).getAddresses()); + + final VirtualMachine vm = new VirtualMachine(); + vm.setProviderVirtualMachineId(TEST_VM_ID); + + new NonStrictExpectations() { + {googleComputeMock.addresses().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = list; + } + {googleProviderMock.getComputeServices().getVirtualMachineSupport(); + result = serverSupport; + } + {serverSupport.getVirtualMachine(TEST_VM_ID); + result = vm; + } + }; + + Iterable pool = support.listIpPool(IPVersion.IPV4, true); + assertNotNull(pool); + List resultAsList = IteratorUtils.toList(pool.iterator()); + assertTrue(resultAsList.size() == 0); + } + + @Test + public void listIpPoolStatus_shouldReturnCorrectStatus() throws CloudException, InternalException, IOException { + final VirtualMachine vm = new VirtualMachine(); + vm.setProviderVirtualMachineId(TEST_VM_ID); + + new NonStrictExpectations() { + {googleComputeMock.addresses().aggregatedList(TEST_ACCOUNT_NO).execute(); + result = getTestAddressAggregatedList(); + } + {googleProviderMock.getComputeServices().getVirtualMachineSupport(); + result = serverSupport; + } + {serverSupport.getVirtualMachine(TEST_VM_ID); + result = vm; + } + }; + + Iterable list = support.listIpPoolStatus(IPVersion.IPV4); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + assertTrue(resultAsList.get(0).getResourceStatus().equals(false)); + } + + @Test + public void listIpPoolStatus_shouldReturnEmptyListIfNotIPv4() throws CloudException, InternalException, IOException { + + Iterable list = support.listIpPoolStatus(IPVersion.IPV6); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 0); + } + + @Test + public void releaseFromPool_shouldResultInSuccessfulOperation() throws CloudException, InternalException, IOException { + final IpAddress address = new IpAddress(); + address.setRegionId(TEST_REGION); + + new NonStrictExpectations(IPAddressSupport.class) { + {support.getIpAddress(TEST_IP_ADDRESS_ID); + result = address; + } + {googleComputeMock.addresses().delete(TEST_ACCOUNT_NO, TEST_REGION, TEST_IP_ADDRESS_ID).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, ""); + result = true; + } + }; + + support.releaseFromPool(TEST_IP_ADDRESS_ID); + } + + @Test + public void releaseFromServer_shouldResultInSuccessfulOperation() throws CloudException, InternalException, IOException { + final Address address = new Address(); + address.setName(TEST_IP_ADDRESS_ID); + address.setAddress(TEST_IP_ADDRESS); + address.setRegion("/"+TEST_REGION); + List users = new ArrayList<>(); + users.add("/zones/"+TEST_DATACENTER+"/instances/"+TEST_VM_ID); + users.add("/zones/"+TEST_DATACENTER+"/instances/vm2"); + address.setUsers(users); + address.setStatus("RESERVED"); + + new NonStrictExpectations() { + {googleComputeMock.addresses().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_IP_ADDRESS_ID).execute(); + result = address; + } + {googleComputeMock.instances().deleteAccessConfig(TEST_ACCOUNT_NO, TEST_DATACENTER, TEST_VM_ID, "External NAT", "nic0").execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.ZONE_OPERATION, "", TEST_DATACENTER); + result = true; + } + }; + support.releaseFromServer(TEST_IP_ADDRESS_ID); + } + + @Test + public void request_shouldReturnNewIpAddressId() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.addresses().insert(TEST_ACCOUNT_NO, TEST_REGION, (Address) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationTarget(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, "", false); + result = "new_ip_address_id"; + } + }; + + String id = support.request(IPVersion.IPV4); + assertTrue(id.equals("new_ip_address_id")); + } + + @Test(expected = OperationNotSupportedException.class) + public void request_shouldThrowExceptionIfNotIPv4() throws CloudException, InternalException { + support.request(IPVersion.IPV6); + } + + @Test(expected = OperationNotSupportedException.class) + public void requestForVlan_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.requestForVLAN(IPVersion.IPV6); + } + + @Test(expected = OperationNotSupportedException.class) + public void requestForVlanWithVlanId_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.requestForVLAN(IPVersion.IPV4, "VLAN1"); + } + + @Test(expected = OperationNotSupportedException.class) + public void stopForward_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.stopForward("RULE"); + } +} From 56b2c49b144cbe5e59724457facb7f6b9fd25b50 Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Tue, 21 Jun 2016 10:52:38 +0100 Subject: [PATCH 13/15] load balancer unit tests --- .../google/network/LoadBalancerSupport.java | 6 + .../dasein/cloud/google/DatacentersTest.java | 2 +- .../cloud/google/LoadBalancerSupportTest.java | 815 ++++++++++++++++++ 3 files changed, 822 insertions(+), 1 deletion(-) create mode 100644 src/test/java/org/dasein/cloud/google/LoadBalancerSupportTest.java diff --git a/src/main/java/org/dasein/cloud/google/network/LoadBalancerSupport.java b/src/main/java/org/dasein/cloud/google/network/LoadBalancerSupport.java index 22a0ae0..ecdf754 100644 --- a/src/main/java/org/dasein/cloud/google/network/LoadBalancerSupport.java +++ b/src/main/java/org/dasein/cloud/google/network/LoadBalancerSupport.java @@ -411,6 +411,9 @@ public void addListeners(String toLoadBalancerId, LbListener[] listeners) throws throw new GeneralCloudException("Exception adding listener", e); } } catch (Exception e) { + if (e instanceof ResourceNotFoundException) { + throw e; + } throw new GeneralCloudException("Exception adding listener", e); // catch the exception from method.getOperation } } @@ -482,6 +485,9 @@ void createLoadBalancerForwardingRule(@Nonnull LoadBalancerCreateOptions options throw new GeneralCloudException("Exception creating forwarding rule", e); } } catch (Exception e) { + if (e instanceof ResourceNotFoundException) { + throw e; + } throw new GeneralCloudException("Exception creating forwarding rule", e); // catch the exception from method.getOperation } finally { diff --git a/src/test/java/org/dasein/cloud/google/DatacentersTest.java b/src/test/java/org/dasein/cloud/google/DatacentersTest.java index f6b5e3b..8d8f9da 100644 --- a/src/test/java/org/dasein/cloud/google/DatacentersTest.java +++ b/src/test/java/org/dasein/cloud/google/DatacentersTest.java @@ -79,7 +79,7 @@ private RegionList getTestRegionList() { List regionList = new ArrayList(); Region region = new Region(); - region.setName(TEST_REGION);; + region.setName(TEST_REGION); regionList.add(region); Region region1 = new Region(); diff --git a/src/test/java/org/dasein/cloud/google/LoadBalancerSupportTest.java b/src/test/java/org/dasein/cloud/google/LoadBalancerSupportTest.java new file mode 100644 index 0000000..52497f5 --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/LoadBalancerSupportTest.java @@ -0,0 +1,815 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.model.ForwardingRule; +import com.google.api.services.compute.model.ForwardingRuleList; +import com.google.api.services.compute.model.HttpHealthCheck; +import com.google.api.services.compute.model.Operation; +import com.google.api.services.compute.model.Region; +import com.google.api.services.compute.model.TargetPool; +import com.google.api.services.compute.model.TargetPoolList; +import com.google.api.services.compute.model.TargetPoolsAddHealthCheckRequest; +import com.google.api.services.compute.model.TargetPoolsAddInstanceRequest; +import com.google.api.services.compute.model.TargetPoolsRemoveInstanceRequest; +import mockit.Expectations; +import mockit.Mocked; +import mockit.NonStrictExpectations; +import org.apache.commons.collections.IteratorUtils; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.ResourceNotFoundException; +import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.compute.VirtualMachine; +import org.dasein.cloud.google.network.IPAddressSupport; +import org.dasein.cloud.google.network.LoadBalancerSupport; +import org.dasein.cloud.network.HealthCheckFilterOptions; +import org.dasein.cloud.network.HealthCheckOptions; +import org.dasein.cloud.network.IPVersion; +import org.dasein.cloud.network.LbAlgorithm; +import org.dasein.cloud.network.LbListener; +import org.dasein.cloud.network.LbPersistence; +import org.dasein.cloud.network.LbProtocol; +import org.dasein.cloud.network.LbType; +import org.dasein.cloud.network.LoadBalancer; +import org.dasein.cloud.network.LoadBalancerAddressType; +import org.dasein.cloud.network.LoadBalancerCreateOptions; +import org.dasein.cloud.network.LoadBalancerEndpoint; +import org.dasein.cloud.network.LoadBalancerHealthCheck; +import org.dasein.cloud.network.LoadBalancerState; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +import static org.junit.Assert.*; + +/** + * User: daniellemayne + * Date: 15/06/2016 + * Time: 09:12 + */ +public class LoadBalancerSupportTest extends GoogleTestBase { + private LoadBalancerSupport support = null; + static final String TEST_LOAD_BALANCER_ID = "TEST_LOAD_BALANCER"; + static final String TEST_IP_ADDRESS_ID = "TEST_IP_ADDRESS_ID"; + static final String TEST_LB_HEALTH_CHECK_NAME = "TEST_HEALTH_CHECK_NAME"; + + @Mocked + IPAddressSupport ipAddressSupport; + + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + support = new LoadBalancerSupport(googleProviderMock); + + new NonStrictExpectations() { + {googleProviderMock.getNetworkServices().getIpAddressSupport(); + result = ipAddressSupport; + } + }; + } + + private ForwardingRuleList getTestForwardingRuleList() { + ForwardingRule fr1 = new ForwardingRule(); + fr1.setName("TEST_FORWARDING_RULE_1"); + fr1.setTarget("TEST_TARGET/"+TEST_LOAD_BALANCER_ID); + fr1.setIPProtocol("TCP"); + fr1.setPortRange("80-80"); + fr1.setIPAddress("192.168.101.2"); + + ForwardingRule fr2 = new ForwardingRule(); + fr2.setName("TEST_FORWARDING_RULE_2"); + fr2.setTarget("TEST_TARGET/"+TEST_LOAD_BALANCER_ID); + fr2.setIPProtocol("TCP"); + fr2.setPortRange("81-81"); + fr2.setIPAddress("192.168.101.3"); + + ForwardingRule fr3 = new ForwardingRule(); + fr3.setName("TEST_FORWARDING_RULE_3"); + fr3.setTarget("TEST_TARGET/"+TEST_LOAD_BALANCER_ID+"1"); + fr3.setIPProtocol("TCP"); + fr3.setPortRange("82-82"); + fr3.setIPAddress("192.168.101.4"); + + List list = new ArrayList<>(); + list.add(fr1); + list.add(fr2); + list.add(fr3); + + ForwardingRuleList frList = new ForwardingRuleList(); + frList.setItems(list); + + return frList; + } + + private HttpHealthCheck getTestHttpHealthCheck() { + HttpHealthCheck check = new HttpHealthCheck(); + check.setName(TEST_LB_HEALTH_CHECK_NAME); + check.setDescription("HC_DESCRIPTION"); + check.setHost("localhost"); + check.setPort(80); + check.setRequestPath("/index.htm"); + check.setCheckIntervalSec(5); + check.setTimeoutSec(5); + check.setHealthyThreshold(3); + check.setUnhealthyThreshold(10); + return check; + } + + private TargetPoolList getTestTargetPoolList() { + TargetPool pool = new TargetPool(); + pool.setName(TEST_LOAD_BALANCER_ID); + pool.setDescription("LB_DESCRIPTION"); + List hcs = new ArrayList<>(); + hcs.add("HC1"); + pool.setHealthChecks(hcs); + pool.setCreationTimestamp("2016-06-20T09:57:34.123"); //yyyy-MM-dd'T'HH:mm:ss.SSS + pool.setRegion(TEST_REGION); + pool.setInstances(Collections.singletonList(TEST_VM_ID)); + + TargetPool pool2 = new TargetPool(); + pool2.setName(TEST_LOAD_BALANCER_ID+"2"); + List hcs2 = new ArrayList<>(); + hcs2.add("HC2"); + hcs2.add("HC3"); + pool2.setHealthChecks(hcs2); + + List tpList = new ArrayList<>(); + tpList.add(pool); + tpList.add(pool2); + + TargetPoolList list = new TargetPoolList(); + list.setItems(tpList); + return list; + } + + @Test + public void removeLoadBalancer() throws CloudException, InternalException, IOException { + final LoadBalancer lb = LoadBalancer.getInstance(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID, LoadBalancerState.ACTIVE, TEST_LOAD_BALANCER_ID, + "DESCRIPTION", LoadBalancerAddressType.DNS, "192.168.101.1", 80); + + new NonStrictExpectations(LoadBalancerSupport.class) { + {support.getLoadBalancer(TEST_LOAD_BALANCER_ID); + result = lb; + } + {googleComputeMock.forwardingRules().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestForwardingRuleList(); + } + {ipAddressSupport.releaseFromPool(anyString); + } + {ipAddressSupport.getIpAddressIdFromIP(lb.getAddress(), TEST_REGION); + result = TEST_IP_ADDRESS_ID; + } + {support.getLoadBalancerHealthCheckName(TEST_LOAD_BALANCER_ID); + result = TEST_LB_HEALTH_CHECK_NAME; + } + {googleComputeMock.targetPools().delete(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = new Operation(); + } + {support.removeLoadBalancerHealthCheck(TEST_LB_HEALTH_CHECK_NAME); + } + }; + + new Expectations() { + {googleComputeMock.forwardingRules().delete(TEST_ACCOUNT_NO, TEST_REGION, anyString).execute(); + result = new Operation(); + times = 2; + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, ""); + result = true; + times = 3; + } + }; + + support.removeLoadBalancer(TEST_LOAD_BALANCER_ID); + } + + @Test + public void getLoadBalancerHealthCheckName_shouldReturnCorrectHealthCheckName() throws CloudException, InternalException, IOException { + final TargetPool tp = new TargetPool(); + tp.setHealthChecks(Collections.singletonList(TEST_LB_HEALTH_CHECK_NAME)); + + new NonStrictExpectations() { + {googleComputeMock.targetPools().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = tp; + } + }; + + String healthCheckName = support.getLoadBalancerHealthCheckName(TEST_LOAD_BALANCER_ID); + assertTrue(healthCheckName.equals(TEST_LB_HEALTH_CHECK_NAME)); + } + + @Test + public void removeListeners() throws CloudException, InternalException, IOException { + final LbListener[] listeners = new LbListener[]{LbListener.getInstance(80, 80)}; + new NonStrictExpectations() { + {googleComputeMock.forwardingRules().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestForwardingRuleList(); + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_1").execute(); + result = getTestForwardingRuleList().getItems().get(0); + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_2").execute(); + result = getTestForwardingRuleList().getItems().get(1); + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_3").execute(); + result = getTestForwardingRuleList().getItems().get(2); + } + {ipAddressSupport.releaseFromPool(anyString); + } + }; + + new Expectations() { + {googleComputeMock.forwardingRules().delete(TEST_ACCOUNT_NO, TEST_REGION, anyString).execute(); + result = new Operation(); + times = 1; + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, ""); + result = true; + times = 1; + } + }; + + support.removeListeners(TEST_LOAD_BALANCER_ID, listeners); + } + + @Test + public void createLoadBalancer_existingHealthCheckShouldNotCreateNewHealthCheck() throws CloudException, InternalException, IOException { + final LoadBalancerCreateOptions options = LoadBalancerCreateOptions.getInstance(TEST_LOAD_BALANCER_ID, TEST_LOAD_BALANCER_ID, TEST_IP_ADDRESS_ID); + final HealthCheckOptions hcOptions = HealthCheckOptions.getInstance( + TEST_LB_HEALTH_CHECK_NAME, null, null, "localhost", + LoadBalancerHealthCheck.HCProtocol.HTTP, 8080, "/index.htm", + support.getCapabilities().getMaxHealthCheckInterval(), + support.getCapabilities().getMaxHealthCheckTimeout(), + 3, + 10); + + options.withHealthCheckOptions(hcOptions); + options.havingListeners(LbListener.getInstance(80, 80)); + + final TargetPool tp = new TargetPool(); + tp.setSelfLink("SELF_LINK"); + + final String validName = support.getCapabilities().getLoadBalancerNamingConstraints().convertToValidName(TEST_LB_HEALTH_CHECK_NAME, Locale.US); + + new NonStrictExpectations(LoadBalancerSupport.class) { + {googleComputeMock.targetPools().insert(TEST_ACCOUNT_NO, TEST_REGION, (TargetPool) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, ""); + result = true; + } + {googleComputeMock.httpHealthChecks().get(TEST_ACCOUNT_NO, validName).execute(); + result = getTestHttpHealthCheck(); + } + {googleComputeMock.httpHealthChecks().insert(TEST_ACCOUNT_NO, (HttpHealthCheck) any).execute(); + times = 0; + } + {support.attachHealthCheckToLoadBalancer(TEST_LOAD_BALANCER_ID, TEST_LB_HEALTH_CHECK_NAME); + } + {googleComputeMock.targetPools().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = tp; + } + {googleComputeMock.forwardingRules().insert(TEST_ACCOUNT_NO, TEST_REGION, (ForwardingRule) any).execute(); + result = new Operation(); + } + }; + + String lbName = support.createLoadBalancer(options); + assertTrue(lbName.equals(TEST_LOAD_BALANCER_ID)); + } + + @Test + public void createLoadBalancer_newHealthCheckShouldCreateHealthCheck() throws CloudException, InternalException, IOException { + final LoadBalancerCreateOptions options = LoadBalancerCreateOptions.getInstance(TEST_LOAD_BALANCER_ID, TEST_LOAD_BALANCER_ID, TEST_IP_ADDRESS_ID); + final HealthCheckOptions hcOptions = HealthCheckOptions.getInstance( + TEST_LB_HEALTH_CHECK_NAME, null, null, "localhost", + LoadBalancerHealthCheck.HCProtocol.HTTP, 8080, "/index.htm", + support.getCapabilities().getMaxHealthCheckInterval(), + support.getCapabilities().getMaxHealthCheckTimeout(), + 3, + 10); + + options.withHealthCheckOptions(hcOptions); + options.havingListeners(LbListener.getInstance(80, 80)); + + final TargetPool tp = new TargetPool(); + tp.setSelfLink("SELF_LINK"); + + final String validName = support.getCapabilities().getLoadBalancerNamingConstraints().convertToValidName(TEST_LB_HEALTH_CHECK_NAME, Locale.US); + + new NonStrictExpectations(LoadBalancerSupport.class) { + {googleComputeMock.targetPools().insert(TEST_ACCOUNT_NO, TEST_REGION, (TargetPool) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, ""); + result = true; + } + {googleComputeMock.httpHealthChecks().get(TEST_ACCOUNT_NO, validName).execute(); + result = null; + result = getTestHttpHealthCheck(); + } + {googleComputeMock.httpHealthChecks().insert(TEST_ACCOUNT_NO, (HttpHealthCheck) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, TEST_REGION, ""); + result = true; + } + {support.attachHealthCheckToLoadBalancer(TEST_LOAD_BALANCER_ID, TEST_LB_HEALTH_CHECK_NAME); + } + {googleComputeMock.targetPools().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = tp; + } + {googleComputeMock.forwardingRules().insert(TEST_ACCOUNT_NO, TEST_REGION, (ForwardingRule) any).execute(); + result = new Operation(); + } + }; + + String lbName = support.createLoadBalancer(options); + assertTrue(lbName.equals(TEST_LOAD_BALANCER_ID)); + } + + @Test(expected = ResourceNotFoundException.class) + public void createLoadBalancer_shouldThrowExceptionIfNewTargetPoolNotFoundDuringForwardingRuleCreation() throws CloudException, InternalException, IOException { + final LoadBalancerCreateOptions options = LoadBalancerCreateOptions.getInstance(TEST_LOAD_BALANCER_ID, TEST_LOAD_BALANCER_ID, TEST_IP_ADDRESS_ID); + final HealthCheckOptions hcOptions = HealthCheckOptions.getInstance( + TEST_LB_HEALTH_CHECK_NAME, null, null, "localhost", + LoadBalancerHealthCheck.HCProtocol.HTTP, 8080, "/index.htm", + support.getCapabilities().getMaxHealthCheckInterval(), + support.getCapabilities().getMaxHealthCheckTimeout(), + 3, + 10); + + options.withHealthCheckOptions(hcOptions); + options.havingListeners(LbListener.getInstance(80, 80)); + + final String validName = support.getCapabilities().getLoadBalancerNamingConstraints().convertToValidName(TEST_LB_HEALTH_CHECK_NAME, Locale.US); + + new NonStrictExpectations(LoadBalancerSupport.class) { + {googleComputeMock.targetPools().insert(TEST_ACCOUNT_NO, TEST_REGION, (TargetPool) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, ""); + result = true; + } + {googleComputeMock.httpHealthChecks().get(TEST_ACCOUNT_NO, validName).execute(); + result = null; + result = getTestHttpHealthCheck(); + } + {googleComputeMock.httpHealthChecks().insert(TEST_ACCOUNT_NO, (HttpHealthCheck) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, TEST_REGION, ""); + result = true; + } + {support.attachHealthCheckToLoadBalancer(TEST_LOAD_BALANCER_ID, TEST_LB_HEALTH_CHECK_NAME); + } + {googleComputeMock.targetPools().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = null; + } + {googleComputeMock.forwardingRules().insert(TEST_ACCOUNT_NO, TEST_REGION, (ForwardingRule) any).execute(); + result = new Operation(); + } + }; + + support.createLoadBalancer(options); + } + + @Test + public void addListeners() throws CloudException, InternalException, IOException { + final TargetPool tp = new TargetPool(); + tp.setSelfLink("SELF_LINK"); + + final LbListener[] listeners = new LbListener[]{LbListener.getInstance(80, 80)}; + + new NonStrictExpectations() { + {googleComputeMock.targetPools().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = tp; + } + {googleComputeMock.forwardingRules().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestForwardingRuleList(); + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_1").execute(); + result = getTestForwardingRuleList().getItems().get(0); + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_2").execute(); + result = getTestForwardingRuleList().getItems().get(1); + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_3").execute(); + result = getTestForwardingRuleList().getItems().get(2); + } + {googleComputeMock.forwardingRules().insert(TEST_ACCOUNT_NO, TEST_REGION, (ForwardingRule) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, ""); + result = true; + } + }; + + support.addListeners(TEST_LOAD_BALANCER_ID, listeners); + } + + @Test(expected = ResourceNotFoundException.class) + public void addListeners_shouldThrowExceptionIfTargetPoolNotFound() throws CloudException, InternalException, IOException { + final LbListener[] listeners = new LbListener[]{LbListener.getInstance(80, 80)}; + + new NonStrictExpectations() { + {googleComputeMock.targetPools().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = null; + } + }; + + support.addListeners(TEST_LOAD_BALANCER_ID, listeners); + } + + @Test + public void createLoadBalancerHealthCheck_shouldReturnNewHealthCheck() throws CloudException, InternalException, IOException { + final String validName = support.getCapabilities().getLoadBalancerNamingConstraints().convertToValidName(TEST_LB_HEALTH_CHECK_NAME, Locale.US); + + new NonStrictExpectations() { + {googleComputeMock.httpHealthChecks().insert(TEST_ACCOUNT_NO, (HttpHealthCheck) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, TEST_REGION, ""); + result = true; + } + {googleComputeMock.httpHealthChecks().get(TEST_ACCOUNT_NO, validName).execute(); + result = getTestHttpHealthCheck(); + } + }; + + LoadBalancerHealthCheck hc = support.createLoadBalancerHealthCheck(HealthCheckOptions.getInstance( + TEST_LB_HEALTH_CHECK_NAME, null, null, "localhost", + LoadBalancerHealthCheck.HCProtocol.HTTP, 8080, "/index.htm", + support.getCapabilities().getMaxHealthCheckInterval(), + support.getCapabilities().getMaxHealthCheckTimeout(), + 3, + 10)); + assertNotNull(hc); + assertTrue(hc.getName().equals(TEST_LB_HEALTH_CHECK_NAME)); + } + + @Test + public void attachHealthCheckToLoadBalancer() throws CloudException, InternalException, IOException { + final String validName = support.getCapabilities().getLoadBalancerNamingConstraints().convertToValidName(TEST_LB_HEALTH_CHECK_NAME, Locale.US); + + new NonStrictExpectations(){ + {googleComputeMock.httpHealthChecks().get(TEST_ACCOUNT_NO, validName).execute(); + result = getTestHttpHealthCheck(); + } + {googleComputeMock.targetPools().addHealthCheck(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID, (TargetPoolsAddHealthCheckRequest) any).execute(); + } + }; + + support.attachHealthCheckToLoadBalancer(TEST_LOAD_BALANCER_ID, TEST_LB_HEALTH_CHECK_NAME); + } + + @Test + public void toLoadBalancerHealthCheck_shouldReturnCorrectAttributes() throws CloudException, InternalException { + LoadBalancerHealthCheck check = support.toLoadBalancerHealthCheck(TEST_LOAD_BALANCER_ID, getTestHttpHealthCheck()); + assertTrue(check.getName().equals(TEST_LB_HEALTH_CHECK_NAME)); + assertTrue(check.getDescription().equals("HC_DESCRIPTION")); + assertTrue(check.getHost().equals("localhost")); + assertTrue(check.getProviderLBHealthCheckId().equals(TEST_LOAD_BALANCER_ID)); + assertTrue(check.getProviderLoadBalancerIds().contains(TEST_LOAD_BALANCER_ID)); + assertTrue(check.getProtocol().equals(LoadBalancerHealthCheck.HCProtocol.HTTP)); + assertTrue(check.getPort() == 80); + assertTrue(check.getPath().equals("/index.htm")); + assertTrue(check.getInterval() == 5); + assertTrue(check.getTimeout() == 5); + assertTrue(check.getHealthyCount() == 3); + assertTrue(check.getUnhealthyCount() == 10); + } + + @Test(expected = InternalException.class) + public void toLoadBalancerHealthCheck_shouldThrowExceptionIfLoadBalancerIdIsNull() throws CloudException, InternalException { + support.toLoadBalancerHealthCheck(null, getTestHttpHealthCheck()); + } + + @Test(expected = InternalException.class) + public void toLoadBalancerHealthCheck_shouldThrowExceptionIfHealthCheckIsNull() throws CloudException, InternalException { + support.toLoadBalancerHealthCheck(TEST_LOAD_BALANCER_ID, null); + } + + @Test + public void listLoadBalancerHealthChecks_noFilterShouldReturnAllAvailableLbHealthChecks() throws CloudException, InternalException, IOException { + final String validName = support.getCapabilities().getLoadBalancerNamingConstraints().convertToValidName(TEST_LB_HEALTH_CHECK_NAME, Locale.US); + + new NonStrictExpectations(LoadBalancerSupport.class) { + {googleComputeMock.targetPools().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestTargetPoolList(); + } + {googleComputeMock.httpHealthChecks().get(TEST_ACCOUNT_NO, validName).execute(); + result = getTestHttpHealthCheck(); + } + {support.toLoadBalancerHealthCheck(TEST_LOAD_BALANCER_ID, getTestHttpHealthCheck()); + result = LoadBalancerHealthCheck.getInstance(LoadBalancerHealthCheck.HCProtocol.HTTP, 80, "/index.htm", 5, 5, 3, 10); + } + }; + Iterable list = support.listLBHealthChecks(HealthCheckFilterOptions.getInstance()); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 2); + } + + @Test + public void removeLoadBalancerHealthCheck() throws CloudException, InternalException, IOException { + new NonStrictExpectations(){ + {googleComputeMock.httpHealthChecks().delete(TEST_ACCOUNT_NO, TEST_LB_HEALTH_CHECK_NAME).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, TEST_REGION, ""); + result = true; + } + }; + support.removeLoadBalancerHealthCheck(TEST_LB_HEALTH_CHECK_NAME); + } + + @Test + public void modifyHealthCheck_shouldReturnHealthCheckWithNewProperty() throws CloudException, InternalException, IOException { + final HealthCheckOptions hcOptions = HealthCheckOptions.getInstance( + TEST_LB_HEALTH_CHECK_NAME, null, null, "localhost", + LoadBalancerHealthCheck.HCProtocol.HTTP, 8080, "/index.htm", + 10,//changed from 5 to 10 + support.getCapabilities().getMaxHealthCheckTimeout(), + 3, + 10); + + final HttpHealthCheck newCheck = new HttpHealthCheck(); + newCheck.setName(TEST_LB_HEALTH_CHECK_NAME); + newCheck.setDescription("HC_DESCRIPTION"); + newCheck.setHost("localhost"); + newCheck.setPort(80); + newCheck.setRequestPath("/index.htm"); + newCheck.setCheckIntervalSec(10); + newCheck.setTimeoutSec(5); + newCheck.setHealthyThreshold(3); + newCheck.setUnhealthyThreshold(10); + + new NonStrictExpectations(){ + {googleComputeMock.httpHealthChecks().get(TEST_ACCOUNT_NO, TEST_LB_HEALTH_CHECK_NAME).execute(); + result = getTestHttpHealthCheck(); + result = newCheck; + } + {googleComputeMock.httpHealthChecks().update(TEST_ACCOUNT_NO, TEST_LB_HEALTH_CHECK_NAME, (HttpHealthCheck) any).execute(); + result = new Operation(); + } + }; + + LoadBalancerHealthCheck check = support.modifyHealthCheck(TEST_LB_HEALTH_CHECK_NAME, hcOptions); + assertTrue(check.getInterval() == 10); + } + + @Test + public void getLoadBalancerHealthCheck_shouldReturnValidObject() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.httpHealthChecks().get(TEST_ACCOUNT_NO, TEST_LB_HEALTH_CHECK_NAME).execute(); + result = getTestHttpHealthCheck(); + } + }; + + LoadBalancerHealthCheck check = support.getLoadBalancerHealthCheck(TEST_LB_HEALTH_CHECK_NAME, TEST_LOAD_BALANCER_ID); + assertNotNull(check); + assertTrue(check.getName().equals(TEST_LB_HEALTH_CHECK_NAME)); + } + + @Test + public void getLoadBalancerHealthCheck_shouldReturnNullForInvalidId() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.httpHealthChecks().get(TEST_ACCOUNT_NO, TEST_LB_HEALTH_CHECK_NAME).execute(); + result = null; + } + }; + + LoadBalancerHealthCheck check = support.getLoadBalancerHealthCheck(TEST_LB_HEALTH_CHECK_NAME, TEST_LOAD_BALANCER_ID); + assertNull(check); + } + + @Test + public void getLoadBalancer_shouldReturnCorrectAttributes() throws CloudException, InternalException, IOException { + final Region region = new Region(); + region.setZones(Collections.singletonList(TEST_DATACENTER)); + + long dt = 0; + + try { + SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); + dt = fmt.parse("2016-06-20T09:57:34.123").getTime(); + } + catch ( ParseException ignore ) {} + final long timestamp = dt; + + new NonStrictExpectations() { + {googleComputeMock.targetPools().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = getTestTargetPoolList().getItems().get(0); + } + {googleComputeMock.forwardingRules().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestForwardingRuleList(); + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_1").execute(); + result = getTestForwardingRuleList().getItems().get(0); + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_2").execute(); + result = null; + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_3").execute(); + result = null; + } + {googleComputeMock.regions().get(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = region; + } + {googleProviderMock.parseTime(anyString); + result = timestamp;} + }; + + LoadBalancer lb = support.getLoadBalancer(TEST_LOAD_BALANCER_ID); + assertTrue(lb.getProviderOwnerId().equals(TEST_ACCOUNT_NO)); + assertTrue(lb.getProviderRegionId().equals(TEST_REGION)); + assertTrue(lb.getProviderLoadBalancerId().equals(TEST_LOAD_BALANCER_ID)); + assertTrue(lb.getCurrentState().equals(LoadBalancerState.ACTIVE)); + assertTrue(lb.getName().equals(TEST_LOAD_BALANCER_ID)); + assertTrue(lb.getDescription().equals("LB_DESCRIPTION")); + assertTrue(lb.getType().equals(LbType.EXTERNAL)); + assertTrue(lb.getAddressType().equals(LoadBalancerAddressType.DNS)); + assertTrue(lb.getAddress().equals("192.168.101.2")); + assertTrue(lb.getProviderLBHealthCheckId().equals("HC1")); + + try { + SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); + long tmp = fmt.parse("2016-06-20T09:57:34.123").getTime(); + assertTrue(lb.getCreationTimestamp() == tmp); + } + catch ( ParseException ignore ) {} + + assertTrue(lb.getProviderDataCenterIds().length == 1); + assertTrue(lb.getProviderDataCenterIds()[0].equals(TEST_DATACENTER)); + assertTrue(lb.getPublicPorts().length == 1); + assertTrue(lb.getPublicPorts()[0] == 80); + assertTrue(lb.getSupportedTraffic()[0].equals(IPVersion.IPV4)); + assertTrue(lb.getListeners().length == 1); + LbListener listener = lb.getListeners()[0]; + assertTrue(listener.getAlgorithm().equals(LbAlgorithm.SOURCE)); + assertTrue(listener.getPersistence().equals(LbPersistence.SUBNET)); + assertTrue(listener.getNetworkProtocol().equals(LbProtocol.RAW_TCP)); + assertTrue(listener.getPublicPort() == 80); + assertTrue(listener.getPrivatePort() == 80); + } + + @Test + public void addServers() throws CloudException, InternalException, IOException { + final VirtualMachine vm = new VirtualMachine(); + vm.setProviderRegionId(TEST_REGION); + vm.setTag("contentLink", "contentLink"); + + new NonStrictExpectations() { + {googleProviderMock.getComputeServices().getVirtualMachineSupport().getVirtualMachine(TEST_VM_ID); + result = vm; + } + {googleComputeMock.targetPools().addInstance(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID, (TargetPoolsAddInstanceRequest) any).execute(); + result = new Operation(); + } + }; + + support.addServers(TEST_LOAD_BALANCER_ID, TEST_VM_ID); + } + + @Test + public void removeServers() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.targetPools().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = getTestTargetPoolList().getItems().get(0); + } + {googleProviderMock.getComputeServices().getVirtualMachineSupport().getVmNameFromId(TEST_VM_ID); + result = TEST_VM_ID; + } + {googleComputeMock.targetPools().removeInstance(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID, (TargetPoolsRemoveInstanceRequest) any).execute(); + result = new Operation(); + } + }; + + support.removeServers(TEST_LOAD_BALANCER_ID, TEST_VM_ID); + } + + @Test(expected = ResourceNotFoundException.class) + public void removeServers_shouldThrowExceptionIfTargetPoolNotFound() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.targetPools().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = null; + } + }; + support.removeServers(TEST_LOAD_BALANCER_ID, TEST_VM_ID); + } + + @Test + public void listEndpoints_shouldReturnAllAvailableEndpoints() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.targetPools().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = getTestTargetPoolList().getItems().get(0); + } + {googleProviderMock.getComputeServices().getVirtualMachineSupport().getVmIdFromName(TEST_VM_ID); + result = TEST_VM_ID; + } + {googleComputeMock.targetPools().removeInstance(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID, (TargetPoolsRemoveInstanceRequest) any).execute(); + result = new Operation(); + } + }; + + Iterable list = support.listEndpoints(TEST_LOAD_BALANCER_ID); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + LoadBalancerEndpoint endpoint = resultAsList.get(0); + assertTrue(endpoint.getEndpointValue().equals(TEST_VM_ID)); + } + + @Test(expected = ResourceNotFoundException.class) + public void listEndpoints_shouldThrowExceptionIfTargetPoolNotFound() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.targetPools().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_LOAD_BALANCER_ID).execute(); + result = null; + } + }; + + support.listEndpoints(TEST_LOAD_BALANCER_ID); + } + + @Test + public void listLoadBalancerStatus() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.targetPools().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestTargetPoolList(); + } + {googleComputeMock.httpHealthChecks().get(TEST_ACCOUNT_NO, TEST_LB_HEALTH_CHECK_NAME).execute(); + result = getTestHttpHealthCheck(); + } + }; + + Iterable list = support.listLoadBalancerStatus(); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 3); + } + + @Test + public void listLoadBalancers() throws CloudException, InternalException, IOException { + final Region region = new Region(); + region.setZones(Collections.singletonList(TEST_DATACENTER)); + + long dt = 0; + + try { + SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); + dt = fmt.parse("2016-06-20T09:57:34.123").getTime(); + } + catch ( ParseException ignore ) {} + final long timestamp = dt; + + new NonStrictExpectations() { + {googleComputeMock.targetPools().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestTargetPoolList(); + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_1").execute(); + result = getTestForwardingRuleList().getItems().get(0); + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_2").execute(); + result = null; + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE_3").execute(); + result = null; + } + {googleComputeMock.regions().get(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = region; + } + {googleProviderMock.parseTime(anyString); + result = timestamp; + } + }; + + Iterable list = support.listLoadBalancerStatus(); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 3); + } +} From 98c9dca4fb3aa56e4da1df31fb2ebd9e24409f85 Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Wed, 22 Jun 2016 10:52:05 +0100 Subject: [PATCH 14/15] network unit tests --- .../cloud/google/network/NetworkSupport.java | 4 +- .../dasein/cloud/google/GoogleTestBase.java | 4 + .../cloud/google/NetworkSupportTest.java | 279 ++++++++++++++++++ 3 files changed, 285 insertions(+), 2 deletions(-) create mode 100644 src/test/java/org/dasein/cloud/google/NetworkSupportTest.java diff --git a/src/main/java/org/dasein/cloud/google/network/NetworkSupport.java b/src/main/java/org/dasein/cloud/google/network/NetworkSupport.java index a9e81de..40fd645 100644 --- a/src/main/java/org/dasein/cloud/google/network/NetworkSupport.java +++ b/src/main/java/org/dasein/cloud/google/network/NetworkSupport.java @@ -70,7 +70,7 @@ public class NetworkSupport extends AbstractVLANSupport { static private final Logger logger = Google.getLogger(NetworkSupport.class); private Google provider; - NetworkSupport(Google provider) { + public NetworkSupport(Google provider) { super(provider); this.provider = provider; } @@ -298,7 +298,7 @@ public void removeVlan(String vlanId) throws CloudException, InternalException { VLAN vlan = getVlan(vlanId); // Check if vlan contains any FW rules, and if so, revoke them. - FirewallSupport fws = new FirewallSupport(provider); + FirewallSupport fws = provider.getNetworkServices().getFirewallSupport(); Collection rules = fws.getRules("fw-" + vlanId); for (FirewallRule rule : rules) { fws.revoke(rule.getProviderRuleId()); diff --git a/src/test/java/org/dasein/cloud/google/GoogleTestBase.java b/src/test/java/org/dasein/cloud/google/GoogleTestBase.java index dc5988a..9cb7a09 100644 --- a/src/test/java/org/dasein/cloud/google/GoogleTestBase.java +++ b/src/test/java/org/dasein/cloud/google/GoogleTestBase.java @@ -22,6 +22,7 @@ import com.google.api.services.compute.Compute; import mockit.Mocked; import mockit.NonStrictExpectations; +import org.apache.log4j.Logger; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.ProviderContext; @@ -41,6 +42,8 @@ public class GoogleTestBase { Compute googleComputeMock; @Mocked GoogleMethod googleMethodMock; + @Mocked + Logger logger; final String CLOUD_NAME = "GCE"; final String TEST_ACCOUNT_NO = "12323232323"; @@ -56,6 +59,7 @@ public void setUp() throws CloudException, InternalException { { providerContextMock.getRegionId(); result = TEST_REGION; } { googleProviderMock.getGoogleCompute(); result = googleComputeMock; } { googleProviderMock.getCloudName(); result = CLOUD_NAME; } + { googleProviderMock.getLogger((Class) any); result = logger; } }; } } diff --git a/src/test/java/org/dasein/cloud/google/NetworkSupportTest.java b/src/test/java/org/dasein/cloud/google/NetworkSupportTest.java new file mode 100644 index 0000000..0d795e1 --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/NetworkSupportTest.java @@ -0,0 +1,279 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.model.Network; +import com.google.api.services.compute.model.NetworkList; +import com.google.api.services.compute.model.Operation; +import com.google.api.services.compute.model.Route; +import com.google.api.services.compute.model.RouteList; +import mockit.Mocked; +import mockit.NonStrictExpectations; +import org.apache.commons.collections.IteratorUtils; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.OperationNotSupportedException; +import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.VisibleScope; +import org.dasein.cloud.compute.VirtualMachine; +import org.dasein.cloud.google.network.FirewallSupport; +import org.dasein.cloud.google.network.NetworkSupport; +import org.dasein.cloud.network.IPVersion; +import org.dasein.cloud.network.RawAddress; +import org.dasein.cloud.network.VLAN; +import org.dasein.cloud.network.VLANState; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertTrue; + +/** + * User: daniellemayne + * Date: 21/06/2016 + * Time: 11:28 + */ +public class NetworkSupportTest extends GoogleTestBase { + private NetworkSupport support = null; + + static final String TEST_ROUTING_TABLE_ID = "TEST_ROUTING_TABLE_ID"; + static final String TEST_DESTINATIN_CIDR = "TEST_DESTINATION_CIDR"; + static final String TEST_ADDRESS = "TEST_ADDRESS"; + static final String TEST_GATEWAY = "TEST_GATEWAY"; + static final String TEST_NIC_ID = "TEST_NIC_ID"; + static final String TEST_VLAN_ID = "TEST_VLAN_ID"; + + @Mocked + FirewallSupport firewallSupport; + + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + support = new NetworkSupport(googleProviderMock); + } + + private RouteList getTestRouteList() { + Route route = new Route(); + route.setName("TEST_ROUTE"); + route.setNetwork(TEST_VLAN_ID); + route.setDestRange(TEST_DESTINATIN_CIDR); + route.setNextHopInstance(TEST_VM_ID); + + RouteList list = new RouteList(); + list.setItems(Collections.singletonList(route)); + return list; + } + + private NetworkList getTestNetworkList() { + Network network = new Network(); + network.setName(TEST_VLAN_ID); + network.setSelfLink("/networks/"+TEST_VLAN_ID); + network.setIPv4Range(TEST_DESTINATIN_CIDR); + network.setDescription("TEST_DESCRIPTION"); + + NetworkList list = new NetworkList(); + list.setItems(Collections.singletonList(network)); + return list; + } + + @Test(expected = OperationNotSupportedException.class) + public void addRouteToAddress_shouldThrowNotSupportedException() throws CloudException, InternalException { + support.addRouteToAddress(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATIN_CIDR, TEST_ADDRESS); + } + + @Test(expected = OperationNotSupportedException.class) + public void addRouteToGateway_shouldThrowNotSupportedException() throws CloudException, InternalException { + support.addRouteToGateway(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATIN_CIDR, TEST_GATEWAY); + } + + @Test(expected = OperationNotSupportedException.class) + public void addRouteToNetworkInterface_shouldThrowNotSupportedException() throws CloudException, InternalException { + support.addRouteToNetworkInterface(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATIN_CIDR, TEST_NIC_ID); + } + + @Test + public void addRouteToVirtualMachine() throws CloudException, InternalException, IOException { + final VirtualMachine vm = new VirtualMachine(); + vm.setTag("contentLink", "contentLink"); + vm.setPrivateAddresses(new RawAddress(TEST_ADDRESS)); + + new NonStrictExpectations() { + {googleProviderMock.getComputeServices().getVirtualMachineSupport().getVirtualMachine(TEST_VM_ID); + result = vm; + } + {googleComputeMock.routes().insert(TEST_ACCOUNT_NO, (Route) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationTarget(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, "", "", false); + result = "NEW_ROUTE"; + } + {googleComputeMock.routes().get(TEST_ACCOUNT_NO, "NEW_ROUTE").execute(); + result = getTestRouteList().getItems().get(0); + } + }; + + org.dasein.cloud.network.Route route = support.addRouteToVirtualMachine(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATIN_CIDR, TEST_VM_ID); + assertTrue(route.getGatewayVirtualMachineId().equals(TEST_VM_ID)); + assertTrue(route.getDestinationCidr().equals(TEST_DESTINATIN_CIDR)); + assertTrue(route.getGatewayOwnerId().equals(TEST_ACCOUNT_NO)); + } + + @Test(expected = OperationNotSupportedException.class) + public void createVlan_shouldThrowExceptionIfCreatingVlansIsNotSupported() throws CloudException, InternalException { + new NonStrictExpectations(NetworkSupport.class) { + {support.getCapabilities().allowsNewVlanCreation(); + result = false; + } + }; + support.createVlan(TEST_DESTINATIN_CIDR, "TEST_VLAN_NAME", "TEST_DESCRIPTION", "TEST_DOMAIN", new String[]{"192.168.1.1"}, new String[]{"192.168.1.1"}); + } + + @Test(expected = InternalException.class) + public void createVlan_shouldThrowExceptionIfRegionNotSet() throws CloudException, InternalException { + new NonStrictExpectations() { + {providerContextMock.getRegionId(); + result = null; + } + }; + support.createVlan(TEST_DESTINATIN_CIDR, "TEST_VLAN_NAME", "TEST_DESCRIPTION", "TEST_DOMAIN", new String[]{"192.168.1.1"}, new String[]{"192.168.1.1"}); + } + + @Test + public void createVlan() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.networks().insert(TEST_ACCOUNT_NO, (Network) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationTarget(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, "", "", false); + result = TEST_VLAN_ID; + } + {googleComputeMock.networks().get(TEST_ACCOUNT_NO, TEST_VLAN_ID).execute(); + result = getTestNetworkList().getItems().get(0); + } + }; + VLAN vlan = support.createVlan(TEST_DESTINATIN_CIDR, TEST_VLAN_ID, "TEST_DESCRIPTION", "TEST_DOMAIN", new String[]{"192.168.1.1"}, new String[]{"192.168.1.1"}); + assertTrue(vlan.getProviderVlanId().equals(TEST_VLAN_ID)); + } + + @Test(expected = OperationNotSupportedException.class) + public void getRoutingTableForVlan_shouldThrowNotSupportedException() throws CloudException, InternalException { + support.getRoutingTableForVlan(TEST_VLAN_ID); + } + + @Test + public void getVlan_shouldReturnCorrectAttributes() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.networks().get(TEST_ACCOUNT_NO, TEST_VLAN_ID).execute(); + result = getTestNetworkList().getItems().get(0); + } + }; + + VLAN vlan = support.getVlan(TEST_VLAN_ID); + assertTrue(vlan.getName().equals(TEST_VLAN_ID)); + assertTrue(vlan.getProviderVlanId().equals(TEST_VLAN_ID)); + assertTrue(vlan.getProviderOwnerId().equals(TEST_ACCOUNT_NO)); + assertTrue(vlan.getTag("contentLink").toString().equals("/networks/"+TEST_VLAN_ID)); + assertTrue(vlan.getCidr().equals(TEST_DESTINATIN_CIDR)); + assertTrue(vlan.getDescription().equals("TEST_DESCRIPTION")); + assertTrue(vlan.getVisibleScope().equals(VisibleScope.ACCOUNT_GLOBAL)); + assertTrue(vlan.getCurrentState().equals(VLANState.AVAILABLE)); + assertTrue(vlan.getSupportedTraffic().length == 1); + assertTrue(vlan.getSupportedTraffic()[0].equals(IPVersion.IPV4)); + } + + @Test(expected = OperationNotSupportedException.class) + public void listFirewallIdsForNic_shouldThrowNotSupportedException() throws CloudException, InternalException { + support.listFirewallIdsForNIC(TEST_NIC_ID); + } + + @Test(expected = OperationNotSupportedException.class) + public void getInternetGatewayById_shouldThrowNotSupportedException() throws CloudException, InternalException { + support.getInternetGatewayById(TEST_GATEWAY); + } + + @Test(expected = OperationNotSupportedException.class) + public void getAttachedInternetGatewayId_shouldThrowNotSupportedException() throws CloudException, InternalException { + support.getAttachedInternetGatewayId(TEST_VLAN_ID); + } + + @Test(expected = OperationNotSupportedException.class) + public void removeInternetGatewayById_shouldThrowNotSupportedException() throws CloudException, InternalException { + support.removeInternetGatewayById(TEST_GATEWAY); + } + + @Test + public void listVlanStatus() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.networks().list(TEST_ACCOUNT_NO).execute(); + result = getTestNetworkList(); + } + }; + + Iterable list = support.listVlanStatus(); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + assertTrue(resultAsList.get(0).getResourceStatus().equals(VLANState.AVAILABLE)); + } + + @Test + public void listVlans() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.networks().list(TEST_ACCOUNT_NO).execute(); + result = getTestNetworkList(); + } + }; + + Iterable list = support.listVlans(); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + } + + @Test + public void removeVlan() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.networks().get(TEST_ACCOUNT_NO, TEST_VLAN_ID).execute(); + result = getTestNetworkList().getItems().get(0); + } + {googleProviderMock.getNetworkServices().getFirewallSupport(); + result = firewallSupport; + } + {firewallSupport.getRules(anyString); + result = Collections.emptyList(); + } + {googleComputeMock.routes().list(TEST_ACCOUNT_NO).execute(); + result = getTestRouteList(); + } + {googleComputeMock.routes().delete(TEST_ACCOUNT_NO, "TEST_ROUTE").execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, "", ""); + result = true; + } + {googleComputeMock.networks().delete(TEST_ACCOUNT_NO, TEST_VLAN_ID).execute(); + result = new Operation(); + } + }; + + support.removeVlan(TEST_VLAN_ID); + } +} From 1a63368408668a5ed69d65fc29ae778d77497a2d Mon Sep 17 00:00:00 2001 From: Danielle Mayne Date: Tue, 28 Jun 2016 16:24:27 +0100 Subject: [PATCH 15/15] vpn unit tests --- .../cloud/google/network/VpnSupport.java | 4 +- .../cloud/google/NetworkSupportTest.java | 24 +- .../dasein/cloud/google/VpnSupportTest.java | 433 ++++++++++++++++++ 3 files changed, 446 insertions(+), 15 deletions(-) create mode 100644 src/test/java/org/dasein/cloud/google/VpnSupportTest.java diff --git a/src/main/java/org/dasein/cloud/google/network/VpnSupport.java b/src/main/java/org/dasein/cloud/google/network/VpnSupport.java index 0216fac..5048c25 100644 --- a/src/main/java/org/dasein/cloud/google/network/VpnSupport.java +++ b/src/main/java/org/dasein/cloud/google/network/VpnSupport.java @@ -49,7 +49,7 @@ public class VpnSupport extends AbstractVpnSupport { private Google provider; private VpnCapabilities capabilities; - protected VpnSupport(Google provider) { + public VpnSupport(Google provider) { super(provider); this.provider = provider; } @@ -70,8 +70,6 @@ public Vpn createVpn(VpnCreateOptions vpnLaunchOptions) throws CloudException, I APITrace.begin(provider, "createVpn"); Vpn vpn = new Vpn(); try { - vpn.setName(vpnLaunchOptions.getName()); - vpn.setDescription(vpnLaunchOptions.getDescription()); Compute gce = getProvider().getGoogleCompute(); try { GoogleMethod method = new GoogleMethod(getProvider()); diff --git a/src/test/java/org/dasein/cloud/google/NetworkSupportTest.java b/src/test/java/org/dasein/cloud/google/NetworkSupportTest.java index 0d795e1..95779a5 100644 --- a/src/test/java/org/dasein/cloud/google/NetworkSupportTest.java +++ b/src/test/java/org/dasein/cloud/google/NetworkSupportTest.java @@ -57,7 +57,7 @@ public class NetworkSupportTest extends GoogleTestBase { private NetworkSupport support = null; static final String TEST_ROUTING_TABLE_ID = "TEST_ROUTING_TABLE_ID"; - static final String TEST_DESTINATIN_CIDR = "TEST_DESTINATION_CIDR"; + static final String TEST_DESTINATION_CIDR = "TEST_DESTINATION_CIDR"; static final String TEST_ADDRESS = "TEST_ADDRESS"; static final String TEST_GATEWAY = "TEST_GATEWAY"; static final String TEST_NIC_ID = "TEST_NIC_ID"; @@ -76,7 +76,7 @@ private RouteList getTestRouteList() { Route route = new Route(); route.setName("TEST_ROUTE"); route.setNetwork(TEST_VLAN_ID); - route.setDestRange(TEST_DESTINATIN_CIDR); + route.setDestRange(TEST_DESTINATION_CIDR); route.setNextHopInstance(TEST_VM_ID); RouteList list = new RouteList(); @@ -88,7 +88,7 @@ private NetworkList getTestNetworkList() { Network network = new Network(); network.setName(TEST_VLAN_ID); network.setSelfLink("/networks/"+TEST_VLAN_ID); - network.setIPv4Range(TEST_DESTINATIN_CIDR); + network.setIPv4Range(TEST_DESTINATION_CIDR); network.setDescription("TEST_DESCRIPTION"); NetworkList list = new NetworkList(); @@ -98,17 +98,17 @@ private NetworkList getTestNetworkList() { @Test(expected = OperationNotSupportedException.class) public void addRouteToAddress_shouldThrowNotSupportedException() throws CloudException, InternalException { - support.addRouteToAddress(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATIN_CIDR, TEST_ADDRESS); + support.addRouteToAddress(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATION_CIDR, TEST_ADDRESS); } @Test(expected = OperationNotSupportedException.class) public void addRouteToGateway_shouldThrowNotSupportedException() throws CloudException, InternalException { - support.addRouteToGateway(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATIN_CIDR, TEST_GATEWAY); + support.addRouteToGateway(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATION_CIDR, TEST_GATEWAY); } @Test(expected = OperationNotSupportedException.class) public void addRouteToNetworkInterface_shouldThrowNotSupportedException() throws CloudException, InternalException { - support.addRouteToNetworkInterface(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATIN_CIDR, TEST_NIC_ID); + support.addRouteToNetworkInterface(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATION_CIDR, TEST_NIC_ID); } @Test @@ -132,9 +132,9 @@ public void addRouteToVirtualMachine() throws CloudException, InternalException, } }; - org.dasein.cloud.network.Route route = support.addRouteToVirtualMachine(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATIN_CIDR, TEST_VM_ID); + org.dasein.cloud.network.Route route = support.addRouteToVirtualMachine(TEST_ROUTING_TABLE_ID, IPVersion.IPV4, TEST_DESTINATION_CIDR, TEST_VM_ID); assertTrue(route.getGatewayVirtualMachineId().equals(TEST_VM_ID)); - assertTrue(route.getDestinationCidr().equals(TEST_DESTINATIN_CIDR)); + assertTrue(route.getDestinationCidr().equals(TEST_DESTINATION_CIDR)); assertTrue(route.getGatewayOwnerId().equals(TEST_ACCOUNT_NO)); } @@ -145,7 +145,7 @@ public void createVlan_shouldThrowExceptionIfCreatingVlansIsNotSupported() throw result = false; } }; - support.createVlan(TEST_DESTINATIN_CIDR, "TEST_VLAN_NAME", "TEST_DESCRIPTION", "TEST_DOMAIN", new String[]{"192.168.1.1"}, new String[]{"192.168.1.1"}); + support.createVlan(TEST_DESTINATION_CIDR, "TEST_VLAN_NAME", "TEST_DESCRIPTION", "TEST_DOMAIN", new String[]{"192.168.1.1"}, new String[]{"192.168.1.1"}); } @Test(expected = InternalException.class) @@ -155,7 +155,7 @@ public void createVlan_shouldThrowExceptionIfRegionNotSet() throws CloudExceptio result = null; } }; - support.createVlan(TEST_DESTINATIN_CIDR, "TEST_VLAN_NAME", "TEST_DESCRIPTION", "TEST_DOMAIN", new String[]{"192.168.1.1"}, new String[]{"192.168.1.1"}); + support.createVlan(TEST_DESTINATION_CIDR, "TEST_VLAN_NAME", "TEST_DESCRIPTION", "TEST_DOMAIN", new String[]{"192.168.1.1"}, new String[]{"192.168.1.1"}); } @Test @@ -171,7 +171,7 @@ public void createVlan() throws CloudException, InternalException, IOException { result = getTestNetworkList().getItems().get(0); } }; - VLAN vlan = support.createVlan(TEST_DESTINATIN_CIDR, TEST_VLAN_ID, "TEST_DESCRIPTION", "TEST_DOMAIN", new String[]{"192.168.1.1"}, new String[]{"192.168.1.1"}); + VLAN vlan = support.createVlan(TEST_DESTINATION_CIDR, TEST_VLAN_ID, "TEST_DESCRIPTION", "TEST_DOMAIN", new String[]{"192.168.1.1"}, new String[]{"192.168.1.1"}); assertTrue(vlan.getProviderVlanId().equals(TEST_VLAN_ID)); } @@ -193,7 +193,7 @@ public void getVlan_shouldReturnCorrectAttributes() throws CloudException, Inter assertTrue(vlan.getProviderVlanId().equals(TEST_VLAN_ID)); assertTrue(vlan.getProviderOwnerId().equals(TEST_ACCOUNT_NO)); assertTrue(vlan.getTag("contentLink").toString().equals("/networks/"+TEST_VLAN_ID)); - assertTrue(vlan.getCidr().equals(TEST_DESTINATIN_CIDR)); + assertTrue(vlan.getCidr().equals(TEST_DESTINATION_CIDR)); assertTrue(vlan.getDescription().equals("TEST_DESCRIPTION")); assertTrue(vlan.getVisibleScope().equals(VisibleScope.ACCOUNT_GLOBAL)); assertTrue(vlan.getCurrentState().equals(VLANState.AVAILABLE)); diff --git a/src/test/java/org/dasein/cloud/google/VpnSupportTest.java b/src/test/java/org/dasein/cloud/google/VpnSupportTest.java new file mode 100644 index 0000000..79de62b --- /dev/null +++ b/src/test/java/org/dasein/cloud/google/VpnSupportTest.java @@ -0,0 +1,433 @@ +/** + * Copyright (C) 2009-2016 Dell, Inc. + * See annotations for authorship information + *

+ * ==================================================================== + * 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 org.dasein.cloud.google; + +import com.google.api.services.compute.model.ForwardingRule; +import com.google.api.services.compute.model.ForwardingRuleList; +import com.google.api.services.compute.model.Network; +import com.google.api.services.compute.model.Operation; +import com.google.api.services.compute.model.Route; +import com.google.api.services.compute.model.RouteList; +import com.google.api.services.compute.model.TargetVpnGateway; +import com.google.api.services.compute.model.TargetVpnGatewayList; +import com.google.api.services.compute.model.VpnTunnel; +import com.google.api.services.compute.model.VpnTunnelList; +import mockit.NonStrictExpectations; +import org.apache.commons.collections.IteratorUtils; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.OperationNotSupportedException; +import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.dc.Region; +import org.dasein.cloud.google.network.VpnSupport; +import org.dasein.cloud.network.IPVersion; +import org.dasein.cloud.network.Vpn; +import org.dasein.cloud.network.VpnConnection; +import org.dasein.cloud.network.VpnConnectionState; +import org.dasein.cloud.network.VpnCreateOptions; +import org.dasein.cloud.network.VpnGateway; +import org.dasein.cloud.network.VpnGatewayCreateOptions; +import org.dasein.cloud.network.VpnGatewayState; +import org.dasein.cloud.network.VpnProtocol; +import org.dasein.cloud.network.VpnState; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * User: daniellemayne + * Date: 22/06/2016 + * Time: 12:19 + */ +public class VpnSupportTest extends GoogleTestBase { + private VpnSupport support = null; + + static final String TEST_VPN_ID = "TEST_VPN_ID"; + static final String TEST_VLAN_ID = "TEST_VLAN_ID"; + static final String TEST_IP_ADDRESS = "192.168.101.1"; + static final String TEST_VPN_GATEWAY = "TEST_VPN_GATEWAY"; + + @Before + public void setUp() throws CloudException, InternalException { + super.setUp(); + support = new VpnSupport(googleProviderMock); + } + + private RouteList getTestRouteList() { + Route route = new Route(); + route.setName(TEST_VPN_ID); + route.setNetwork(TEST_VLAN_ID); + route.setDestRange("192.168.101.0"); + route.setNextHopInstance(TEST_VM_ID); + route.setNextHopVpnTunnel("VPN_TUNNEL"); + + RouteList list = new RouteList(); + list.setItems(Collections.singletonList(route)); + return list; + } + + private VpnTunnelList getTestVpnTunnelList() { + VpnTunnel vt = new VpnTunnel(); + vt.setName(TEST_VPN_GATEWAY); + vt.setId(new BigInteger("112233")); + vt.setDescription(TEST_VPN_GATEWAY+" DESCRIPTION"); + vt.setRegion(TEST_REGION); + vt.setPeerIp(TEST_IP_ADDRESS); + vt.setIkeVersion(1); + vt.setStatus("DONE"); + vt.setTargetVpnGateway(TEST_VPN_ID); + + VpnTunnelList list = new VpnTunnelList(); + list.setItems(Collections.singletonList(vt)); + return list; + } + + private TargetVpnGatewayList getTestTargetVpnGatewayList() { + TargetVpnGateway tvg = new TargetVpnGateway(); + tvg.setName(TEST_VPN_ID); + tvg.setDescription("TEST_DESCRIPTION"); + tvg.setId(new BigInteger("11223344")); + tvg.setNetwork(TEST_VLAN_ID); + tvg.setSelfLink("TEST_TARGET/TEST_LOAD_BALANCER_ID"); + TargetVpnGatewayList list = new TargetVpnGatewayList(); + list.setItems(Collections.singletonList(tvg)); + return list; + } + + private ForwardingRuleList getTestForwardingRuleList() { + ForwardingRule fr1 = new ForwardingRule(); + fr1.setName("TEST_FORWARDING_RULE_1"); + fr1.setTarget("TEST_TARGET/TEST_LOAD_BALANCER_ID"); + fr1.setIPProtocol("TCP"); + fr1.setPortRange("80-80"); + fr1.setIPAddress("192.168.101.2"); + + List list = new ArrayList<>(); + list.add(fr1); + + ForwardingRuleList frList = new ForwardingRuleList(); + frList.setItems(list); + + return frList; + } + + @Test(expected = OperationNotSupportedException.class) + public void attachToVlan_shouldThrowNotSupportedException() throws CloudException, InternalException { + support.attachToVlan(TEST_VPN_ID, TEST_VLAN_ID); + } + + @Test + public void createVpn_shouldReturnNewVpnWithCorrectName() throws CloudException, InternalException, IOException { + final VpnCreateOptions options = VpnCreateOptions.getInstance(TEST_VPN_ID, "TEST_DESCRIPTION", VpnProtocol.OPEN_VPN).withProviderVlanId(TEST_VLAN_ID); + + final Network network = new Network(); + network.setName(TEST_VLAN_ID); + network.setSelfLink("/networks/"+TEST_VLAN_ID); + network.setIPv4Range("TEST_DESTINATION_CIDR"); + network.setDescription("TEST_DESCRIPTION"); + + new NonStrictExpectations() { + {googleComputeMock.networks().get(TEST_ACCOUNT_NO, TEST_VLAN_ID).execute(); + result = network; + } + {googleComputeMock.targetVpnGateways().insert(TEST_ACCOUNT_NO, TEST_REGION, (TargetVpnGateway) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, "", ""); + result = true; + } + {googleProviderMock.getNetworkServices().getIpAddressSupport().request(IPVersion.IPV4); + result = TEST_IP_ADDRESS; + } + {googleProviderMock.getNetworkServices().getIpAddressSupport().getIpAddress(TEST_IP_ADDRESS).getRawAddress().getIpAddress(); + result = TEST_IP_ADDRESS; + } + {googleComputeMock.getBaseUrl(); + result = "/"; + } + {googleComputeMock.forwardingRules().insert(TEST_ACCOUNT_NO, TEST_REGION, (ForwardingRule) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, null); + result = true; + } + }; + Vpn vpn = support.createVpn(options); + assertTrue(vpn.getName().equals(TEST_VPN_ID)); + assertTrue(vpn.getProtocol().equals(VpnProtocol.OPEN_VPN)); + } + + @Test + public void deleteVpn() throws CloudException, InternalException, IOException { + final TargetVpnGateway tvg = new TargetVpnGateway(); + tvg.setForwardingRules(Collections.singletonList("TEST_FORWARDING_RULE")); + + final ForwardingRule fr = new ForwardingRule(); + fr.setIPAddress("192.168.101.0"); + + new NonStrictExpectations() { + {googleComputeMock.targetVpnGateways().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_VPN_ID).execute(); + result = tvg; + } + {googleComputeMock.routes().list(TEST_ACCOUNT_NO).execute(); + result = getTestRouteList(); + } + {googleComputeMock.routes().delete(TEST_ACCOUNT_NO, TEST_VPN_ID).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, null, null); + result = true; + } + {googleComputeMock.forwardingRules().get(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE").execute(); + result = fr; + } + {googleComputeMock.forwardingRules().delete(TEST_ACCOUNT_NO, TEST_REGION, "TEST_FORWARDING_RULE").execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, null); + result = true; + } + {googleProviderMock.getNetworkServices().getIpAddressSupport().getIpAddressIdFromIP(TEST_IP_ADDRESS, TEST_REGION); + result = "TEST_IP_ADDRESS_ID"; + } + {googleProviderMock.getNetworkServices().getIpAddressSupport().releaseFromPool("TEST_IP_ADDRESS_ID"); + } + {googleComputeMock.targetVpnGateways().delete(TEST_ACCOUNT_NO, TEST_REGION, TEST_VPN_ID).execute(); + result = new Operation(); + } + }; + + support.deleteVpn(TEST_VPN_ID); + } + + @Test + public void createVpnGateway() throws CloudException, InternalException, IOException { + final VpnGatewayCreateOptions options = VpnGatewayCreateOptions.getInstance(TEST_VPN_GATEWAY, TEST_VPN_GATEWAY+" DESCRIPTION", VpnProtocol.IKE_V1, TEST_IP_ADDRESS); + options.withSharedSecret("SECRET"); + options.withVlanName(TEST_VLAN_ID); + options.withCidr("192.168.101.0"); + + new NonStrictExpectations() { + {googleComputeMock.vpnTunnels().insert(TEST_ACCOUNT_NO, TEST_REGION, (VpnTunnel) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, null); + result = true; + } + {googleComputeMock.routes().insert(TEST_ACCOUNT_NO, (Route) any).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.GLOBAL_OPERATION, null, null); + result = true; + } + {googleComputeMock.vpnTunnels().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_VPN_GATEWAY).execute(); + result = getTestVpnTunnelList().getItems().get(0); + } + }; + + VpnGateway vg = support.createVpnGateway(options); + assertNotNull(vg); + assertTrue(vg.getName().equals(TEST_VPN_GATEWAY)); + assertTrue(vg.getProtocol().equals(VpnProtocol.IKE_V1)); + } + + @Test(expected = OperationNotSupportedException.class) + public void connectToGateway_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.connectToGateway(TEST_VPN_ID, TEST_VPN_GATEWAY); + } + + @Test(expected = OperationNotSupportedException.class) + public void disconnectFromGateway_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.disconnectFromGateway(TEST_VPN_ID, TEST_VPN_GATEWAY); + } + + @Test + public void deleteVpnGateway() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.vpnTunnels().delete(TEST_ACCOUNT_NO, TEST_REGION, TEST_VPN_GATEWAY).execute(); + result = new Operation(); + } + {googleMethodMock.getOperationComplete(providerContextMock, (Operation) any, GoogleOperationType.REGION_OPERATION, TEST_REGION, null); + result = true; + } + }; + + support.deleteVpnGateway(TEST_VPN_GATEWAY); + } + + @Test(expected = OperationNotSupportedException.class) + public void detachFromVlan_shouldThrowOperationNotSupportedException() throws CloudException, InternalException { + support.detachFromVlan(TEST_VPN_ID, TEST_VLAN_ID); + } + + @Test + public void getGateway_shouldReturnCorrectAttributes() throws CloudException, InternalException, IOException { + new NonStrictExpectations() { + {googleComputeMock.vpnTunnels().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_VPN_GATEWAY).execute(); + result = getTestVpnTunnelList().getItems().get(0); + } + }; + VpnGateway gateway = support.getGateway(TEST_VPN_GATEWAY); + assertNotNull(gateway); + assertTrue(gateway.getName().equals(TEST_VPN_GATEWAY)); + assertTrue(gateway.getDescription().equals(TEST_VPN_GATEWAY+" DESCRIPTION")); + assertTrue(gateway.getProviderRegionId().equals(TEST_REGION)); + assertTrue(gateway.getEndpoint().equals(TEST_IP_ADDRESS)); + assertTrue(gateway.getProtocol().equals(VpnProtocol.IKE_V1)); + assertTrue(gateway.getCurrentState().equals(VpnGatewayState.AVAILABLE)); + } + + @Test + public void getVpn_shouldReturnCorrectAttributes() throws CloudException, InternalException, IOException { + final Region r = new Region(); + r.setName(TEST_REGION); + + new NonStrictExpectations() { + {googleProviderMock.getDataCenterServices().listRegions(); + result = Collections.singletonList(r); + } + {googleComputeMock.targetVpnGateways().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestTargetVpnGatewayList();} + }; + + Vpn vpn = support.getVpn(TEST_VPN_ID); + assertNotNull(vpn); + assertTrue(vpn.getName().equals(TEST_VPN_ID)); + assertTrue(vpn.getDescription().equals("TEST_DESCRIPTION")); + assertTrue(vpn.getProviderVpnId().equals("11223344")); + } + + @Test(expected = OperationNotSupportedException.class) + public void listGatewayConnections_shouldThrowOperationNotSupportedException() throws CloudException, InternalException{ + support.listGatewayConnections(TEST_VPN_GATEWAY); + } + + @Test(expected = OperationNotSupportedException.class) + public void listGatewaStatus_shouldThrowOperationNotSupportedException() throws CloudException, InternalException{ + support.listGatewayStatus(); + } + + @Test(expected = OperationNotSupportedException.class) + public void listGateways_shouldThrowOperationNotSupportedException() throws CloudException, InternalException{ + support.listGateways(); + } + + @Test(expected = OperationNotSupportedException.class) + public void listGatewaysWithBgpAsn_shouldThrowOperationNotSupportedException() throws CloudException, InternalException{ + support.listGatewaysWithBgpAsn("BGP_ASN"); + } + + @Test + public void listVpnConnections_shouldReturnCorrectAttributes() throws CloudException, InternalException, IOException { + final Vpn vpn = new Vpn(); + vpn.setName(TEST_VPN_ID); + + final Region r = new Region(); + r.setName(TEST_REGION); + + new NonStrictExpectations(VpnSupport.class) { + {support.getVpn(TEST_VPN_ID); + result = vpn; + } + {googleProviderMock.getDataCenterServices().listRegions(); + result = Collections.singletonList(r); + } + {googleComputeMock.vpnTunnels().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestVpnTunnelList(); + } + }; + + Iterable list = support.listVpnConnections(TEST_VPN_ID); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + VpnConnection vc = resultAsList.get(0); + assertTrue(vc.getProtocol().equals(VpnProtocol.IKE_V1)); + assertTrue(vc.getCurrentState().equals(VpnConnectionState.PENDING)); + assertTrue(vc.getProviderGatewayId().equals(TEST_IP_ADDRESS)); + assertTrue(vc.getProviderVpnConnectionId().equals(TEST_VPN_GATEWAY)); + assertTrue(vc.getProviderVpnId().equals(TEST_VPN_ID)); + } + + @Test + public void listVpnStatus() throws CloudException, InternalException, IOException { + final Region r = new Region(); + r.setName(TEST_REGION); + + + new NonStrictExpectations(VpnSupport.class) { + {googleProviderMock.getDataCenterServices().listRegions(); + result = Collections.singletonList(r); + } + {googleComputeMock.vpnTunnels().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestVpnTunnelList(); + } + }; + + Iterable list = support.listVpnStatus(); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + assertTrue(resultAsList.get(0).getResourceStatus().equals(VpnState.PENDING)); + } + + @Test + public void listVpns() throws CloudException, InternalException, IOException { + final Region r = new Region(); + r.setName(TEST_REGION); + + new NonStrictExpectations(VpnSupport.class) { + {googleProviderMock.getDataCenterServices().listRegions(); + result = Collections.singletonList(r); + } + {googleComputeMock.vpnTunnels().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestVpnTunnelList(); + } + {googleComputeMock.targetVpnGateways().get(TEST_ACCOUNT_NO, TEST_REGION, TEST_VPN_ID).execute(); + result = getTestTargetVpnGatewayList().getItems().get(0); + } + {googleComputeMock.forwardingRules().list(TEST_ACCOUNT_NO, TEST_REGION).execute(); + result = getTestForwardingRuleList(); + } + }; + + Iterable list = support.listVpns(); + assertNotNull(list); + List resultAsList = IteratorUtils.toList(list.iterator()); + assertTrue(resultAsList.size() == 1); + Vpn vpn = resultAsList.get(0); + assertTrue(vpn.getName().equals(TEST_VPN_GATEWAY)); + assertTrue(vpn.getDescription().equals(TEST_VPN_GATEWAY+" DESCRIPTION")); + assertTrue(vpn.getProviderVpnId().equals("112233")); + assertTrue(vpn.getProtocol().equals(VpnProtocol.IKE_V1)); + assertTrue(vpn.getCurrentState().equals(VpnState.PENDING)); + assertTrue(vpn.getProviderVlanIds().length == 1); + assertTrue(vpn.getProviderVlanIds()[0].equals(TEST_VLAN_ID)); + assertTrue(vpn.getProviderVpnIp().equals("192.168.101.2")); + } +}