From 76440c0ea26b57cc71876738c5c16f3e8445c73f Mon Sep 17 00:00:00 2001 From: mariapavlova Date: Thu, 14 Jan 2016 21:50:40 +0000 Subject: [PATCH 1/7] LB tests --- .../cloud/openstack/nova/os/NovaMethod.java | 34 +- .../os/network/LoadBalancerSupportImpl.java | 119 ++-- .../openstack/nova/os/NovaMethodTest.java | 418 +++++++++++++ .../openstack/nova/os/OpenstackTest.java | 31 + .../nova/os/compute/NovaServerTest.java | 26 +- .../network/LoadBalancerSupportImplTest.java | 565 ++++++++++++++++++ .../nova/os/network/QuantumTest.java | 144 +---- .../fixtures/lb/create_health_monitor.json | 19 + .../nova/fixtures/lb/get_health_check.json | 22 + .../nova/fixtures/lb/get_health_checks.json | 22 + .../nova/fixtures/lb/get_member.json | 11 + .../resources/nova/fixtures/lb/get_pools.json | 24 + .../resources/nova/fixtures/lb/get_vips.json | 23 + .../nova/fixtures/lb/list_health_checks.json | 35 ++ 14 files changed, 1279 insertions(+), 214 deletions(-) create mode 100644 src/test/java/org/dasein/cloud/openstack/nova/os/NovaMethodTest.java create mode 100644 src/test/java/org/dasein/cloud/openstack/nova/os/OpenstackTest.java create mode 100644 src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java create mode 100644 src/test/resources/nova/fixtures/lb/create_health_monitor.json create mode 100644 src/test/resources/nova/fixtures/lb/get_health_check.json create mode 100644 src/test/resources/nova/fixtures/lb/get_health_checks.json create mode 100644 src/test/resources/nova/fixtures/lb/get_member.json create mode 100644 src/test/resources/nova/fixtures/lb/get_pools.json create mode 100644 src/test/resources/nova/fixtures/lb/get_vips.json create mode 100644 src/test/resources/nova/fixtures/lb/list_health_checks.json diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/NovaMethod.java b/src/main/java/org/dasein/cloud/openstack/nova/os/NovaMethod.java index 534a6a7..ea306c0 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/NovaMethod.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/NovaMethod.java @@ -36,11 +36,13 @@ import java.util.HashMap; import java.util.Map; +import org.dasein.cloud.openstack.nova.os.*; + public class NovaMethod extends AbstractMethod { public NovaMethod(NovaOpenStack provider) { super(provider); } public void deleteServers(@Nonnull final String resource, @Nonnull final String resourceId) throws CloudException, InternalException { - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String endpoint = context.getComputeUrl(); if( endpoint == null ) { @@ -62,7 +64,7 @@ public void deleteServers(@Nonnull final String resource, @Nonnull final String } public void deleteNetworks(@Nonnull final String resource, @Nonnull final String resourceId) throws CloudException, InternalException { - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String endpoint = context.getNetworkUrl(); if( endpoint == null ) { @@ -87,7 +89,7 @@ public void deleteNetworks(@Nonnull final String resource, @Nonnull final String } public @Nullable JSONObject getPorts(@Nonnull final String resource, @Nonnull final String resourceId) throws CloudException, InternalException { - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String endpoint = context.getComputeUrl(); if( endpoint == null ) { @@ -122,9 +124,13 @@ public void deleteNetworks(@Nonnull final String resource, @Nonnull final String } } } - + + public AuthenticationContext getAuthenticationContext() throws CloudException, InternalException { + return provider.getAuthenticationContext(); + } + public @Nullable JSONObject getServers(@Nonnull final String resource, @Nullable final String resourceId, final boolean suffix) throws CloudException, InternalException { - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String endpoint = context.getComputeUrl(); if( endpoint == null ) { @@ -167,7 +173,7 @@ else if( suffix ) { } public @Nullable JSONObject getNetworks(@Nonnull final String resource, @Nullable final String resourceId, final boolean suffix, final String query) throws CloudException, InternalException { - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String endpoint = context.getNetworkUrl(); if( endpoint == null ) { @@ -212,7 +218,7 @@ else if( suffix ) { } public @Nullable String postServersForString(@Nonnull final String resource, @Nullable final String resourceId, @Nonnull final JSONObject body, final boolean suffix) throws CloudException, InternalException { - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String resourceUri = resource; if( resourceId != null ) { @@ -239,7 +245,7 @@ else if( suffix ) { } public @Nullable JSONObject postServers(@Nonnull final String resource, @Nullable final String resourceId, @Nonnull final JSONObject body, final boolean suffix) throws CloudException, InternalException { - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String resourceUri = resource; if( resourceId != null ) { @@ -276,7 +282,7 @@ else if( suffix ) { } public @Nullable JSONObject postNetworks(@Nonnull final String resource, @Nullable final String resourceId, @Nonnull final JSONObject body, @Nullable final String action) throws CloudException, InternalException { - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String resourceUri = resource; if( resourceId != null ) { @@ -317,7 +323,7 @@ else if( suffix ) { } public @Nullable JSONObject putNetworks(@Nonnull final String resource, @Nullable final String resourceId, @Nonnull final JSONObject body, final String action) throws CloudException, InternalException { - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String resourceUri = resource; if( resourceId != null ) { @@ -362,7 +368,7 @@ else if( suffix ) { } public @Nullable String getHPCDN(@Nullable final String resourceId) throws CloudException, InternalException { - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String endpoint = context.getServiceUrl(HPCDN.SERVICE); if( endpoint == null ) { @@ -385,7 +391,7 @@ else if( suffix ) { public void putHPCDN(final String container) throws CloudException, InternalException { Map headers = new HashMap(); - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String endpoint = context.getServiceUrl(HPCDN.SERVICE); if( endpoint == null ) { @@ -416,7 +422,7 @@ public void putHPCDN(final String container) throws CloudException, InternalExce } public void postHPCDN(@Nonnull final String container, @Nonnull final Map headers) throws CloudException, InternalException { - AuthenticationContext context = provider.getAuthenticationContext(); + AuthenticationContext context = getAuthenticationContext(); String endpoint = context.getServiceUrl(HPCDN.SERVICE); if( endpoint == null ) { @@ -441,7 +447,7 @@ public void postHPCDN(@Nonnull final String container, @Nonnull final Map 0 ) { @@ -123,12 +124,11 @@ public boolean isSubscribed() throws CloudException, InternalException { Map json = new HashMap(); json.put("pool", lb); - NovaMethod method = new NovaMethod(getProvider()); if( logger.isTraceEnabled() ) { logger.trace("create(): Posting new load balancer data..."); } - JSONObject result = method.postNetworks(getLoadBalancersResource(), null, new JSONObject(json), false); + JSONObject result = getMethod().postNetworks(getLoadBalancersResource(), null, new JSONObject(json), false); if( result == null ) { logger.error("create(): Method executed successfully, but no load balancer was created"); @@ -143,7 +143,7 @@ public boolean isSubscribed() throws CloudException, InternalException { createListener(lbId, subnetId, listener); } catch ( Throwable e ) { - method.deleteNetworks(getLoadBalancersResource(), lbId); + getMethod().deleteNetworks(getLoadBalancersResource(), lbId); throw new CloudException(e); } if( options.getEndpoints() != null ) { @@ -172,10 +172,9 @@ public boolean isSubscribed() throws CloudException, InternalException { @Override public @Nonnull Iterable listLoadBalancerStatus() throws CloudException, InternalException { - NovaMethod method = new NovaMethod(getProvider()); // Unlike Horizon the OS LB API returns all tenants' load balancers, so we must filter - JSONObject result = method.getNetworks(getLoadBalancersResource(), null, false, - "?tenant_id="+getContext().getAccountNumber() + "&fields=id&fields=status"); + JSONObject result = getMethod().getNetworks(getLoadBalancersResource(), null, false, + "?tenant_id="+ getAccountNumber() + "&fields=id&fields=status"); List results = new ArrayList(); if( result != null && result.has("pools") ) { try { @@ -263,14 +262,17 @@ private Subnet findSubnetById(List subnets, String subnetId) { // addIPEndpoints(toLoadBalancerId, ipAddressesToAdd.toArray(new String[ipAddressesToAdd.size()])); // } + protected NovaMethod getMethod() { + return new NovaMethod(getProvider()); + } + @Override public void removeIPEndpoints(@Nonnull String fromLoadBalancerId, @Nonnull String... addresses) throws CloudException, InternalException { - NovaMethod method = new NovaMethod(getProvider()); for( JSONObject member : findAllMembers(fromLoadBalancerId) ) { for( String address : addresses ) { try { if( address.equals(member.getString("address")) ) { - method.deleteNetworks(getMembersResource(), member.getString("id")); + getMethod().deleteNetworks(getMembersResource(), member.getString("id")); } } catch( JSONException e ) { @@ -280,11 +282,15 @@ public void removeIPEndpoints(@Nonnull String fromLoadBalancerId, @Nonnull Strin } } + protected VirtualMachine getVirtualMachine(String serverId) throws CloudException, InternalException { + return getProvider().getComputeServices().getVirtualMachineSupport().getVirtualMachine(serverId); + } + @Override public void removeServers(@Nonnull String fromLoadBalancerId, @Nonnull String... serverIdsToRemove) throws CloudException, InternalException { - List ipAddressesToRemove = new ArrayList(); + List ipAddressesToRemove = new ArrayList<>(); for( String serverId : serverIdsToRemove ) { - VirtualMachine vm = getProvider().getComputeServices().getVirtualMachineSupport().getVirtualMachine(serverId); + VirtualMachine vm = getVirtualMachine(serverId); if( vm != null ) { for( RawAddress address : vm.getPrivateAddresses() ) { ipAddressesToRemove.add(address.getIpAddress()); @@ -316,12 +322,11 @@ public void attachHealthCheckToLoadBalancer(@Nonnull String providerLoadBalancer Map json = new HashMap(); json.put("health_monitor", lb); - NovaMethod method = new NovaMethod(getProvider()); if( logger.isTraceEnabled() ) { logger.trace("create(): Posting health monitor id to attach..."); } - JSONObject result = method.postNetworks(getLoadBalancersResource(), providerLoadBalancerId, new JSONObject(json), "health_monitors"); + JSONObject result = getMethod().postNetworks(getLoadBalancersResource(), providerLoadBalancerId, new JSONObject(json), "health_monitors"); if( result == null ) { logger.error("create(): Method executed successfully, but no health monitor was attached"); throw new CloudException("Method executed successfully, but no health monitor was attached"); @@ -336,8 +341,7 @@ public void attachHealthCheckToLoadBalancer(@Nonnull String providerLoadBalancer public Iterable listLBHealthChecks(@Nullable HealthCheckFilterOptions opts) throws CloudException, InternalException { APITrace.begin(getProvider(), "LB.listLBHealthChecks"); try { - NovaMethod method = new NovaMethod(getProvider()); - JSONObject result = method.getNetworks(getHealthMonitorsResource(), null, false); + JSONObject result = getMethod().getNetworks(getHealthMonitorsResource(), null, false); List healthMonitors = new ArrayList(); if( result != null && result.has("health_monitors") ) { try { @@ -366,9 +370,8 @@ public Iterable listLBHealthChecks(@Nullable HealthChec public LoadBalancerHealthCheck getLoadBalancerHealthCheck(@Nonnull String providerLBHealthCheckId, /* ignored */ @Nullable String providerLoadBalancerId) throws CloudException, InternalException { APITrace.begin(getProvider(), "LB.getLoadBalancerHealthCheck"); try { - NovaMethod method = new NovaMethod(getProvider()); - JSONObject result = method.getNetworks(getHealthMonitorsResource(), providerLBHealthCheckId, false); + JSONObject result = getMethod().getNetworks(getHealthMonitorsResource(), providerLBHealthCheckId, false); if( result == null ) { logger.error("create(): Method executed successfully, but no health monitor was found"); @@ -401,7 +404,7 @@ public LoadBalancerHealthCheck modifyHealthCheck(@Nonnull String providerLBHealt } } - private void safeDeleteLoadBalancerHealthCheck(LoadBalancerHealthCheck hc) throws CloudException, InternalException { + protected void safeDeleteLoadBalancerHealthCheck(LoadBalancerHealthCheck hc) throws CloudException, InternalException { for( String loadBalancer: hc.getProviderLoadBalancerIds() ) { detatchHealthCheck(loadBalancer, hc.getProviderLBHealthCheckId()); } @@ -429,12 +432,12 @@ public void detatchHealthCheck(@Nonnull String loadBalancerId, @Nonnull String p } } - private LoadBalancerHealthCheck createHealthMonitor(@Nonnull List loadbalancerIds, @Nonnull HealthCheckOptions opt) throws InternalException, CloudException { + protected LoadBalancerHealthCheck createHealthMonitor(@Nonnull List loadbalancerIds, @Nonnull HealthCheckOptions opt) throws InternalException, CloudException { APITrace.begin(getProvider(), "LB.createListener"); try { Map lb = new HashMap(); - lb.put("tenant_id", getContext().getAccountNumber()); + lb.put("tenant_id", getAccountNumber()); lb.put("type", toOSHCType(opt.getProtocol())); lb.put("delay", opt.getInterval()); lb.put("timeout", opt.getTimeout()); @@ -446,12 +449,11 @@ private LoadBalancerHealthCheck createHealthMonitor(@Nonnull List loadba Map json = new HashMap(); json.put("health_monitor", lb); - NovaMethod method = new NovaMethod(getProvider()); if( logger.isTraceEnabled() ) { logger.trace("create(): Posting new health monitor data..."); } - JSONObject result = method.postNetworks(getHealthMonitorsResource(), null, new JSONObject(json), null); + JSONObject result = getMethod().postNetworks(getHealthMonitorsResource(), null, new JSONObject(json), null); if( result == null ) { logger.error("create(): Method executed successfully, but no health monitor was created"); @@ -475,10 +477,18 @@ private LoadBalancerHealthCheck createHealthMonitor(@Nonnull List loadba } - private void deleteHealthMonitor(String providerLBHealthCheckId) throws CloudException, InternalException { + protected String getAccountNumber() throws InternalException { + return getContext().getAccountNumber(); + } + + protected String getCurrentRegionId() throws InternalException { + return getContext().getRegionId(); + } + + protected void deleteHealthMonitor(String providerLBHealthCheckId) throws CloudException, InternalException { APITrace.begin(getProvider(), "LB.deleteHealthMonitor"); try { - new NovaMethod(getProvider()).deleteNetworks(getHealthMonitorsResource(), providerLBHealthCheckId); + getMethod().deleteNetworks(getHealthMonitorsResource(), providerLBHealthCheckId); } finally { APITrace.end(); @@ -491,7 +501,7 @@ private void deleteHealthMonitor(String providerLBHealthCheckId) throws CloudExc * @return LoadBalancerHealthCheck * @throws JSONException */ - private @Nonnull LoadBalancerHealthCheck toLoadBalancerHealthCheck(JSONObject ob) throws JSONException, InternalException, CloudException { + protected @Nonnull LoadBalancerHealthCheck toLoadBalancerHealthCheck(JSONObject ob) throws JSONException, InternalException, CloudException { LoadBalancerHealthCheck.HCProtocol protocol = fromOSProtocol(ob.getString("type")); int count = ob.getInt("max_retries"); int port = -1; @@ -518,7 +528,7 @@ private void deleteHealthMonitor(String providerLBHealthCheckId) throws CloudExc return lbhc; } - private String toOSHCType(LoadBalancerHealthCheck.HCProtocol hcProtocol) { + protected String toOSHCType(LoadBalancerHealthCheck.HCProtocol hcProtocol) { switch( hcProtocol ) { case TCP: return "TCP"; @@ -529,7 +539,7 @@ private String toOSHCType(LoadBalancerHealthCheck.HCProtocol hcProtocol) { } } - private void createListener(@Nonnull String lbId, String subnetId, @Nonnull LbListener listener) throws CloudException, InternalException { + protected void createListener(@Nonnull String lbId, String subnetId, @Nonnull LbListener listener) throws CloudException, InternalException { APITrace.begin(getProvider(), "LB.createListener"); try { @@ -538,7 +548,7 @@ private void createListener(@Nonnull String lbId, String subnetId, @Nonnull LbLi // private ports in OS are set in members which may not and unlikely to even exist at this point // so we have to serialise the private port into the VIP name. lb.put("name", generateListenerId(lbId, listener.getPrivatePort())); - lb.put("tenant_id", getContext().getAccountNumber()); + lb.put("tenant_id", getAccountNumber()); lb.put("protocol", toOSProtocol(listener.getNetworkProtocol())); lb.put("subnet_id", subnetId); lb.put("protocol_port", listener.getPublicPort()); @@ -546,12 +556,11 @@ private void createListener(@Nonnull String lbId, String subnetId, @Nonnull LbLi Map json = new HashMap(); json.put("vip", lb); - NovaMethod method = new NovaMethod(getProvider()); if( logger.isTraceEnabled() ) { logger.trace("create(): Posting new listener data..."); } - JSONObject result = method.postNetworks(getListenersResource(), null, new JSONObject(json), false); + JSONObject result = getMethod().postNetworks(getListenersResource(), null, new JSONObject(json), false); if( result == null ) { logger.error("create(): Method executed successfully, but no listener was created"); @@ -563,24 +572,23 @@ private void createListener(@Nonnull String lbId, String subnetId, @Nonnull LbLi } } - private void createMember(@Nonnull String lbId, String address, int privatePort) throws CloudException, InternalException { + protected void createMember(@Nonnull String lbId, String address, int privatePort) throws CloudException, InternalException { APITrace.begin(getProvider(), "LB.createMember"); try { Map lb = new HashMap(); - lb.put("tenant_id", getContext().getAccountNumber()); + lb.put("tenant_id", getAccountNumber()); lb.put("protocol_port", privatePort); lb.put("address", address); lb.put("pool_id", lbId); Map json = new HashMap(); json.put("member", lb); - NovaMethod method = new NovaMethod(getProvider()); if( logger.isTraceEnabled() ) { logger.trace("create(): Posting new listener data..."); } - JSONObject result = method.postNetworks(getMembersResource(), null, new JSONObject(json), false); + JSONObject result = getMethod().postNetworks(getMembersResource(), null, new JSONObject(json), false); if( result == null ) { logger.error("create(): Method executed successfully, but no load balancer member was created"); throw new CloudException("Method executed successfully, but no load balancer member was created"); @@ -598,9 +606,8 @@ private void createMember(@Nonnull String lbId, String address, int privatePort) * @throws CloudException * @throws InternalException */ - private List findAllVips(@Nullable String loadBalancerId) throws CloudException, InternalException { - NovaMethod method = new NovaMethod(getProvider()); - JSONObject result = method.getNetworks(getListenersResource(), null, false, "?tenant_id="+getContext().getAccountNumber()); + protected List findAllVips(@Nullable String loadBalancerId) throws CloudException, InternalException { + JSONObject result = getMethod().getNetworks(getListenersResource(), null, false, "?tenant_id="+ getAccountNumber()); List listeners = new ArrayList(); if( result != null && result.has("vips") ) { try { @@ -627,9 +634,8 @@ private List findAllVips(@Nullable String loadBalancerId) throws Clo * @throws CloudException * @throws InternalException */ - private List findAllMembers(@Nullable String loadBalancerId) throws CloudException, InternalException { - NovaMethod method = new NovaMethod(getProvider()); - JSONObject result = method.getNetworks(getMembersResource(), null, false, "?tenant_id="+getContext().getAccountNumber()); + protected List findAllMembers(@Nullable String loadBalancerId) throws CloudException, InternalException { + JSONObject result = getMethod().getNetworks(getMembersResource(), null, false, "?tenant_id="+ getAccountNumber()); List members = new ArrayList(); if( result != null && result.has("members") ) { try { @@ -666,9 +672,8 @@ private List findLoadBalancers(@Nullable String loadBalancerId) th // get all members, optionally filtered by lbId List members = findAllMembers(loadBalancerId); - NovaMethod method = new NovaMethod(getProvider()); // Unlike Horizon the OS LB API returns all tenants' load balancers, so we must filter - JSONObject result = method.getNetworks(getLoadBalancersResource(), loadBalancerId, false, "?tenant_id="+getContext().getAccountNumber()); + JSONObject result = getMethod().getNetworks(getLoadBalancersResource(), loadBalancerId, false, "?tenant_id="+ getAccountNumber()); List results = new ArrayList(); if( loadBalancerId == null && result != null && result.has("pools") ) { try { @@ -706,7 +711,7 @@ else if( result != null && result.has("pool")) { } - private @Nullable JSONObject findListenerByLbId(@Nonnull List listeners, @Nonnull String lbId) throws JSONException { + protected @Nullable JSONObject findListenerByLbId(@Nonnull List listeners, @Nonnull String lbId) throws JSONException { for( JSONObject listener : listeners ) { if( listener.has("pool_id") && lbId.equals(listener.getString("pool_id")) ) { return listener; @@ -715,9 +720,9 @@ else if( result != null && result.has("pool")) { return null; } - private LoadBalancer toLoadBalancer(JSONObject lb, List listeners, List members) throws JSONException, InternalException { + protected LoadBalancer toLoadBalancer(JSONObject lb, List listeners, List members) throws JSONException, InternalException { String ownerId = lb.optString("tenant_id"); - String regionId = getContext().getRegionId(); + String regionId = getCurrentRegionId(); String lbId = lb.getString("id"); LoadBalancerState state = "ACTIVE".equalsIgnoreCase(lb.getString("status")) ? LoadBalancerState.ACTIVE : LoadBalancerState.PENDING; @@ -780,15 +785,16 @@ else if (sessionPersistence.endsWith("COOKIE")) { lbListeners.add(LbListener.getInstance(algorithm, persistence, protocol, publicPort, privatePort)); } } - LoadBalancer loadBalancer = LoadBalancer.getInstance( - ownerId, regionId, lbId, state, name, description, addressType, address, new int[] {publicPort}); - loadBalancer.withProviderSubnetIds(lb.optString("subnet_id")); - loadBalancer.withListeners(lbListeners.toArray(new LbListener[lbListeners.size()])); JSONArray monitors = lb.getJSONArray("health_monitors"); + String lbhcId = null; if( monitors.length() > 0 ) { // Dasein can only support one, should probably extend that in core - loadBalancer.setProviderLBHealthCheckId(monitors.getString(0)); + lbhcId = monitors.getString(0); } + LoadBalancer loadBalancer = LoadBalancer.getInstance( + ownerId, regionId, lbId, state, name, description, LbType.EXTERNAL, addressType, address, lbhcId, VisibleScope.ACCOUNT_REGION, new int[] {publicPort}); + loadBalancer.withProviderSubnetIds(lb.optString("subnet_id")); + loadBalancer.withListeners(lbListeners.toArray(new LbListener[lbListeners.size()])); loadBalancer.operatingIn(regionId + "-a"); return loadBalancer; @@ -805,7 +811,7 @@ private LoadBalancerEndpoint toLoadBalancerEnpoint(JSONObject member) throws Clo } } - private String generateListenerId(String lbId, int privatePort) { + protected String generateListenerId( String lbId, int privatePort ) { return lbId + ":" + privatePort; } @@ -830,11 +836,10 @@ public void removeLoadBalancer(@Nonnull String loadBalancerId) throws CloudExcep } } - NovaMethod method = new NovaMethod(getProvider()); List listeners = findAllVips(loadBalancerId); for( JSONObject listener : listeners ) { try { - method.deleteNetworks(getListenersResource(), listener.getString("id")); + getMethod().deleteNetworks(getListenersResource(), listener.getString("id")); } catch( JSONException ignore ) { } @@ -844,7 +849,7 @@ public void removeLoadBalancer(@Nonnull String loadBalancerId) throws CloudExcep do { try { - method.deleteNetworks(getLoadBalancersResource(), loadBalancerId); + getMethod().deleteNetworks(getLoadBalancersResource(), loadBalancerId); return; } catch( NovaException e ) { @@ -881,7 +886,7 @@ private String toOSProtocol(LbProtocol networkProtocol) { } } - private LoadBalancerHealthCheck.HCProtocol fromOSProtocol(String protocol) { + protected LoadBalancerHealthCheck.HCProtocol fromOSProtocol(String protocol) { if( "HTTPS".equalsIgnoreCase(protocol) ) { return LoadBalancerHealthCheck.HCProtocol.HTTPS; } @@ -907,11 +912,11 @@ private String getLoadBalancersResource() { return "v2.0/lb/pools"; } - private String getListenersResource() { + protected String getListenersResource() { return "v2.0/lb/vips"; } - private String getMembersResource() { + protected String getMembersResource() { return "v2.0/lb/members"; } diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/NovaMethodTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/NovaMethodTest.java new file mode 100644 index 0000000..25d376e --- /dev/null +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/NovaMethodTest.java @@ -0,0 +1,418 @@ +package org.dasein.cloud.openstack.nova.os; + +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.compute.VirtualMachine; +import org.dasein.cloud.openstack.nova.os.compute.NovaServer; +import org.dasein.cloud.openstack.nova.os.ext.hp.cdn.HPCDN; +import org.dasein.cloud.openstack.nova.os.network.Quantum; +import org.json.JSONObject; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Created by mariapavlova on 20/11/2015. + */ +public class NovaMethodTest { + + @Test + public void deleteServersTest (){ + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + + final String testResourceId = "testResourceId"; + final String testComputeUrl = "testComputeUrl"; + final String testAuthToken = "testAuthToken"; + final String testResource = "testResource"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getComputeUrl()).thenReturn(testComputeUrl); + + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doNothing().when(method).delete(anyString(),anyString(),anyString()); + Mockito.doCallRealMethod().when(method).deleteServers(anyString(), anyString()); + method.deleteServers(testResource, testResourceId); + + ArgumentCaptor testToken = ArgumentCaptor.forClass(String.class); + ArgumentCaptor testEndpoint = ArgumentCaptor.forClass(String.class); + ArgumentCaptor testResourceCapt = ArgumentCaptor.forClass(String.class); + verify(method).delete(testToken.capture(), testEndpoint.capture(), testResourceCapt.capture()); + assertEquals("Token passed to the method is not as expected", testAuthToken, testToken.getValue()); + assertEquals("Endpoint passed to the method is not as expected", testComputeUrl, testEndpoint.getValue()); + assertEquals("Resource passed to the method is not as expected", testResource + "/" + testResourceId, testResourceCapt.getValue()); + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void deleteNetworks (){ + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + + final String testResourceId = "testResourceId"; + final String testNetworkUrl = "testNetworkUrl"; + final String testAuthToken = "testAuthToken"; + final String testResource = "testResource"; + + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getNetworkUrl()).thenReturn(testNetworkUrl); + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doNothing().when(method).delete(anyString(),anyString(),anyString()); + Mockito.doCallRealMethod().when(method).deleteNetworks(anyString(), anyString()); + method.deleteNetworks("testResource", testResourceId); + + ArgumentCaptor testToken = ArgumentCaptor.forClass(String.class); + ArgumentCaptor testEndpoint = ArgumentCaptor.forClass(String.class); + ArgumentCaptor testResourceCapt = ArgumentCaptor.forClass(String.class); + verify(method).delete(testToken.capture(), testEndpoint.capture(), testResourceCapt.capture()); + assertEquals("Token passed to the method is not as expected", testAuthToken, testToken.getValue()); + assertEquals("Endpoint passed to the method is not as expected", testNetworkUrl + "/", testEndpoint.getValue()); + assertEquals("Resource passed to the method is not as expected", testResource + "/" + testResourceId, testResourceCapt.getValue()); + + + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void getPortsTest () { + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + + final String testResourceId = "testResourceId"; + final String testComputeUrl = "testComputeUrl"; + final String testAuthToken = "testAuthToken"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getComputeUrl()).thenReturn(testComputeUrl); + when(context.getMyRegion()).thenReturn("testRegionId"); + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doCallRealMethod().when(method).getPorts(anyString(), anyString()); + method.getPorts("testResource", testResourceId); + + ArgumentCaptor vmIdArg = ArgumentCaptor.forClass(String.class); + verify(method).getPorts(anyString(), vmIdArg.capture()); + assertEquals("VM ID passed to the method is not as expected", testResourceId, vmIdArg.getValue()); + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void getServersTest () { + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + + final String testResourceId = "testResourceId"; + final String testComputeUrl = "testComputeUrl"; + final String testAuthToken = "testAuthToken"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getComputeUrl()).thenReturn(testComputeUrl); + when(context.getMyRegion()).thenReturn("testRegionId"); + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doCallRealMethod().when(method).getServers(anyString(), anyString(), anyBoolean()); + method.getServers("testResource", testResourceId, true); + + ArgumentCaptor vmIdArg = ArgumentCaptor.forClass(String.class); + verify(method).getServers(anyString(), vmIdArg.capture(), anyBoolean()); + assertEquals("VM ID passed to the method is not as expected", testResourceId, vmIdArg.getValue()); + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void getNetworksTest () { + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + + final String testResourceId = "testResourceId"; + final String testNetworkUrl = "testNetworkUrl"; + final String testAuthToken = "testAuthToken"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getNetworkUrl()).thenReturn(testNetworkUrl); + when(context.getMyRegion()).thenReturn("testRegionId"); + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doCallRealMethod().when(method).getNetworks(anyString(), anyString(), anyBoolean(), anyString()); + method.getNetworks("testResource", testResourceId, true, "testQuery"); + + ArgumentCaptor vmIdArg = ArgumentCaptor.forClass(String.class); + verify(method).getNetworks(anyString(), vmIdArg.capture(), anyBoolean(), anyString()); + assertEquals("VM ID passed to the method is not as expected", testResourceId, vmIdArg.getValue()); + + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void postServersForStringTest () { + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + JSONObject serverObj = new JSONObject(); + + final String testResourceId = "testResourceId"; + final String testComputeUrl = "testComputeUrl"; + final String testAuthToken = "testAuthToken"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getComputeUrl()).thenReturn(testComputeUrl); + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doCallRealMethod().when(method).postServersForString(anyString(), anyString(), any(JSONObject.class), anyBoolean()); + method.postServersForString("testResource", testResourceId, serverObj, true); + + ArgumentCaptor vmIdArg = ArgumentCaptor.forClass(String.class); + ArgumentCaptor jsonArg = ArgumentCaptor.forClass(JSONObject.class); + + verify(method).postServersForString(anyString(), vmIdArg.capture(), jsonArg.capture(), anyBoolean()); + assertEquals("VM ID passed to the method is not as expected", testResourceId, vmIdArg.getValue()); + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void postServersTest () { + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + JSONObject serverObj = new JSONObject(); + + final String testResourceId = "testResourceId"; + final String testComputeUrl = "testComputeUrl"; + final String testAuthToken = "testAuthToken"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getComputeUrl()).thenReturn(testComputeUrl); + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doCallRealMethod().when(method).postServers(anyString(), anyString(), any(JSONObject.class), anyBoolean()); + method.postServers("testResource", testResourceId, serverObj, true); + + ArgumentCaptor vmIdArg = ArgumentCaptor.forClass(String.class); + ArgumentCaptor jsonArg = ArgumentCaptor.forClass(JSONObject.class); + + verify(method).postServers(anyString(), vmIdArg.capture(), jsonArg.capture(), anyBoolean()); + assertEquals("VM ID passed to the method is not as expected", testResourceId, vmIdArg.getValue()); + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void postNetworksTest () { + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + JSONObject serverObj = new JSONObject(); + + final String testResourceId = "testResourceId"; + final String testNetworkUrl = "testNetworkUrl"; + final String testAuthToken = "testAuthToken"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getNetworkUrl()).thenReturn(testNetworkUrl); + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doCallRealMethod().when(method).postNetworks(anyString(), anyString(), any(JSONObject.class), anyString()); + method.postNetworks("testResource", testResourceId, serverObj, "testAction"); + + ArgumentCaptor vmIdArg = ArgumentCaptor.forClass(String.class); + ArgumentCaptor jsonArg = ArgumentCaptor.forClass(JSONObject.class); + + verify(method).postNetworks(anyString(), vmIdArg.capture(), jsonArg.capture(), anyString()); + assertEquals("VM ID passed to the method is not as expected", testResourceId, vmIdArg.getValue()); + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void putNetworksTest () { + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + JSONObject serverObj = new JSONObject(); + + final String testResourceId = "testResourceId"; + final String testNetworkUrl = "testNetworkUrl"; + final String testAuthToken = "testAuthToken"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getNetworkUrl()).thenReturn(testNetworkUrl); + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doCallRealMethod().when(method).putNetworks(anyString(), anyString(), any(JSONObject.class), anyString()); + method.putNetworks("testResource", testResourceId, serverObj, "testAction"); + + ArgumentCaptor vmIdArg = ArgumentCaptor.forClass(String.class); + ArgumentCaptor jsonArg = ArgumentCaptor.forClass(JSONObject.class); + + verify(method).putNetworks(anyString(), vmIdArg.capture(), jsonArg.capture(), anyString()); + assertEquals("VM ID passed to the method is not as expected", testResourceId, vmIdArg.getValue()); + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void getHPCDNTest () { + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + + final String testResourceId = "testResourceId"; + final String testServiceUrl = "testServiceUrl"; + final String testAuthToken = "testAuthToken"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getServiceUrl(anyString())).thenReturn(testServiceUrl); + when(context.getMyRegion()).thenReturn("testRegionId"); + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doCallRealMethod().when(method).getHPCDN(anyString()); + method.getHPCDN(testResourceId); + + ArgumentCaptor vmIdArg = ArgumentCaptor.forClass(String.class); + verify(method).getHPCDN(vmIdArg.capture()); + assertEquals("VM ID passed to the method is not as expected", testResourceId, vmIdArg.getValue()); + + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void putHPCDNTest () { + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + + final String testResourceId = "testResourceId"; + final String testServiceUrl = "testServiceUrl"; + final String testAuthToken = "testAuthToken"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getServiceUrl(anyString())).thenReturn(testServiceUrl); + when(context.getMyRegion()).thenReturn("testRegionId"); + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doCallRealMethod().when(method).putHPCDN(anyString()); + when(method.headResource(anyString(), anyString(), anyString())).thenReturn(Collections.EMPTY_MAP); + + method.putHPCDN(testResourceId); + + ArgumentCaptor headers = ArgumentCaptor.forClass(Map.class); + verify(method).putHeaders(anyString(), anyString(), anyString(), headers.capture()); + + Map verifyMap = headers.getValue(); + assertEquals("X-TTL param is not present", true, verifyMap.containsKey("X-TTL")); + assertEquals("X-TTL param value is not as expected", "86400", verifyMap.get("X-TTL")); + + ArgumentCaptor service = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resource = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceId = ArgumentCaptor.forClass(String.class); + verify(method).headResource(service.capture(), resource.capture(), resourceId.capture()); + assertEquals("Service is not as expected", HPCDN.SERVICE, service.getValue()); + assertEquals("Resource is not as expected", HPCDN.RESOURCE, resource.getValue()); + assertEquals("ResourceId is not as expected", testResourceId, resourceId.getValue()); + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void postHPCDNTest () { + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + + final String testResourceId = "testResourceId"; + final String testRegionId = "testRegionId"; + final String testAuthToken = "testAuthToken"; + final String testComputeUrl = "testComputeUrl"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getServiceUrl(anyString())).thenReturn(testComputeUrl); + when(context.getMyRegion()).thenReturn(testRegionId); + when(context.getAuthToken()).thenReturn(testAuthToken); + Mockito.doCallRealMethod().when(method).postHPCDN(anyString(), anyMap()); + method.postHPCDN(testResourceId, Collections.EMPTY_MAP); + + ArgumentCaptor testToken = ArgumentCaptor.forClass(String.class); + ArgumentCaptor testEndpoint = ArgumentCaptor.forClass(String.class); + ArgumentCaptor testResource = ArgumentCaptor.forClass(String.class); + ArgumentCaptor testMap = ArgumentCaptor.forClass(Map.class); + verify(method).postHeaders(testToken.capture(), testEndpoint.capture(), testResource.capture(), testMap.capture()); + assertEquals("Token passed to the method is not as expected", testAuthToken, testToken.getValue()); + assertEquals("Endpoint passed to the method is not as expected", testComputeUrl, testEndpoint.getValue()); + assertEquals("Resource passed to the method is not as expected", "/" + testResourceId, testResource.getValue()); + assertEquals("Custom headers passed to the method are not as expected", Collections.EMPTY_MAP, testMap.getValue()); + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + @Test + public void deleteHPCDNTest (){ + AuthenticationContext context = mock(AuthenticationContext.class); + NovaMethod method = mock(NovaMethod.class); + + final String testContainerId = "testContainerId"; + final String testServiceUrl = "testServiceUrl"; + final String testAuthToken = "testAuthToken"; + final String testRegionId = "testRegionId"; + try { + when(method.getAuthenticationContext()).thenReturn(context); + when(context.getServiceUrl(anyString())).thenReturn(testServiceUrl); + when(context.getAuthToken()).thenReturn(testAuthToken); + when(context.getMyRegion()).thenReturn(testRegionId); + Mockito.doNothing().when(method).delete(anyString(),anyString(),anyString()); + Mockito.doCallRealMethod().when(method).deleteHPCDN(anyString()); + method.deleteHPCDN("testContainerId"); + + ArgumentCaptor testToken = ArgumentCaptor.forClass(String.class); + ArgumentCaptor testEndpoint = ArgumentCaptor.forClass(String.class); + ArgumentCaptor testContainer = ArgumentCaptor.forClass(String.class); + verify(method).delete(testToken.capture(), testEndpoint.capture(), testContainer.capture()); + assertEquals("Token passed to the method is not as expected", testAuthToken, testToken.getValue()); + assertEquals("Endpoint passed to the method is not as expected", testServiceUrl, testEndpoint.getValue()); + assertEquals("Resource passed to the method is not as expected", "/" + testContainerId, testContainer.getValue()); + + } + catch( InternalException | CloudException e) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + +} diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/OpenstackTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/OpenstackTest.java new file mode 100644 index 0000000..3768f13 --- /dev/null +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/OpenstackTest.java @@ -0,0 +1,31 @@ +package org.dasein.cloud.openstack.nova.os; + +import org.apache.commons.io.IOUtils; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Base class for tests, contains useful common methods + */ +public class OpenStackTest { + + protected JSONObject readJson(String filename) { + try { + InputStream is = getClass().getClassLoader().getResourceAsStream(filename); + if( is == null ) { + throw new RuntimeException("File not found: " + filename); + } + String jsonText = IOUtils.toString(is); + return new JSONObject(jsonText); + } + catch( JSONException e ) { + throw new RuntimeException(e); + } + catch( IOException e ) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaServerTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaServerTest.java index f1ab69d..12e0962 100644 --- a/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaServerTest.java +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaServerTest.java @@ -1,20 +1,17 @@ package org.dasein.cloud.openstack.nova.os.compute; -import org.apache.commons.io.IOUtils; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.ResourceStatus; -import org.dasein.cloud.Tag; import org.dasein.cloud.compute.*; import org.dasein.cloud.network.*; import org.dasein.cloud.openstack.nova.os.NovaMethod; import org.dasein.cloud.openstack.nova.os.OpenStackProvider; +import org.dasein.cloud.openstack.nova.os.OpenStackTest; import org.dasein.cloud.openstack.nova.os.network.NovaFloatingIP; import org.dasein.cloud.openstack.nova.os.network.NovaNetworkServices; import org.dasein.cloud.openstack.nova.os.network.NovaSecurityGroup; import org.dasein.cloud.openstack.nova.os.network.Quantum; -import org.dasein.util.uom.storage.Megabyte; -import org.dasein.util.uom.storage.Storage; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; @@ -22,8 +19,6 @@ import org.mockito.Mockito; import org.skyscreamer.jsonassert.JSONAssert; -import java.io.IOException; -import java.io.InputStream; import java.util.*; import static org.junit.Assert.*; @@ -32,26 +27,13 @@ import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; -import static org.mockito.internal.verification.VerificationModeFactory.atLeast; import static org.mockito.internal.verification.VerificationModeFactory.times; /** * Created by mariapavlova on 09/10/2015. */ -public class NovaServerTest { - private JSONObject readJson(String filename) { - try { - InputStream is = getClass().getClassLoader().getResourceAsStream(filename); - String jsonText = IOUtils.toString(is); - return new JSONObject(jsonText); - } - catch( JSONException e ) { - throw new RuntimeException(e); - } - catch( IOException e ) { - throw new RuntimeException(e); - } - } +public class NovaServerTest extends OpenStackTest { + @Test public void getConsoleOutputTest() { @@ -148,7 +130,7 @@ public void getVirtualMachineTest(){ when(server.getPlatform(anyString(), anyString(), anyString())).thenReturn(Platform.UBUNTU); when(server.getRegionId()).thenReturn("testRegion"); - when(server.listFirewalls(anyString())).thenReturn(Collections.EMPTY_LIST); + when(server.listFirewalls(anyString(), any(JSONObject.class))).thenReturn(Collections.EMPTY_LIST); when(server.toVirtualMachine(any(JSONObject.class), anyList(), anyList(), anyList())).thenCallRealMethod(); when(method.getServers(anyString(), anyString(), anyBoolean())).thenReturn(json); when(server.getVirtualMachine(anyString())).thenCallRealMethod(); diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java new file mode 100644 index 0000000..244481f --- /dev/null +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java @@ -0,0 +1,565 @@ +package org.dasein.cloud.openstack.nova.os.network; + +import org.dasein.cloud.Cloud; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.VisibleScope; +import org.dasein.cloud.compute.VirtualMachine; +import org.dasein.cloud.network.*; +import org.dasein.cloud.openstack.nova.os.AuthenticationContext; +import org.dasein.cloud.openstack.nova.os.NovaMethod; +import org.dasein.cloud.openstack.nova.os.OpenStackTest; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import java.util.*; + +import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.*; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.*; +import static org.mockito.internal.verification.VerificationModeFactory.times; + +/** + * Created by mariapavlova on 01/12/2015. + */ +public class LoadBalancerSupportImplTest extends OpenStackTest { + + private final String testLbId = "testLbId"; + private final String testSubnetId = "testSubnetId"; + private final String testProviderLBHealthCheckId = "testProviderLBHealthCheckId"; + private final String testOwnerId = "testOwnerId"; + private final String testRegionId = "testRegionId"; + private final String testVmId = "testVmId"; + private final String testIpAddress1 = "177.177.177.177"; + private final String testIpAddress2 = "188.177.177.177"; + private final int testPrivatePort = 9999; + + private LoadBalancer createTestLb() { + return LoadBalancer.getInstance(testOwnerId, testRegionId, testLbId, LoadBalancerState.ACTIVE, "name", "description", LoadBalancerAddressType.IP, "65.65.65.65", 8080, 8081).withListeners(LbListener.getInstance(8080, testPrivatePort)); + } + + private HealthCheckOptions createHCO() { + return HealthCheckOptions.getInstance("name", "description", testLbId, null, null, testPrivatePort, null, 1, 1, 1, 1); + } + + @Test + public void addIPEndpointsTest() { + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + LoadBalancer lb = createTestLb(); + + try { + Mockito.doCallRealMethod().when(lbSupport).addIPEndpoints(anyString(), any(String[].class)); + when(lbSupport.getLoadBalancer(anyString())).thenReturn(lb); + ArgumentCaptor captLbId = ArgumentCaptor.forClass(String.class); + ArgumentCaptor captAddress = ArgumentCaptor.forClass(String.class); + ArgumentCaptor captPort = ArgumentCaptor.forClass(Integer.class); + + lbSupport.addIPEndpoints(testLbId, testIpAddress1); + + verify(lbSupport).createMember(captLbId.capture(), captAddress.capture(), captPort.capture()); + assertEquals("Loadbalancer Id is not as expected", testLbId, captLbId.getValue()); + assertEquals("Endpoint Ip address is not as expected", testIpAddress1, captAddress.getValue()); + assertEquals("Endpoint port is not as expected", testPrivatePort, (int) captPort.getValue()); + } + catch( InternalException | CloudException e ) { + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void removeServersTest() { + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + VirtualMachine vmMock = mock(VirtualMachine.class); + + RawAddress[] addresses = new RawAddress[] { + new RawAddress(testIpAddress1), + new RawAddress(testIpAddress2) + }; + try { + when(vmMock.getPrivateAddresses()).thenReturn(addresses); + when(lbSupport.getVirtualMachine(anyString())).thenReturn(vmMock); + Mockito.doCallRealMethod().when(lbSupport).removeServers(anyString(), any(String[].class)); + + ArgumentCaptor lbCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor address1Capt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor address2Capt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor vmIdCapt = ArgumentCaptor.forClass(String.class); + + lbSupport.removeServers(testLbId, testVmId); + + verify(lbSupport).getVirtualMachine(vmIdCapt.capture()); + assertEquals("Requested vm id is not as expected", testVmId, vmIdCapt.getValue()); + + verify(lbSupport).removeIPEndpoints(lbCapt.capture(), address1Capt.capture(), address2Capt.capture()); + assertEquals("Requested lb id is not as expected", testLbId, lbCapt.getValue()); + assertEquals("Requested IP is not as expected", testIpAddress1, address1Capt.getValue()); + assertEquals("Requested IP is not as expected", testIpAddress2, address2Capt.getValue()); + } + catch( InternalException | CloudException e ) { + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void createLoadBalancerHealthCheckTest() { + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + final String testName = "testName"; + final String testDescription = "testDescription"; + final String testHost = "testHost"; + final LoadBalancerHealthCheck.HCProtocol testProtocol = LoadBalancerHealthCheck.HCProtocol.HTTP; + final int testPort = 42; + final String testPath = "testPath"; + final int testInterval = 5; + final int testTimeout = 3; + final int testHealthyCount = 1; + final int testUnhealthyCount = 2; + try { + when(lbSupport.createLoadBalancerHealthCheck(anyString(), anyString(), anyString(), any(LoadBalancerHealthCheck.HCProtocol.class), anyInt(), anyString(), anyInt(), anyInt(), anyInt(), anyInt())).thenCallRealMethod(); + ArgumentCaptor optsCapt = ArgumentCaptor.forClass(HealthCheckOptions.class); + lbSupport.createLoadBalancerHealthCheck(testName, testDescription, testHost, testProtocol, testPort, testPath, testInterval, testTimeout, testHealthyCount, testUnhealthyCount); + verify(lbSupport).createLoadBalancerHealthCheck(optsCapt.capture()); + + assertEquals("Name is not as expected", testName, optsCapt.getValue().getName()); + assertEquals("Description is not as expected", testDescription, optsCapt.getValue().getDescription()); + assertEquals("Host is not as expected", testHost, optsCapt.getValue().getHost()); + assertEquals("Protocol is not as expected", testProtocol, optsCapt.getValue().getProtocol()); + assertEquals("Port is not as expected", testPort, optsCapt.getValue().getPort()); + assertEquals("Path is not as expected", testPath, optsCapt.getValue().getPath()); + assertEquals("Interval is not as expected", testInterval, optsCapt.getValue().getInterval()); + assertEquals("Timeout is not as expected", testTimeout, optsCapt.getValue().getTimeout()); + assertEquals("HealthyCount is not as expected", testHealthyCount, optsCapt.getValue().getHealthyCount()); + assertEquals("UnhealthyCount is not as expected", testUnhealthyCount, optsCapt.getValue().getUnhealthyCount()); + } + catch( InternalException | CloudException e ) { + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void attachHealthCheckToLoadBalancerTest() { + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + NovaMethod method = mock(NovaMethod.class); + JSONObject jsonObject = new JSONObject(); + try { + when(lbSupport.getMethod()).thenReturn(method); + when(method.postNetworks(anyString(), anyString(), any(JSONObject.class),anyString())).thenReturn(jsonObject); + Mockito.doCallRealMethod().when(lbSupport).attachHealthCheckToLoadBalancer(anyString(), anyString()); + + lbSupport.attachHealthCheckToLoadBalancer(testLbId, testProviderLBHealthCheckId); + ArgumentCaptor lbCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor lbHealthCapt = ArgumentCaptor.forClass(String.class); + verify(lbSupport).attachHealthCheckToLoadBalancer(lbCapt.capture(), lbHealthCapt.capture()); + assertEquals("Requested lb id is not as expected", testLbId, lbCapt.getValue()); + assertEquals("Requested lb id is not as expected", testProviderLBHealthCheckId, lbHealthCapt.getValue()); + + } + catch( InternalException | CloudException e ) { + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void listLBHealthChecksTest() { + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + NovaMethod method = mock(NovaMethod.class); + JSONObject jsonObject = readJson("nova/fixtures/lb/list_health_checks.json"); + LoadBalancer lb = createTestLb(); + + try { + when(lbSupport.listLBHealthChecks(any(HealthCheckFilterOptions.class))).thenCallRealMethod(); + when(lbSupport.getMethod()).thenReturn(method); + when(method.getNetworks(anyString(), anyString(), anyBoolean())).thenReturn(jsonObject); + when(lbSupport.toLoadBalancerHealthCheck(any(JSONObject.class))).thenCallRealMethod(); + when(lbSupport.fromOSProtocol(anyString())).thenCallRealMethod(); + when(lbSupport.getLoadBalancer(anyString())).thenReturn(lb); + Iterable res = lbSupport.listLBHealthChecks(null); + LoadBalancerHealthCheck testObject = res.iterator().next(); + assertEquals("Returned provider load balancer health check Id does not match", "466c8345-28d8-4f84-a246-e04380b0461d", testObject.getProviderLBHealthCheckId()); + assertEquals("Returned protocol does not match", LoadBalancerHealthCheck.HCProtocol.HTTP, testObject.getProtocol()); + assertEquals("Returned port does not match", 9999, testObject.getPort()); + assertEquals("Returned interval does not match", 10, testObject.getInterval()); + assertEquals("Returned timeout does not match", 1, testObject.getTimeout()); + assertEquals("Returned unhealthyCount does not match", 1, testObject.getUnhealthyCount()); + assertEquals("Returned load balancer Id does not match", "lbId", testObject.getProviderLoadBalancerIds().get(0)); + assertEquals("Returned healthCount does not match", 1, testObject.getHealthyCount()); + } + catch( InternalException | CloudException | JSONException e ) { + fail("Test failed " + e.getMessage()); + } + } + @Test + public void getLoadBalancerHealthCheckTest() { + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + NovaMethod method = mock(NovaMethod.class); + JSONObject jsonObject = readJson("nova/fixtures/lb/get_health_checks.json"); + LoadBalancer lb = createTestLb(); + try { + when(lbSupport.getMethod()).thenReturn(method); + when(lbSupport.getLoadBalancerHealthCheck(anyString(), anyString())).thenCallRealMethod(); + when(method.getNetworks(anyString(), anyString(), anyBoolean())).thenReturn(jsonObject); + when(lbSupport.toLoadBalancerHealthCheck(any(JSONObject.class))).thenCallRealMethod(); + when(lbSupport.fromOSProtocol(anyString())).thenCallRealMethod(); + when(lbSupport.getLoadBalancer(anyString())).thenReturn(lb); + LoadBalancerHealthCheck res = lbSupport.getLoadBalancerHealthCheck(testProviderLBHealthCheckId, testLbId); + assertEquals("Returned provider load balancer health check Id does not match", "0a9ac99d-0a09-4b18-8499-a0796850279a", res.getProviderLBHealthCheckId()); + assertEquals("Returned protocol does not match", LoadBalancerHealthCheck.HCProtocol.HTTP, res.getProtocol()); + assertEquals("Returned timeout does not match", 1, res.getTimeout()); + + } + catch( InternalException | CloudException | JSONException e ) { + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void modifyHealthCheckTest() { + final HealthCheckOptions testHCO = createHCO(); + final List testLbIds = Arrays.asList(testLbId); + + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + LoadBalancerHealthCheck loadBalancerHealthCheck = mock(LoadBalancerHealthCheck.class); + when(loadBalancerHealthCheck.getProviderLoadBalancerIds()).thenReturn(testLbIds); + + LoadBalancerHealthCheck anotherLoadBalancerHealthCheck = mock(LoadBalancerHealthCheck.class); + try { + when(lbSupport.getLoadBalancerHealthCheck(anyString(), anyString())).thenReturn(loadBalancerHealthCheck); + when(lbSupport.createHealthMonitor(any(List.class), any(HealthCheckOptions.class))).thenReturn(anotherLoadBalancerHealthCheck); + when(lbSupport.modifyHealthCheck(anyString(), any(HealthCheckOptions.class))).thenCallRealMethod(); + + lbSupport.modifyHealthCheck(testProviderLBHealthCheckId, testHCO); + + ArgumentCaptor lbIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor lbHcIdCapt = ArgumentCaptor.forClass(String.class); + verify(lbSupport).getLoadBalancerHealthCheck(lbHcIdCapt.capture(), lbIdCapt.capture()); + assertEquals("Loadbalancer Healthcheck id is not as expected", testProviderLBHealthCheckId, lbHcIdCapt.getValue()); + assertEquals("Loadbalancer id is not as expected", null, lbIdCapt.getValue()); + + ArgumentCaptor lbHcCapt = ArgumentCaptor.forClass(LoadBalancerHealthCheck.class); + verify(lbSupport).safeDeleteLoadBalancerHealthCheck(lbHcCapt.capture()); + assertEquals("Loadbalancer Healthcheck object is not as expected", loadBalancerHealthCheck, lbHcCapt.getValue()); + + ArgumentCaptor lbIdsCapt = ArgumentCaptor.forClass(List.class); + ArgumentCaptor hcoCapt = ArgumentCaptor.forClass(HealthCheckOptions.class); + verify(lbSupport).createHealthMonitor(lbIdsCapt.capture(), hcoCapt.capture()); + + assertEquals("Loadbalancer Ids are not as expected", testLbIds, lbIdsCapt.getValue()); + assertEquals("HealthCheckOptions object is not as expected", testHCO, hcoCapt.getValue()); + + } + catch( InternalException | CloudException e ) { + fail("Test failed " + e.getMessage()); + } + + } + + @Test + public void safeDeleteLoadBalancerHealthCheckTest() { + final List testLbIds = Arrays.asList(testLbId); + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + LoadBalancerHealthCheck loadBalancerHealthCheck = mock(LoadBalancerHealthCheck.class); + when(loadBalancerHealthCheck.getProviderLoadBalancerIds()).thenReturn(testLbIds); + when(loadBalancerHealthCheck.getProviderLBHealthCheckId()).thenReturn(testProviderLBHealthCheckId); + try { + Mockito.doCallRealMethod().when(lbSupport).safeDeleteLoadBalancerHealthCheck(any(LoadBalancerHealthCheck.class)); + //when(method.deleteNetworks(anyString(),anyString())) + + lbSupport.safeDeleteLoadBalancerHealthCheck(loadBalancerHealthCheck); + + ArgumentCaptor lbhcIdCapt = ArgumentCaptor.forClass(String.class); + verify(lbSupport).deleteHealthMonitor(lbhcIdCapt.capture()); + assertEquals("Loadbalancer health check Id are not as expected", testProviderLBHealthCheckId, lbhcIdCapt.getValue()); + + verify(lbSupport, times(testLbIds.size())).detatchHealthCheck(anyString(), anyString()); + for( String lbId : testLbIds ) { + ArgumentCaptor lbIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor hcIdCapt = ArgumentCaptor.forClass(String.class); + verify(lbSupport).detatchHealthCheck(lbIdCapt.capture(), hcIdCapt.capture()); + assertEquals("Loadbalancer id is not as expected", lbId, lbIdCapt.getValue()); + assertEquals("Loadbalancer health check id is not as expected", testProviderLBHealthCheckId, hcIdCapt.getValue()); + } + + } + catch( InternalException | CloudException e ) { + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void removeLoadBalancerHealthCheckTest() { + final List testLbIds = Arrays.asList(testLbId); + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + LoadBalancerHealthCheck loadBalancerHealthCheck = mock(LoadBalancerHealthCheck.class); + try { + when(loadBalancerHealthCheck.getProviderLoadBalancerIds()).thenReturn(testLbIds); + when(lbSupport.listLBHealthChecks(null)).thenReturn(Arrays.asList(loadBalancerHealthCheck)); + Mockito.doCallRealMethod().when(lbSupport).removeLoadBalancerHealthCheck(anyString()); + + lbSupport.removeLoadBalancerHealthCheck(testLbId); + + ArgumentCaptor lbHcCapt = ArgumentCaptor.forClass(LoadBalancerHealthCheck.class); + verify(lbSupport).safeDeleteLoadBalancerHealthCheck(lbHcCapt.capture()); + assertEquals("Loadbalancer Healthcheck object is not as expected", loadBalancerHealthCheck, lbHcCapt.getValue()); + } + catch( InternalException | CloudException e ) { + fail("Test failed " + e.getMessage()); + } + + } + + @Test + public void createHealthMonitorTest() { + final List testLbIds = Arrays.asList(testLbId); + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + NovaMethod method = mock(NovaMethod.class); + final HealthCheckOptions testHCO = createHCO(); + final int testTimeout = 1; + JSONObject jsonObject = readJson("nova/fixtures/lb/create_health_monitor.json"); + + try { + when(lbSupport.getLoadBalancer(anyString())).thenReturn(createTestLb()); + when(lbSupport.toOSHCType(any(LoadBalancerHealthCheck.HCProtocol.class))).thenReturn("HTTP"); + when(lbSupport.getAccountNumber()).thenReturn("testAcc"); + when(lbSupport.getMethod()).thenReturn(method); + when(method.postNetworks(anyString(), anyString(), any(JSONObject.class), anyString())).thenReturn(jsonObject); + Mockito.doCallRealMethod().when(lbSupport).createHealthMonitor(anyList(), any(HealthCheckOptions.class)); + when(lbSupport.toLoadBalancerHealthCheck(any(JSONObject.class))).thenCallRealMethod(); + when(lbSupport.fromOSProtocol(anyString())).thenCallRealMethod(); + LoadBalancerHealthCheck res = lbSupport.createHealthMonitor(testLbIds, testHCO); + ArgumentCaptor lbCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor lbHealthCapt = ArgumentCaptor.forClass(String.class); + verify(lbSupport).attachHealthCheckToLoadBalancer(lbCapt.capture(), lbHealthCapt.capture()); + assertEquals("Returned timeout is not as expected", testTimeout, res.getTimeout()); + assertEquals("Returned provider load balancer health check Id does not match", "0a9ac99d-0a09-4b18-8499-a0796850279a", res.getProviderLBHealthCheckId()); + assertEquals("Returned protocol does not match", LoadBalancerHealthCheck.HCProtocol.HTTP, res.getProtocol()); + assertEquals("Returned port does not match", 9999, res.getPort()); + assertEquals("Returned interval does not match", 1, res.getInterval()); + assertEquals("Returned timeout does not match", 1, res.getTimeout()); + assertEquals("Returned unhealthyCount does not match", 5, res.getUnhealthyCount()); + assertEquals("Returned unhealthyCount does not match", 5, res.getHealthyCount()); + } + catch( InternalException | CloudException | JSONException e ) { + fail("Test failed " + e.getMessage()); + } + + } + @Test + public void deleteHealthMonitorTest() { + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + NovaMethod method = mock(NovaMethod.class); + + try { + Mockito.doCallRealMethod().when(lbSupport).deleteHealthMonitor(anyString()); + when(lbSupport.getMethod()).thenReturn(method); + lbSupport.deleteHealthMonitor(testProviderLBHealthCheckId); + verify(method, times(1)).deleteNetworks(anyString(), eq(testProviderLBHealthCheckId)); + } + catch( CloudException | InternalException e ) { + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void toLoadBalancerHealthCheck() { + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + JSONObject jsonObject = readJson("nova/fixtures/lb/get_health_check.json"); + LoadBalancer lb = mock(LoadBalancer.class); + + try { + when(lbSupport.toLoadBalancerHealthCheck(any(JSONObject.class))).thenCallRealMethod(); + when(lbSupport.fromOSProtocol(anyString())).thenCallRealMethod(); + when(lbSupport.getLoadBalancer(anyString())).thenReturn(lb); + when(lb.getListeners()).thenReturn(new LbListener[]{ LbListener.getInstance(8080, 4040) }); + LoadBalancerHealthCheck lbhc = lbSupport.toLoadBalancerHealthCheck(jsonObject.getJSONObject("health_monitor")); + assertNotNull("The LBHC object should not be null", lbhc); + assertEquals("The LBHC id is not as expected", "0a9ac99d-0a09-4b18-8499-a0796850279a", lbhc.getProviderLBHealthCheckId()); + assertEquals("The number of attached loadbalancers is not correct", 2, lbhc.getProviderLoadBalancerIds().size()); + assertEquals("The LBHC protocol is not correct", LoadBalancerHealthCheck.HCProtocol.HTTP, lbhc.getProtocol()); + assertEquals("The LBHC interval is not as expected", 2, lbhc.getInterval()); + assertEquals("The LBHC timeout is not as expected", 1, lbhc.getTimeout()); + assertEquals("The LBHC healthy count is not as expected", 5, lbhc.getHealthyCount()); + assertEquals("The LBHC unhealthy count is not as expected", 5, lbhc.getUnhealthyCount()); + assertEquals("The LBHC HTTP path is not as expected", "/index.html", lbhc.getPath()); + assertEquals("The LBHC port is not as expected", 4040, lbhc.getPort()); + assertNull("The LBHC name should be null", lbhc.getName()); + assertNull("The LBHC description should be null", lbhc.getDescription()); + assertNull("The LBHC host should be null", lbhc.getHost()); + + } catch (JSONException | InternalException | CloudException e) { + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void createListener() { + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + LbListener listener = LbListener.getInstance(80, 8080); + NovaMethod method = mock(NovaMethod.class); + try { + JSONObject result = new JSONObject(); + when(method.postNetworks(anyString(), anyString(), any(JSONObject.class), anyBoolean())).thenReturn(result); + Mockito.doCallRealMethod().when(lbSupport).createListener(anyString(), anyString(), any(LbListener.class)); + when(lbSupport.generateListenerId(anyString(), anyInt())).thenCallRealMethod(); + when(lbSupport.getMethod()).thenReturn(method); + when(lbSupport.getListenersResource()).thenCallRealMethod(); + when(lbSupport.getAccountNumber()).thenReturn(testOwnerId); + + lbSupport.createListener(testLbId, testSubnetId, listener); + + ArgumentCaptor resourceCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bodyCpt = ArgumentCaptor.forClass(JSONObject.class); + ArgumentCaptor suffixCpt = ArgumentCaptor.forClass(Boolean.class); + verify(method).postNetworks(resourceCpt.capture(), resourceIdCpt.capture(), bodyCpt.capture(), suffixCpt.capture()); + assertEquals("Resource parameter is wrong", lbSupport.getListenersResource(), resourceCpt.getValue()); + assertNull("Resource Id should be null", resourceIdCpt.getValue()); + JSONObject body = bodyCpt.getValue(); + assertNotNull("Body parameter should not be null", body); + assertTrue("Body parameter should contain root element 'vip'", body.has("vip")); + assertTrue("The value of root element 'vip' must implement Map", body.get("vip") instanceof Map); + Map vip = (Map) body.get("vip"); + assertEquals("Root element 'vip' should contain 6 subelements", 6, vip.size()); + assertEquals("VIP tenant id is not as expected", testOwnerId, vip.get("tenant_id")); + assertEquals("VIP protocol is not as expected", "TCP", vip.get("protocol")); + assertEquals("VIP protocol port is not as expected", 80, vip.get("protocol_port")); + assertEquals("VIP name is not as expected", "testLbId:8080", vip.get("name")); + assertEquals("VIP subnet id is not as expected", testSubnetId, vip.get("subnet_id")); + assertEquals("VIP pool id is not as expected", testLbId, vip.get("pool_id")); + assertEquals("Suffix parameter is wrong", false, suffixCpt.getValue()); + } catch (Exception e) { + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void createMember() { + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + NovaMethod method = mock(NovaMethod.class); + try { + JSONObject result = new JSONObject(); + when(method.postNetworks(anyString(), anyString(), any(JSONObject.class), anyBoolean())).thenReturn(result); + Mockito.doCallRealMethod().when(lbSupport).createMember(anyString(), anyString(), anyInt()); + when(lbSupport.getMethod()).thenReturn(method); + when(lbSupport.getMembersResource()).thenCallRealMethod(); + when(lbSupport.getAccountNumber()).thenReturn(testOwnerId); + + lbSupport.createMember(testLbId, testIpAddress1, testPrivatePort); + + ArgumentCaptor resourceCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bodyCpt = ArgumentCaptor.forClass(JSONObject.class); + ArgumentCaptor suffixCpt = ArgumentCaptor.forClass(Boolean.class); + verify(method).postNetworks(resourceCpt.capture(), resourceIdCpt.capture(), bodyCpt.capture(), suffixCpt.capture()); + assertEquals("Resource parameter is wrong", lbSupport.getMembersResource(), resourceCpt.getValue()); + assertNull("Resource Id should be null", resourceIdCpt.getValue()); + JSONObject body = bodyCpt.getValue(); + assertNotNull("Body parameter should not be null", body); + assertTrue("Body parameter should contain root element 'member'", body.has("member")); + assertTrue("The value of root element 'member' must implement Map", body.get("member") instanceof Map); + Map member = (Map) body.get("member"); + assertEquals("Root element 'member' should contain 4 subelements", 4, member.size()); + assertEquals("Member tenant id is not as expected", testOwnerId, member.get("tenant_id")); + assertEquals("Member protocol port is not as expected", testPrivatePort, member.get("protocol_port")); + assertEquals("Member address is not as expected", testIpAddress1, member.get("address")); + assertEquals("Member pool id is not as expected", testLbId, member.get("pool_id")); + assertEquals("Suffix parameter is wrong", false, suffixCpt.getValue()); + } catch (Exception e) { + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void findAllVips() { + fail("Test not implemented"); + } + + @Test + public void findAllMembers() { + fail("Test not implemented"); + } + + @Test + public void findLoadBalancers() { + fail("Test not implemented"); + } + + @Test + public void toLoadBalancer() { + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + JSONObject jsonObject = readJson("nova/fixtures/lb/get_pools.json"); + + try { + List jsonListeners = Arrays.asList( + readJson("nova/fixtures/lb/get_vips.json").getJSONArray("vips").getJSONObject(0)); + + List jsonMembers = Arrays.asList( + readJson("nova/fixtures/lb/get_member.json").getJSONObject("member")); + + when(lbSupport.toLoadBalancer(any(JSONObject.class), anyList(), anyList())).thenCallRealMethod(); + when(lbSupport.getCurrentRegionId()).thenReturn("testRegion"); + when(lbSupport.findListenerByLbId(anyList(), anyString())).thenCallRealMethod(); + when(lbSupport.findAllVips(anyString())).thenReturn(jsonListeners); + LoadBalancer lb = lbSupport.toLoadBalancer( + jsonObject.getJSONArray("pools").getJSONObject(0), + jsonListeners, jsonMembers); + // let's check everything now + assertNotNull("Loadbalancer object cannot be null", lb); + assertEquals("LB address is not as expected", "10.0.0.10", lb.getAddress()); + assertEquals("LB address type is not as expected", LoadBalancerAddressType.IP, lb.getAddressType()); + assertEquals("LB timestamp is not as expected", 0, lb.getCreationTimestamp()); // no information on this so 0 is good + assertEquals("LB current state is not as expected", LoadBalancerState.ACTIVE, lb.getCurrentState()); + assertEquals("LB description should be empty", "", lb.getDescription()); + assertEquals("LB type is not as expected", LbType.EXTERNAL, lb.getType()); + assertEquals("The number of listeners is wrong", 1, lb.getListeners().length); + LbListener listener = lb.getListeners()[0]; + assertEquals("Listener algo is not as expected", LbAlgorithm.ROUND_ROBIN, listener.getAlgorithm()); + assertEquals("Listener cookie should be null", null, listener.getCookie()); + assertEquals("Listener network protocol is not as expected", LbProtocol.HTTP, listener.getNetworkProtocol()); + assertEquals("Listener persistence is not as expected", LbPersistence.COOKIE, listener.getPersistence()); // but why cookie is null? + assertEquals("Listener private port is not as expected", 8080, listener.getPrivatePort()); + assertEquals("Listener public port is not as expected", 80, listener.getPublicPort()); + assertEquals("Listener SSL cert name should be null as they are not supported in Lbaas 1.0", + null, listener.getSslCertificateName()); + assertEquals("Listener LBHC id is expected to be null", null, listener.getProviderLBHealthCheckId()); + assertEquals("LB name is not as expected", "app_pool", lb.getName()); + assertEquals("The number of datacenters is wrong", 1, lb.getProviderDataCenterIds().length); + assertEquals("LB datacenter id is not as expected", "testRegion-a", lb.getProviderDataCenterIds()[0]); + assertEquals("LB id is not as expected", "72741b06-df4d-4715-b142-276b6bce75ab", lb.getProviderLoadBalancerId()); + assertEquals("LB owner id is not as expected", "83657cfcdfe44cd5920adaf26c48ceea", lb.getProviderOwnerId()); + assertEquals("LB region id is not as expected", "testRegion", lb.getProviderRegionId()); + int subnetCount = 0; + for( String id : lb.getProviderSubnetIds() ) { + subnetCount++; + } + assertEquals("The number of subnets is wrong", 1, subnetCount); + assertEquals("LB subnet id is not as expected", "8032909d-47a1-4715-90af-5153ffe39861", lb.getProviderSubnetIds().iterator().next()); + assertEquals("The number of public ports is wrong", 1, lb.getPublicPorts().length); + assertEquals("LB public port is not as expected", 80, lb.getPublicPorts()[0]); + assertArrayEquals("LB supported IP version is not as expected", new IPVersion[] { IPVersion.IPV4 }, lb.getSupportedTraffic()); + assertEquals("LB HC id is not as expected", "466c8345-28d8-4f84-a246-e04380b0461d", lb.getProviderLBHealthCheckId()); + assertNull("The firewalls are expected to be null", lb.getProviderFirewallIds()); // FIXME: that's a core bug, must be an empty array/list + assertEquals("LB visible scope is not as expected", VisibleScope.ACCOUNT_REGION, lb.getVisibleScope()); + assertEquals("LB VLAN id should be null", null, lb.getProviderVlanId()); + } catch( JSONException | InternalException | CloudException e ) { + e.printStackTrace(); + fail("Test failed " + e.getMessage()); + } + } + + @Test + public void removeLoadBalancer() { + fail("Test not implemented"); + } + + @Test + public void getLoadBalancer() { + fail("Test not implemented"); + } + +} + diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/network/QuantumTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/network/QuantumTest.java index 0b35de7..aa0824c 100644 --- a/src/test/java/org/dasein/cloud/openstack/nova/os/network/QuantumTest.java +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/network/QuantumTest.java @@ -7,6 +7,7 @@ import org.dasein.cloud.compute.VirtualMachineSupport; import org.dasein.cloud.network.*; import org.dasein.cloud.openstack.nova.os.NovaMethod; +import org.dasein.cloud.openstack.nova.os.OpenStackTest; import org.dasein.cloud.test.network.NetworkResources; import org.json.JSONArray; import org.json.JSONException; @@ -32,22 +33,7 @@ /** * Created by mariapavlova on 15/09/2015. */ -public class QuantumTest { - - - private JSONObject readJson(String filename) { - try { - InputStream is = getClass().getClassLoader().getResourceAsStream(filename); - String jsonText = IOUtils.toString(is); - return new JSONObject(jsonText); - } - catch( JSONException e ) { - throw new RuntimeException(e); - } - catch( IOException e ) { - throw new RuntimeException(e); - } - } +public class QuantumTest extends OpenStackTest { @Test public void listVlansTest() { @@ -96,18 +82,9 @@ public void listPortsTest() { NovaMethod method = mock(NovaMethod.class); Quantum quantum = mock(Quantum.class); VirtualMachine mv = mock(VirtualMachine.class); - JSONObject json = null; - try { - InputStream is = getClass().getClassLoader().getResourceAsStream("nova/fixtures/list_ports.json"); - String jsonText = IOUtils.toString(is); - json = new JSONObject(jsonText); - } - catch( IOException e ) { - throw new RuntimeException(e); - } - catch( JSONException e ) { - throw new RuntimeException(e); - } + + JSONObject json = readJson("nova/fixtures/list_ports.json"); + when(quantum.getMethod()).thenReturn(method); when(mv.getProviderVirtualMachineId()).thenReturn("blah"); try { @@ -134,18 +111,7 @@ public void listSubnetsTest() { NovaMethod method = mock(NovaMethod.class); Quantum quantum = mock(Quantum.class); VirtualMachine vm = mock(VirtualMachine.class); - JSONObject json = null; - try { - InputStream is = getClass().getClassLoader().getResourceAsStream("nova/fixtures/list_subnets.json"); - String jsonText = IOUtils.toString(is); - json = new JSONObject(jsonText); - } - catch( JSONException e ) { - throw new RuntimeException(e); - } - catch( IOException e ) { - throw new RuntimeException(e); - } + JSONObject json = readJson("nova/fixtures/list_subnets.json"); when(quantum.getMethod()).thenReturn(method); try { when(quantum.getNetworkType()).thenReturn(Quantum.QuantumType.QUANTUM); @@ -172,10 +138,10 @@ public void listSubnetsTest() { } catch( CloudException e ) { - e.printStackTrace(); + fail("Unexpected exception " + e); } catch( InternalException e ) { - e.printStackTrace(); + fail("Unexpected exception " + e); } } @@ -184,18 +150,7 @@ public void listSubnetsTest() { public void getVlanTest() { NovaMethod method = mock(NovaMethod.class); Quantum quantum = mock(Quantum.class); - JSONObject json = null; - try { - InputStream is = getClass().getClassLoader().getResourceAsStream("nova/fixtures/get_vlan.json"); - String jsonText = IOUtils.toString(is); - json = new JSONObject(jsonText); - } - catch( JSONException e ) { - throw new RuntimeException(e); - } - catch( IOException e ) { - throw new RuntimeException(e); - } + JSONObject json = readJson("nova/fixtures/get_vlan.json"); try { when(quantum.getMethod()).thenReturn(method); when(quantum.getNetworkType()).thenReturn(Quantum.QuantumType.QUANTUM); @@ -209,10 +164,10 @@ public void getVlanTest() { } catch( CloudException e ) { - e.printStackTrace(); + fail("Unexpected exception " + e); } catch( InternalException e ) { - e.printStackTrace(); + fail("Unexpected exception " + e); } } @@ -220,18 +175,7 @@ public void getVlanTest() { public void getSubnetTest() { NovaMethod method = mock(NovaMethod.class); Quantum quantum = mock(Quantum.class); - JSONObject json = null; - try { - InputStream is = getClass().getClassLoader().getResourceAsStream("nova/fixtures/get_subnet.json"); - String jsonText = IOUtils.toString(is); - json = new JSONObject(jsonText); - } - catch( JSONException e ) { - throw new RuntimeException(e); - } - catch( IOException e ) { - throw new RuntimeException(e); - } + JSONObject json = readJson("nova/fixtures/get_subnet.json"); try { when(quantum.getMethod()).thenReturn(method); when(quantum.getNetworkType()).thenReturn(Quantum.QuantumType.QUANTUM); @@ -248,10 +192,10 @@ public void getSubnetTest() { } catch( CloudException e ) { - e.printStackTrace(); + fail("Unexpected exception " + e); } catch( InternalException e ) { - e.printStackTrace(); + fail("Unexpected exception " + e); } } @@ -381,7 +325,7 @@ public void createVlanTest() { fail("Test failed " + e.getMessage()); } catch( JSONException e ) { - e.printStackTrace(); + fail("Test failed " + e.getMessage()); } } @@ -423,18 +367,7 @@ public void getNetworkResourceTest() { public void getNetworkResourceVersionTest() { NovaMethod method = mock(NovaMethod.class); Quantum quantum = mock(Quantum.class); - JSONObject json = null; - try { - InputStream is = getClass().getClassLoader().getResourceAsStream("nova/fixtures/get_networkResourceVersion.json"); - String jsonText = IOUtils.toString(is); - json = new JSONObject(jsonText); - } - catch( JSONException e ) { - throw new RuntimeException(e); - } - catch( IOException e ) { - throw new RuntimeException(e); - } + JSONObject json = readJson("nova/fixtures/get_networkResourceVersion.json"); try { when(quantum.getMethod()).thenReturn(method); when(method.getNetworks(anyString(), anyString(), anyBoolean())).thenReturn(json); @@ -491,18 +424,7 @@ public void getSubnetResource() { public void isSubscribedTest() { NovaMethod method = mock(NovaMethod.class); Quantum quantum = mock(Quantum.class); - JSONObject json = null; - try { - InputStream is = getClass().getClassLoader().getResourceAsStream("nova/fixtures/get_vlan.json"); - String jsonText = IOUtils.toString(is); - json = new JSONObject(jsonText); - } - catch( JSONException e ) { - throw new RuntimeException(e); - } - catch( IOException e ) { - throw new RuntimeException(e); - } + JSONObject json = readJson("nova/fixtures/get_vlan.json"); try { when(quantum.getMethod()).thenReturn(method); when(quantum.getNetworkType()).thenReturn(Quantum.QuantumType.QUANTUM); @@ -523,21 +445,11 @@ public void isSubscribedTest() { public void listPortsByNetworkIdTest() { NovaMethod method = mock(NovaMethod.class); Quantum quantum = mock(Quantum.class); - JSONObject json = null; + JSONObject json = readJson("nova/fixtures/list_ports.json"); final String testVlanId = "testVlanId"; VLAN vlan = new VLAN(); vlan.setProviderVlanId(testVlanId); - try { - InputStream is = getClass().getClassLoader().getResourceAsStream("nova/fixtures/list_ports.json"); - String jsonText = IOUtils.toString(is); - json = new JSONObject(jsonText); - } - catch( IOException e ) { - throw new RuntimeException(e); - } - catch( JSONException e ) { - throw new RuntimeException(e); - } + when(quantum.getMethod()).thenReturn(method); try { when(quantum.getNetworkType()).thenReturn(Quantum.QuantumType.QUANTUM); @@ -566,19 +478,8 @@ public void listPortsBySubnetId() { NovaMethod method = mock(NovaMethod.class); Quantum quantum = mock(Quantum.class); Subnet subnet = mock(Subnet.class); - JSONObject json = null; + JSONObject json = readJson("nova/fixtures/list_ports.json"); final String testSubnetId = "66435044-1513-4f23-9f65-5557b130a008"; - try { - InputStream is = getClass().getClassLoader().getResourceAsStream("nova/fixtures/list_ports.json"); - String jsonText = IOUtils.toString(is); - json = new JSONObject(jsonText); - } - catch( IOException e ) { - throw new RuntimeException(e); - } - catch( JSONException e ) { - throw new RuntimeException(e); - } when(quantum.getMethod()).thenReturn(method); when(subnet.getProviderVlanId()).thenReturn(testSubnetId); try { @@ -835,6 +736,7 @@ public void toSubnetTest() { throw new RuntimeException("Error while handling JSON", e); } } + @Test public void toVlanTest() { Quantum quantum = mock(Quantum.class); @@ -845,7 +747,7 @@ public void toVlanTest() { vlan.setDescription("testDescription"); final String networkId = "testId"; final String testSubnetId = "testSubnetId"; + // TODO } - - } +} diff --git a/src/test/resources/nova/fixtures/lb/create_health_monitor.json b/src/test/resources/nova/fixtures/lb/create_health_monitor.json new file mode 100644 index 0000000..61b0ceb --- /dev/null +++ b/src/test/resources/nova/fixtures/lb/create_health_monitor.json @@ -0,0 +1,19 @@ +{ + "health_monitor": { + "admin_state_up": true, + "delay": 1, + "expected_codes": "200,201,202", + "http_method": "GET", + "id": "0a9ac99d-0a09-4b18-8499-a0796850279a", + "max_retries": 5, + "pools": [ + { + "pool_id": "74aa2010-a59f-4d35-a436-60a6da882819" + } + ], + "tenant_id": "6f3584d5754048a18e30685362b88411", + "timeout": 1, + "type": "HTTP", + "url_path": "/index.html" + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/lb/get_health_check.json b/src/test/resources/nova/fixtures/lb/get_health_check.json new file mode 100644 index 0000000..1d7e8aff --- /dev/null +++ b/src/test/resources/nova/fixtures/lb/get_health_check.json @@ -0,0 +1,22 @@ +{ + "health_monitor": { + "admin_state_up": true, + "delay": 2, + "expected_codes": "200,201,202", + "http_method": "GET", + "id": "0a9ac99d-0a09-4b18-8499-a0796850279a", + "max_retries": 5, + "pools": [ + { + "pool_id": "74aa2010-a59f-4d35-a436-60a6da882819" + }, + { + "pool_id": "74aa2010-a59f-4d35-a436-60a6da882820" + } + ], + "tenant_id": "6f3584d5754048a18e30685362b88411", + "timeout": 1, + "type": "HTTP", + "url_path": "/index.html" + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/lb/get_health_checks.json b/src/test/resources/nova/fixtures/lb/get_health_checks.json new file mode 100644 index 0000000..e825c9a --- /dev/null +++ b/src/test/resources/nova/fixtures/lb/get_health_checks.json @@ -0,0 +1,22 @@ +{ + "health_monitor": { + "admin_state_up": true, + "delay": 1, + "expected_codes": "200,201,202", + "http_method": "GET", + "id": "0a9ac99d-0a09-4b18-8499-a0796850279a", + "max_retries": 5, + "pools": [ + { + "pool_id": "74aa2010-a59f-4d35-a436-60a6da882819" + }, + { + "pool_id": "74aa2010-a59f-4d35-a436-60a6da882820" + } + ], + "tenant_id": "6f3584d5754048a18e30685362b88411", + "timeout": 1, + "type": "HTTP", + "url_path": "/index.html" + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/lb/get_member.json b/src/test/resources/nova/fixtures/lb/get_member.json new file mode 100644 index 0000000..b81586f --- /dev/null +++ b/src/test/resources/nova/fixtures/lb/get_member.json @@ -0,0 +1,11 @@ +{ + "member": { + "address": "10.0.0.8", + "admin_state_up": true, + "id": "9a7aff27-fd41-4ec1-ba4c-3eb92c629313", + "protocol_port": 8080, + "pool_id": "72741b06-df4d-4715-b142-276b6bce75ab", + "tenant_id": "1a3e005cf9ce40308c900bcb08e5320c", + "weight": 1 + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/lb/get_pools.json b/src/test/resources/nova/fixtures/lb/get_pools.json new file mode 100644 index 0000000..1c36359 --- /dev/null +++ b/src/test/resources/nova/fixtures/lb/get_pools.json @@ -0,0 +1,24 @@ +{ + "pools": [ + { + "status": "ACTIVE", + "lb_method": "ROUND_ROBIN", + "protocol": "HTTP", + "description": "", + "health_monitors": [ + "466c8345-28d8-4f84-a246-e04380b0461d", + "5d4b5228-33b0-4e60-b225-9b727c1a20e7" + ], + "subnet_id": "8032909d-47a1-4715-90af-5153ffe39861", + "tenant_id": "83657cfcdfe44cd5920adaf26c48ceea", + "admin_state_up": true, + "name": "app_pool", + "members": [ + "701b531b-111a-4f21-ad85-4795b7b12af6", + "beb53b4d-230b-4abd-8118-575b8fa006ef" + ], + "id": "72741b06-df4d-4715-b142-276b6bce75ab", + "vip_id": "4ec89087-d057-4e2c-911f-60a3b47ee304" + } + ] +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/lb/get_vips.json b/src/test/resources/nova/fixtures/lb/get_vips.json new file mode 100644 index 0000000..47d0d4f --- /dev/null +++ b/src/test/resources/nova/fixtures/lb/get_vips.json @@ -0,0 +1,23 @@ +{ + "vips": [ + { + "status": "ACTIVE", + "protocol": "HTTP", + "description": "", + "admin_state_up": true, + "subnet_id": "8032909d-47a1-4715-90af-5153ffe39861", + "tenant_id": "83657cfcdfe44cd5920adaf26c48ceea", + "connection_limit": 1000, + "pool_id": "72741b06-df4d-4715-b142-276b6bce75ab", + "session_persistence": { + "cookie_name": "MyAppCookie", + "type": "APP_COOKIE" + }, + "address": "10.0.0.10", + "protocol_port": 80, + "port_id": "b5a743d6-056b-468b-862d-fb13a9aa694e", + "id": "4ec89087-d057-4e2c-911f-60a3b47ee304", + "name": "my-vip" + } + ] +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/lb/list_health_checks.json b/src/test/resources/nova/fixtures/lb/list_health_checks.json new file mode 100644 index 0000000..ba4af5b --- /dev/null +++ b/src/test/resources/nova/fixtures/lb/list_health_checks.json @@ -0,0 +1,35 @@ +{ + "health_monitors":[ + { + "admin_state_up":true, + "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", + "delay":10, + "max_retries":1, + "timeout":1, + "type":"PING", + "pools": [ + { + "pool_id": "lbId" + } + ], + "id":"466c8345-28d8-4f84-a246-e04380b0461d" + }, + { + "admin_state_up":true, + "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", + "delay":5, + "expected_codes":"200", + "max_retries":2, + "http_method":"GET", + "pools": [ + { + "pool_id": "lbId" + } + ], + "timeout":2, + "url_path":"/", + "type":"HTTP", + "id":"5d4b5228-33b0-4e60-b225-9b727c1a20e7" + } + ] +} \ No newline at end of file From 581fedd96e6eeff5e9b4784e423215fcc2d969e9 Mon Sep 17 00:00:00 2001 From: mariapavlova Date: Fri, 22 Jan 2016 13:04:59 +0000 Subject: [PATCH 2/7] More loadbalancer tests --- .../os/network/LoadBalancerSupportImpl.java | 4 +- .../network/LoadBalancerSupportImplTest.java | 227 +++++++++++++++++- .../resources/nova/fixtures/lb/get_pool.json | 22 ++ 3 files changed, 245 insertions(+), 8 deletions(-) create mode 100644 src/test/resources/nova/fixtures/lb/get_pool.json diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java index f32c977..2e18eef 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java @@ -663,7 +663,7 @@ protected List findAllMembers(@Nullable String loadBalancerId) throw * @throws CloudException * @throws InternalException */ - private List findLoadBalancers(@Nullable String loadBalancerId) throws CloudException, InternalException { + protected List findLoadBalancers(@Nullable String loadBalancerId) throws CloudException, InternalException { APITrace.begin(getProvider(), "LB.listLoadBalancers"); try { // get all vips, optionally filtered by lbId @@ -908,7 +908,7 @@ private String toOSAlgorithm(LbAlgorithm algorithm) { } // Below is the list of resource endpoints, these will change in LBaaS 2.0 - private String getLoadBalancersResource() { + protected String getLoadBalancersResource() { return "v2.0/lb/pools"; } diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java index 244481f..8704e98 100644 --- a/src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java @@ -17,6 +17,7 @@ import java.util.*; +import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.*; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.*; @@ -475,17 +476,184 @@ public void createMember() { @Test public void findAllVips() { - fail("Test not implemented"); + NovaMethod method = mock(NovaMethod.class); + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + JSONObject jsonObject = readJson("nova/fixtures/lb/get_vips.json"); + LoadBalancer lb = createTestLb(); + try { + when(lbSupport.getMethod()).thenReturn(method); + when(lbSupport.getAccountNumber()).thenReturn(testOwnerId); + when(method.getNetworks(anyString(), anyString(), anyBoolean(), anyString())).thenReturn(jsonObject); + when(lbSupport.findAllVips(anyString())).thenCallRealMethod(); + + List result = lbSupport.findAllVips(testLbId); + + assertNotNull("List of VIPs cannot be null", result); + ArgumentCaptor resourceCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor suffixCpt = ArgumentCaptor.forClass(Boolean.class); + ArgumentCaptor queryCpt = ArgumentCaptor.forClass(String.class); + verify(method, times(1)).getNetworks(resourceCpt.capture(), resourceIdCpt.capture(), suffixCpt.capture(), queryCpt.capture()); + assertEquals("Resource is not correct", lbSupport.getLoadBalancersResource(), resourceCpt.getValue()); + assertEquals("ResourceId is not correct", null, resourceIdCpt.getValue()); + assertEquals("Suffix is not correct", false, suffixCpt.getValue()); + assertEquals("Query is not correct", "?tenant_id="+ testOwnerId, queryCpt.getValue()); + + } + catch( CloudException e ) { + e.printStackTrace(); + } + catch( InternalException e ) { + e.printStackTrace(); + } + } @Test public void findAllMembers() { - fail("Test not implemented"); + NovaMethod method = mock(NovaMethod.class); + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + JSONObject jsonObject = readJson("nova/fixtures/lb/get_member.json"); + LoadBalancer lb = createTestLb(); + try { + when(lbSupport.getMethod()).thenReturn(method); + when(lbSupport.getAccountNumber()).thenReturn(testOwnerId); + when(method.getNetworks(anyString(), anyString(), anyBoolean(), anyString())).thenReturn(jsonObject); + when(lbSupport.findAllMembers(anyString())).thenCallRealMethod(); + + List result = lbSupport.findAllMembers(testLbId); + + assertNotNull("List of members cannot be null", result); + ArgumentCaptor resourceCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor suffixCpt = ArgumentCaptor.forClass(Boolean.class); + ArgumentCaptor queryCpt = ArgumentCaptor.forClass(String.class); + verify(method, times(1)).getNetworks(resourceCpt.capture(), resourceIdCpt.capture(), suffixCpt.capture(), queryCpt.capture()); + assertEquals("Resource is not correct", lbSupport.getLoadBalancersResource(), resourceCpt.getValue()); + assertEquals("ResourceId is not correct", null, resourceIdCpt.getValue()); + assertEquals("Suffix is not correct", false, suffixCpt.getValue()); + assertEquals("Query is not correct", "?tenant_id="+ testOwnerId, queryCpt.getValue()); + + } + catch( CloudException e ) { + e.printStackTrace(); + } + catch( InternalException e ) { + e.printStackTrace(); + } + } @Test - public void findLoadBalancers() { - fail("Test not implemented"); + public void findLoadBalancersWithoutId() { + NovaMethod method = mock(NovaMethod.class); + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + JSONObject jsonObject = readJson("nova/fixtures/lb/get_pools.json"); + LoadBalancer lb = createTestLb(); + + try { + List jsonListeners = Arrays.asList( + readJson("nova/fixtures/lb/get_vips.json").getJSONArray("vips").getJSONObject(0)); + List jsonMembers = Arrays.asList( + readJson("nova/fixtures/lb/get_member.json").getJSONObject("member")); + when(lbSupport.getAccountNumber()).thenReturn(testOwnerId); + when(lbSupport.findAllVips(anyString())).thenReturn(jsonListeners); + when(lbSupport.findAllMembers(anyString())).thenReturn(jsonMembers); + when(lbSupport.getMethod()).thenReturn(method); + when(method.getNetworks(anyString(), anyString(), anyBoolean(), anyString())).thenReturn(jsonObject); + when(lbSupport.toLoadBalancer(any(JSONObject.class), anyList(), anyList())).thenReturn(lb); + when(lbSupport.findLoadBalancers(anyString())).thenCallRealMethod(); + + List result = lbSupport.findLoadBalancers(null); + + assertNotNull("List of loadbalancers cannot be null", result); + assertThat("The number of returned loadbalancers is not correct", result.size(), greaterThan(0)); + ArgumentCaptor lbIdCpt = ArgumentCaptor.forClass(String.class); + verify(lbSupport, times(1)).findAllVips(lbIdCpt.capture()); + assertEquals("LoadbalancerId passed to findAllVips is incorrect", null, lbIdCpt.getValue()); + + verify(lbSupport, times(1)).findAllMembers(lbIdCpt.capture()); + assertEquals("LoadbalancerId passed to findAllMembers is incorrect", null, lbIdCpt.getValue()); + + ArgumentCaptor resourceCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor suffixCpt = ArgumentCaptor.forClass(Boolean.class); + ArgumentCaptor queryCpt = ArgumentCaptor.forClass(String.class); + verify(method, times(1)).getNetworks(resourceCpt.capture(), resourceIdCpt.capture(), suffixCpt.capture(), queryCpt.capture()); + assertEquals("Resource is not correct", lbSupport.getLoadBalancersResource(), resourceCpt.getValue()); + assertEquals("ResourceId is not correct", null, resourceIdCpt.getValue()); + assertEquals("Suffix is not correct", false, suffixCpt.getValue()); + assertEquals("Query is not correct", "?tenant_id="+ testOwnerId, queryCpt.getValue()); + + + } + catch( CloudException e ) { + fail("Test failed " + e.getMessage()); + } + catch( InternalException e ) { + fail("Test failed " + e.getMessage()); + } + catch( JSONException e ) { + fail("Test failed " + e.getMessage()); + } + + + } + + @Test + public void findLoadBalancersWithId() { + NovaMethod method = mock(NovaMethod.class); + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + JSONObject jsonObject = readJson("nova/fixtures/lb/get_pool.json"); + LoadBalancer lb = createTestLb(); + + try { + List jsonListeners = Arrays.asList( + readJson("nova/fixtures/lb/get_vips.json").getJSONArray("vips").getJSONObject(0)); + List jsonMembers = Arrays.asList( + readJson("nova/fixtures/lb/get_member.json").getJSONObject("member")); + when(lbSupport.getAccountNumber()).thenReturn(testOwnerId); + when(lbSupport.findAllVips(anyString())).thenReturn(jsonListeners); + when(lbSupport.findAllMembers(anyString())).thenReturn(jsonMembers); + when(lbSupport.getMethod()).thenReturn(method); + when(method.getNetworks(anyString(), anyString(), anyBoolean(), anyString())).thenReturn(jsonObject); + when(lbSupport.toLoadBalancer(any(JSONObject.class), anyList(), anyList())).thenReturn(lb); + when(lbSupport.findLoadBalancers(anyString())).thenCallRealMethod(); + + List result = lbSupport.findLoadBalancers(testLbId); + + assertNotNull("List of loadbalancers cannot be null", result); + assertThat("The number of returned loadbalancers is not correct", result.size(), greaterThan(0)); + ArgumentCaptor lbIdCpt = ArgumentCaptor.forClass(String.class); + verify(lbSupport, times(1)).findAllVips(lbIdCpt.capture()); + assertEquals("LoadbalancerId passed to findAllVips is incorrect", testLbId, lbIdCpt.getValue()); + + verify(lbSupport, times(1)).findAllMembers(lbIdCpt.capture()); + assertEquals("LoadbalancerId passed to findAllMembers is incorrect", testLbId, lbIdCpt.getValue()); + + ArgumentCaptor resourceCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor suffixCpt = ArgumentCaptor.forClass(Boolean.class); + ArgumentCaptor queryCpt = ArgumentCaptor.forClass(String.class); + verify(method, times(1)).getNetworks(resourceCpt.capture(), resourceIdCpt.capture(), suffixCpt.capture(), queryCpt.capture()); + assertEquals("Resource is not correct", lbSupport.getLoadBalancersResource(), resourceCpt.getValue()); + assertEquals("ResourceId is not correct", testLbId, resourceIdCpt.getValue()); + assertEquals("Suffix is not correct", false, suffixCpt.getValue()); + assertEquals("Query is not correct", "?tenant_id="+ testOwnerId, queryCpt.getValue()); + + + } + catch( CloudException e ) { + fail("Test failed " + e.getMessage()); + } + catch( InternalException e ) { + fail("Test failed " + e.getMessage()); + } + catch( JSONException e ) { + fail("Test failed " + e.getMessage()); + } + + } @Test @@ -553,12 +721,59 @@ public void toLoadBalancer() { @Test public void removeLoadBalancer() { - fail("Test not implemented"); + NovaMethod method = mock(NovaMethod.class); + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + LoadBalancer lb = createTestLb(); + try { + List jsonListeners = Arrays.asList( + readJson("nova/fixtures/lb/get_vips.json").getJSONArray("vips").getJSONObject(0)); + when(lbSupport.getLoadBalancer(anyString())).thenReturn(lb); + Mockito.doCallRealMethod().when(lbSupport).removeLoadBalancer(anyString()); + when(lbSupport.findAllVips(anyString())).thenReturn(jsonListeners); + when(lbSupport.getMethod()).thenReturn(method); + lbSupport.removeLoadBalancer(testLbId); + ArgumentCaptor resourceCpt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCpt = ArgumentCaptor.forClass(String.class); + + verify(method, times(2)).deleteNetworks(resourceCpt.capture(), resourceIdCpt.capture()); + assertEquals("Resource parameter when deleting a listener was wrong", + lbSupport.getListenersResource(), resourceCpt.getAllValues().get(0)); + assertEquals("Resource Id parameter when deleting a listener was wrong", + "4ec89087-d057-4e2c-911f-60a3b47ee304", resourceIdCpt.getAllValues().get(0)); + + assertEquals("Resource parameter when deleting a loadbalancer was wrong", + lbSupport.getLoadBalancersResource(), resourceCpt.getAllValues().get(1)); + assertEquals("Resource Id parameter when deleting a loadbalancer was wrong", + testLbId, resourceIdCpt.getAllValues().get(1)); + + + } + catch( CloudException e ) { + fail("Test failed " + e.getMessage()); + + } + catch( InternalException e ) { + fail("Test failed " + e.getMessage()); + } + catch( JSONException e ) { + fail("Test failed " + e.getMessage()); + } + } @Test public void getLoadBalancer() { - fail("Test not implemented"); + LoadBalancerSupportImpl lbSupport = mock(LoadBalancerSupportImpl.class); + LoadBalancer lb = createTestLb(); + try { + when(lbSupport.getLoadBalancer(anyString())).thenCallRealMethod(); + when(lbSupport.findLoadBalancers(anyString())).thenReturn(Collections.singletonList(lb)); + LoadBalancer loadBalancer = lbSupport.getLoadBalancer(testLbId); + assertEquals("Returned loadbalancer is not correct", lb, loadBalancer); + } + catch( CloudException | InternalException e ) { + fail("Test failed " + e.getMessage()); + } } } diff --git a/src/test/resources/nova/fixtures/lb/get_pool.json b/src/test/resources/nova/fixtures/lb/get_pool.json new file mode 100644 index 0000000..a8fc525 --- /dev/null +++ b/src/test/resources/nova/fixtures/lb/get_pool.json @@ -0,0 +1,22 @@ +{ + "pool": { + "status": "ACTIVE", + "lb_method": "ROUND_ROBIN", + "protocol": "HTTP", + "description": "", + "health_monitors": [ + "466c8345-28d8-4f84-a246-e04380b0461d", + "5d4b5228-33b0-4e60-b225-9b727c1a20e7" + ], + "subnet_id": "8032909d-47a1-4715-90af-5153ffe39861", + "tenant_id": "83657cfcdfe44cd5920adaf26c48ceea", + "admin_state_up": true, + "name": "app_pool", + "members": [ + "701b531b-111a-4f21-ad85-4795b7b12af6", + "beb53b4d-230b-4abd-8118-575b8fa006ef" + ], + "id": "72741b06-df4d-4715-b142-276b6bce75ab", + "vip_id": "4ec89087-d057-4e2c-911f-60a3b47ee304" + } +} \ No newline at end of file From 26867585484aa86ce9a9b5f6b7fb8cb541949f12 Mon Sep 17 00:00:00 2001 From: mariapavlova Date: Tue, 26 Jan 2016 18:05:32 +0000 Subject: [PATCH 3/7] Exceptions handling for Openstack --- .../openstack/nova/os/AbstractMethod.java | 200 ++++++--------- .../nova/os/NovaLocationServices.java | 11 +- .../cloud/openstack/nova/os/NovaMethod.java | 44 ++-- .../openstack/nova/os/NovaOpenStack.java | 16 +- .../cloud/openstack/nova/os/SwiftMethod.java | 18 +- .../nova/os/compute/CinderSnapshot.java | 74 +++--- .../nova/os/compute/CinderVolume.java | 164 +++---------- .../openstack/nova/os/compute/NovaImage.java | 85 +++---- .../openstack/nova/os/compute/NovaServer.java | 101 ++++---- .../openstack/nova/os/ext/hp/cdn/HPCDN.java | 14 +- .../openstack/nova/os/ext/hp/db/HPRDBMS.java | 231 +++++------------- .../os/ext/rackspace/cdn/RackspaceCDN.java | 2 +- .../os/ext/rackspace/db/RackspaceRDBMS.java | 146 ++++------- .../ext/rackspace/dns/RackspaceCloudDNS.java | 53 ++-- .../rackspace/lb/RackspaceLBCapabilities.java | 3 +- .../rackspace/lb/RackspaceLoadBalancers.java | 187 ++++---------- .../nova/os/identity/NovaKeypair.java | 138 ++++------- .../os/network/LoadBalancerSupportImpl.java | 57 +++-- .../nova/os/network/NovaFloatingIP.java | 113 ++------- .../nova/os/network/NovaSecurityGroup.java | 118 +++------ .../openstack/nova/os/network/Quantum.java | 93 ++----- .../nova/os/storage/SwiftBlobStore.java | 136 ++--------- .../openstack/nova/os/AbstractMethodTest.java | 3 - .../openstack/nova/os/NovaMethodTest.java | 1 - .../network/LoadBalancerSupportImplTest.java | 45 +--- 25 files changed, 637 insertions(+), 1416 deletions(-) diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/AbstractMethod.java b/src/main/java/org/dasein/cloud/openstack/nova/os/AbstractMethod.java index 05d419c..1d8d5d8 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/AbstractMethod.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/AbstractMethod.java @@ -63,11 +63,7 @@ import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.ContextRequirements; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ProviderContext; +import org.dasein.cloud.*; import org.dasein.cloud.openstack.nova.os.ext.hp.db.HPRDBMS; import org.dasein.cloud.util.APITrace; import org.dasein.cloud.util.Cache; @@ -94,12 +90,12 @@ public abstract class AbstractMethod { ProviderContext ctx = provider.getContext(); if( ctx == null ) { - throw new CloudException("Unable to authenticate due to lack of context"); + throw new InternalException("Unable to authenticate due to lack of context"); } - String endpoint = ctx.getEndpoint(); + String endpoint = ctx.getCloud().getEndpoint(); if( endpoint == null ) { - throw new CloudException("No authentication endpoint"); + throw new InternalException("No authentication endpoint"); } AuthenticationContext auth; @@ -170,8 +166,7 @@ else if( endpoint.startsWith("st:") ) { } catch( UnsupportedEncodingException e ) { std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new InternalException("Unable to read access credentials", e); } if( std.isInfoEnabled() ) { @@ -247,7 +242,7 @@ else if( provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) { post.setEntity(new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8")); } catch( UnsupportedEncodingException e ) { - throw new InternalException(e); + throw new InternalException("Unable to encode", e); } /*try { wire.debug(EntityUtils.toString(post.getEntity())); } catch( IOException ignore ) { }*/ @@ -269,8 +264,7 @@ else if( provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) { } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage(), e); } int code = response.getStatusLine().getStatusCode(); @@ -297,8 +291,7 @@ else if( provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Unable to read the response", e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -328,8 +321,7 @@ else if( provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException(e.getMessage(), e); } if( data != null && !data.trim().equals("") ) { if( std.isInfoEnabled() ) { @@ -357,15 +349,14 @@ else if( provider.getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) { } catch( JSONException e ) { std.error("authenticateKeystone(): Invalid response from server: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException(e.getMessage(), e); } if( tenantId == null ) { tenantId = account; } if( id != null ) { - HashMap> services = new HashMap>(); - HashMap> bestVersion = new HashMap>(); + Map> services = new HashMap>(); + Map> bestVersion = new HashMap>(); String myRegionId = provider.getContext().getRegionId(); if( std.isDebugEnabled() ) { @@ -470,8 +461,7 @@ else if( regionId == null && (type.equals("compute") || type.equals("object-stor } catch( JSONException e ) { std.error("authenticateKeystone(): Failed to read JSON from server: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException(e.getMessage(), e); } } if( std.isDebugEnabled() ) { @@ -488,7 +478,7 @@ else if( regionId == null && (type.equals("compute") || type.equals("object-stor } } } - throw new CloudException("No authentication tokens were provided"); + throw new InternalException("No authentication tokens were provided"); } finally { if (client != null) { @@ -527,8 +517,7 @@ else if( regionId == null && (type.equals("compute") || type.equals("object-stor } catch( UnsupportedEncodingException e ) { std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new InternalException("Unable to read access credentials", e); } String[] endpoints; @@ -581,8 +570,7 @@ else if( regionId == null && (type.equals("compute") || type.equals("object-stor } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage(), e); } int code = response.getStatusLine().getStatusCode(); @@ -607,8 +595,7 @@ else if( regionId == null && (type.equals("compute") || type.equals("object-stor } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } if( code == HttpStatus.SC_INTERNAL_SERVER_ERROR && data.contains("") ) { return null; @@ -696,7 +683,7 @@ else if( h.getName().equalsIgnoreCase("x-cdn-management-url") ) { } if( authToken == null ) { std.warn("authenticateStandard(): No authentication token in response"); - throw new CloudException("No authentication token in cloud response"); + throw new AuthenticationException("No authentication token in cloud response"); } return new AuthenticationContext(myRegion, authToken, tenantId, services, null); } @@ -730,8 +717,7 @@ else if( h.getName().equalsIgnoreCase("x-cdn-management-url") ) { } catch( UnsupportedEncodingException e ) { std.error("authenticateKeystone(): Unable to read access credentials: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new InternalException("Unable to read access credentials", e); } String tenantId = accountNum; String authToken = null, storageToken = null; @@ -788,8 +774,7 @@ else if( h.getName().equalsIgnoreCase("x-cdn-management-url") ) { } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage(), e); } int code = response.getStatusLine().getStatusCode(); @@ -814,8 +799,7 @@ else if( h.getName().equalsIgnoreCase("x-cdn-management-url") ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -865,7 +849,7 @@ else if( h.getName().equalsIgnoreCase("x-storage-token") ) { } if( authToken == null ) { std.warn("authenticate(): No authentication token in response"); - throw new CloudException("No authentication token in cloud response"); + throw new CommunicationException("No authentication token in cloud response"); } return new AuthenticationContext(thisRegion, authToken, tenantId, services, storageToken); } @@ -889,7 +873,7 @@ public void deleteResource(@Nonnull final String service, @Nonnull final String String endpoint = context.getServiceUrl(service); if( endpoint == null ) { - throw new CloudException("No " + service + " endpoint exists"); + throw new InternalException("No " + service + " endpoint exists"); } String resourceUri = resource + "/" + resourceId; if( suffix != null ) { @@ -950,8 +934,7 @@ protected void delete(@Nonnull final String authToken, @Nonnull final String end } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage(), e); } int code = response.getStatusLine().getStatusCode(); @@ -973,8 +956,7 @@ protected void delete(@Nonnull final String authToken, @Nonnull final String end } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -1011,7 +993,7 @@ protected void delete(@Nonnull final String authToken, @Nonnull final String end String endpoint = context.getServiceUrl(service); if( endpoint == null ) { - throw new CloudException("No " + service + " URL has been established in " + context.getMyRegion()); + throw new InternalException("No " + service + " URL has been established in " + context.getMyRegion()); } String resourceUri = resource; if( suffix ) { @@ -1053,7 +1035,7 @@ protected void delete(@Nonnull final String authToken, @Nonnull final String end String endpoint = context.getServiceUrl(service); if( endpoint == null ) { - throw new CloudException("No " + service + " URL has been established in " + context.getMyRegion()); + throw new InternalException("No " + service + " URL has been established in " + context.getMyRegion()); } String resourceUri = resource; if( resourceId != null ) { @@ -1077,7 +1059,7 @@ else if( suffix ) { return new JSONObject(response); } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response); + throw new CommunicationException("Invalid response from server", e); } } catch (NovaException ex) { @@ -1133,8 +1115,7 @@ else if( suffix ) { } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage(), e); } int code = response.getStatusLine().getStatusCode(); @@ -1160,8 +1141,7 @@ else if( suffix ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } try { JSONObject err = (new JSONObject(data)).getJSONObject("badRequest"); @@ -1202,8 +1182,7 @@ else if( suffix ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -1236,8 +1215,7 @@ else if( suffix ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } return data; } @@ -1296,8 +1274,7 @@ else if( suffix ) { } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage(), e); } int code = response.getStatusLine().getStatusCode(); @@ -1322,8 +1299,7 @@ else if( suffix ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -1350,9 +1326,9 @@ else if( suffix ) { catch( IOException e ) { std.error("getStream(): Failed to read response error due to a cloud I/O error: " + e.getMessage()); if( std.isTraceEnabled() ) { - e.printStackTrace(); + std.trace("IO error", e); } - throw new CloudException(e); + throw new CommunicationException("getStream(): Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } if( wire.isDebugEnabled() ) { wire.debug("---> Binary Data <---"); @@ -1430,7 +1406,7 @@ public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws Ce String endpoint = context.getServiceUrl(service); if( endpoint == null ) { - throw new CloudException("No " + service + " URL has been established in " + context.getMyRegion()); + throw new InternalException("No " + service + " URL has been established in " + context.getMyRegion()); } String resourceUri = resource; if( resource == null && resourceId == null ) { @@ -1496,8 +1472,7 @@ else if( resourceId != null ) { } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage(), e); } int code = response.getStatusLine().getStatusCode(); @@ -1522,8 +1497,7 @@ else if( resourceId != null ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -1559,7 +1533,7 @@ public void postResourceHeaders(final String service, final String resource, fin String endpoint = context.getServiceUrl(service); if( endpoint == null ) { - throw new CloudException("No " + service + " has been established in " + context.getMyRegion()); + throw new InternalException("No " + service + " has been established in " + context.getMyRegion()); } if( resourceId == null ) { throw new InternalException("No container was specified"); @@ -1628,8 +1602,7 @@ public void postResourceHeaders(final String service, final String resource, fin } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage(), e); } int code = response.getStatusLine().getStatusCode(); @@ -1651,8 +1624,7 @@ public void postResourceHeaders(final String service, final String resource, fin } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } try { if( data != null ) { @@ -1664,7 +1636,7 @@ public void postResourceHeaders(final String service, final String resource, fin int min = ob.getInt("retryAfter"); if( min < 1 ) { - throw new CloudException(CloudErrorType.CAPACITY, 413, "Over Limit", ob.has("message") ? ob.getString("message") : "Over Limit"); + throw new GeneralCloudException(CloudErrorType.CAPACITY, 413, "Over Limit", ob.has("message") ? ob.getString("message") : "Over Limit"); } try { Thread.sleep(CalendarWrapper.MINUTE * min); } catch( InterruptedException ignore ) { } @@ -1674,7 +1646,7 @@ public void postResourceHeaders(final String service, final String resource, fin } } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Invalid response", e); } } @@ -1695,8 +1667,7 @@ public void postResourceHeaders(final String service, final String resource, fin } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -1727,8 +1698,7 @@ public void postResourceHeaders(final String service, final String resource, fin } catch( IOException e ) { std.error("Failed to read response due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response due to a cloud I/O error: " + e.getMessage(), e); } if( data != null && !data.trim().equals("") ) { return data; @@ -1756,7 +1726,7 @@ public void postResourceHeaders(final String service, final String resource, fin String endpoint = context.getServiceUrl(service); if( endpoint == null ) { - throw new CloudException("No " + service + " endpoint exists"); + throw new InternalException("No " + service + " endpoint exists"); } try { String response = postString(context.getAuthToken(), endpoint, resource + "/" + resourceId + "/" + extra, body.toString()); @@ -1768,7 +1738,7 @@ public void postResourceHeaders(final String service, final String resource, fin return new JSONObject(response); } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response); + throw new CommunicationException("Invalid response", e); } } catch (NovaException ex) { @@ -1793,7 +1763,7 @@ public void postResourceHeaders(final String service, final String resource, fin String endpoint = context.getServiceUrl(service); if( endpoint == null ) { - throw new CloudException("No " + service + " endpoint exists"); + throw new InternalException("No " + service + " endpoint exists"); } try { String response = postString(context.getAuthToken(), endpoint, resourceUri, body.toString()); @@ -1804,7 +1774,7 @@ public void postResourceHeaders(final String service, final String resource, fin return new JSONObject(response); } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response); + throw new CommunicationException("Invalid response", e); } } catch (NovaException ex) { @@ -1850,7 +1820,7 @@ public void postResourceHeaders(final String service, final String resource, fin post.setEntity(new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8")); } catch( UnsupportedEncodingException e ) { - throw new InternalException(e); + throw new InternalException("Unable to encode", e); } try { wire.debug(EntityUtils.toString(post.getEntity())); } catch( IOException ignore ) { } @@ -1872,8 +1842,7 @@ public void postResourceHeaders(final String service, final String resource, fin } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException("Communication error while reading from cloud endpoint", e); + throw new CommunicationException("Communication error while reading from cloud endpoint", e); } int code = response.getStatusLine().getStatusCode(); @@ -1894,8 +1863,7 @@ public void postResourceHeaders(final String service, final String resource, fin } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } try { if( data != null ) { @@ -1905,7 +1873,7 @@ public void postResourceHeaders(final String service, final String resource, fin int min = ob.optInt("retryAfter", 0); if( min < 1 ) { - throw new CloudException(CloudErrorType.CAPACITY, 413, "Over Limit", ob.has("message") ? ob.getString("message") : "Over Limit"); + throw new GeneralCloudException(CloudErrorType.CAPACITY, 413, "Over Limit", ob.has("message") ? ob.getString("message") : "Over Limit"); } try { Thread.sleep(CalendarWrapper.MINUTE * min); } catch( InterruptedException ignore ) { } @@ -1914,7 +1882,7 @@ public void postResourceHeaders(final String service, final String resource, fin } } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Invalid response", e); } } if( code != HttpStatus.SC_OK && code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_CREATED ) { @@ -1934,8 +1902,7 @@ public void postResourceHeaders(final String service, final String resource, fin } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -1966,8 +1933,7 @@ public void postResourceHeaders(final String service, final String resource, fin } catch( IOException e ) { std.error("Failed to read response due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response due to a cloud I/O error: " + e.getMessage(), e); } if( data != null && !data.trim().equals("") ) { return data; @@ -2045,8 +2011,7 @@ else if( code == HttpStatus.SC_ACCEPTED ) { } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage()); } int code = response.getStatusLine().getStatusCode(); @@ -2060,7 +2025,7 @@ else if( code == HttpStatus.SC_ACCEPTED ) { } } if( responseHash != null && md5Hash != null && !responseHash.equals(md5Hash) ) { - throw new CloudException("MD5 hash values do not match, probably data corruption"); + throw new CommunicationException("MD5 hash values do not match, probably data corruption"); } if( code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT ) { std.error("postStream(): Expected ACCEPTED or NO CONTENT for POST request, got " + code); @@ -2079,8 +2044,7 @@ else if( code == HttpStatus.SC_ACCEPTED ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage()); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -2112,8 +2076,7 @@ else if( code == HttpStatus.SC_ACCEPTED ) { } catch( IOException e ) { std.error("Failed to read response due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response due to a cloud I/O error: " + e.getMessage(), e); } if( data != null && !data.trim().equals("") ) { return data; @@ -2141,7 +2104,7 @@ public void putResourceHeaders(@Nonnull final String service, @Nullable final St String endpoint = context.getServiceUrl(service); if( endpoint == null ) { - throw new CloudException("No " + service + " has been established in " + context.getMyRegion()); + throw new InternalException("No " + service + " has been established in " + context.getMyRegion()); } String resourceUri = resource; if( resource == null && resourceId == null ) { @@ -2217,8 +2180,7 @@ else if( resourceId != null ) { } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage(), e); } int code = response.getStatusLine().getStatusCode(); @@ -2241,8 +2203,7 @@ else if( resourceId != null ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -2273,8 +2234,7 @@ else if( resourceId != null ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } if( data != null && !data.trim().equals("") ) { return data; @@ -2305,7 +2265,7 @@ else if( resourceId != null ) { } String endpoint = context.getServiceUrl(service); if( endpoint == null ) { - throw new CloudException("No " + service + " endpoint exists"); + throw new InternalException("No " + service + " endpoint exists"); } try { String response = putString(context.getAuthToken(), endpoint, resourceUri, body.toString()); @@ -2316,7 +2276,7 @@ else if( resourceId != null ) { return new JSONObject(response); } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response); + throw new CommunicationException("Invalid response", e); } } catch (NovaException ex) { @@ -2363,7 +2323,7 @@ else if( resourceId != null ) { put.setEntity(new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8")); } catch( UnsupportedEncodingException e ) { - throw new InternalException(e); + throw new InternalException("Unable to encode", e); } try { wire.debug(EntityUtils.toString(put.getEntity())); } catch( IOException ignore ) { } @@ -2385,8 +2345,7 @@ else if( resourceId != null ) { } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage(), e); } int code = response.getStatusLine().getStatusCode(); @@ -2409,8 +2368,7 @@ else if( resourceId != null ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -2441,8 +2399,7 @@ else if( resourceId != null ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } if( data != null && !data.trim().equals("") ) { return data; @@ -2513,8 +2470,7 @@ else if( resourceId != null ) { } catch( IOException e ) { std.error("I/O error from server communications: " + e.getMessage()); - e.printStackTrace(); - throw new InternalException(e); + throw new CommunicationException("I/O error from server communications: " + e.getMessage(), e); } int code = response.getStatusLine().getStatusCode(); @@ -2528,7 +2484,7 @@ else if( resourceId != null ) { } } if( responseHash != null && md5Hash != null && !responseHash.equals(md5Hash) ) { - throw new CloudException("MD5 hash values do not match, probably data corruption"); + throw new CommunicationException("MD5 hash values do not match, probably data corruption"); } if( code != HttpStatus.SC_CREATED && code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT ) { std.error("putStream(): Expected CREATED, ACCEPTED, or NO CONTENT for PUT request, got " + code); @@ -2547,8 +2503,7 @@ else if( resourceId != null ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); @@ -2579,8 +2534,7 @@ else if( resourceId != null ) { } catch( IOException e ) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Failed to read response error due to a cloud I/O error: " + e.getMessage(), e); } if( data != null && !data.trim().equals("") ) { return data; @@ -2677,9 +2631,9 @@ else if( ver2 == null ) { result = major1 - major2; if (result==0) result = minor1 - minor2; - } catch (Exception e) { + } catch (NumberFormatException e) { // Something really stupid showed up in the version string... - throw new InternalException(e); + throw new InternalException("Unable to parse the version", e); } finally { if( logger.isTraceEnabled() ) { diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/NovaLocationServices.java b/src/main/java/org/dasein/cloud/openstack/nova/os/NovaLocationServices.java index f92ee7f..6f2d010 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/NovaLocationServices.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/NovaLocationServices.java @@ -62,15 +62,10 @@ public class NovaLocationServices extends AbstractDataCenterServices listDataCenters(String providerRegionId) throws In Region region = getRegion(providerRegionId); if( region == null ) { - throw new CloudException("No such region: " + providerRegionId); + throw new InternalException("No such region: " + providerRegionId); } DataCenter dc = new DataCenter(); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/NovaMethod.java b/src/main/java/org/dasein/cloud/openstack/nova/os/NovaMethod.java index ea306c0..f26d771 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/NovaMethod.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/NovaMethod.java @@ -20,9 +20,7 @@ package org.dasein.cloud.openstack.nova.os; import org.apache.http.HttpStatus; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; +import org.dasein.cloud.*; import org.dasein.cloud.openstack.nova.os.ext.hp.cdn.HPCDN; import org.dasein.cloud.util.Cache; import org.dasein.cloud.util.CacheLevel; @@ -46,7 +44,7 @@ public void deleteServers(@Nonnull final String resource, @Nonnull final String String endpoint = context.getComputeUrl(); if( endpoint == null ) { - throw new CloudException("No compute endpoint exists"); + throw new InternalException("No compute endpoint exists"); } try { delete(context.getAuthToken(), endpoint, resource + "/" + resourceId); @@ -68,7 +66,7 @@ public void deleteNetworks(@Nonnull final String resource, @Nonnull final String String endpoint = context.getNetworkUrl(); if( endpoint == null ) { - throw new CloudException("No network endpoint exists"); + throw new InternalException("No network endpoint exists"); } if (resource != null && (!endpoint.endsWith("/") && !resource.startsWith("/"))) { endpoint = endpoint+"/"; @@ -93,7 +91,7 @@ public void deleteNetworks(@Nonnull final String resource, @Nonnull final String String endpoint = context.getComputeUrl(); if( endpoint == null ) { - throw new CloudException("No compute URL has been established in " + context.getMyRegion()); + throw new InternalException("No compute URL has been established in " + context.getMyRegion()); } String resourceUri = resource; if( resourceId != null ) { @@ -110,7 +108,7 @@ public void deleteNetworks(@Nonnull final String resource, @Nonnull final String return new JSONObject(response); } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response); + throw new CommunicationException("Unable to understand getPorts response: " + e.getMessage(), e); } } catch (NovaException ex) { @@ -134,7 +132,7 @@ public AuthenticationContext getAuthenticationContext() throws CloudException, I String endpoint = context.getComputeUrl(); if( endpoint == null ) { - throw new CloudException("No compute URL has been established in " + context.getMyRegion()); + throw new InternalException("No compute URL has been established in " + context.getMyRegion()); } String resourceUri = resource; // make a copy in case we need to retry with the original resource if( resourceId != null ) { @@ -153,7 +151,7 @@ else if( suffix ) { return new JSONObject(response); } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response); + throw new CommunicationException("Unable to understand getServers response: " + e.getMessage(), e); } } catch (NovaException ex) { @@ -177,7 +175,7 @@ else if( suffix ) { String endpoint = context.getNetworkUrl(); if( endpoint == null ) { - throw new CloudException("No network URL has been established in " + context.getMyRegion()); + throw new InternalException("No network URL has been established in " + context.getMyRegion()); } String resourceUri = resource; // make a copy in case we need to retry with the original resource if( resourceId != null ) { @@ -202,7 +200,7 @@ else if( suffix ) { return new JSONObject(response); } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response); + throw new CommunicationException("Unable to understand getNetworks response: " + e.getMessage(), e); } } catch (NovaException ex) { @@ -227,7 +225,7 @@ else if( suffix ) { String computeEndpoint = context.getComputeUrl(); if( computeEndpoint == null ) { - throw new CloudException("No compute endpoint exists"); + throw new InternalException("No compute endpoint exists"); } try { return postString(context.getAuthToken(), computeEndpoint, resourceUri, body.toString()); @@ -254,7 +252,7 @@ else if( suffix ) { String computeEndpoint = context.getComputeUrl(); if( computeEndpoint == null ) { - throw new CloudException("No compute endpoint exists"); + throw new InternalException("No compute endpoint exists"); } try { String response = postString(context.getAuthToken(), computeEndpoint, resourceUri, body.toString()); @@ -266,7 +264,7 @@ else if( suffix ) { return new JSONObject(response); } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response); + throw new CommunicationException("Unable to understand postServers response: " + e.getMessage(), e); } } catch (NovaException ex) { @@ -291,7 +289,7 @@ else if( suffix ) { String endpoint = context.getNetworkUrl(); if( endpoint == null ) { - throw new CloudException("No network endpoint exists"); + throw new InternalException("No network endpoint exists"); } if (resourceUri != null && (!endpoint.endsWith("/") && !resourceUri.startsWith("/"))) { @@ -307,7 +305,7 @@ else if( suffix ) { return new JSONObject(response); } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response); + throw new CommunicationException("Unable to understand postNetworks response: " + e.getMessage(), e); } } catch (NovaException ex) { @@ -332,7 +330,7 @@ else if( suffix ) { String endpoint = context.getNetworkUrl(); if( endpoint == null ) { - throw new CloudException("No network endpoint exists"); + throw new InternalException("No network endpoint exists"); } if (resourceUri != null && (!endpoint.endsWith("/") && !resourceUri.startsWith("/"))) { @@ -348,7 +346,7 @@ else if( suffix ) { return new JSONObject(response); } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", response); + throw new CommunicationException("Unable to understand putNetworks response: " + e.getMessage(), e); } } catch (NovaException ex) { @@ -372,7 +370,7 @@ else if( suffix ) { String endpoint = context.getServiceUrl(HPCDN.SERVICE); if( endpoint == null ) { - throw new CloudException("No CDN URL has been established in " + context.getMyRegion()); + throw new InternalException("No CDN URL has been established in " + context.getMyRegion()); } try { return getString(context.getAuthToken(), endpoint, resourceId == null ? "" : ("/" + resourceId)); @@ -395,7 +393,7 @@ public void putHPCDN(final String container) throws CloudException, InternalExce String endpoint = context.getServiceUrl(HPCDN.SERVICE); if( endpoint == null ) { - throw new CloudException("No CDN URL has been established in " + context.getMyRegion()); + throw new InternalException("No CDN URL has been established in " + context.getMyRegion()); } if( container == null ) { throw new InternalException("No container was specified"); @@ -406,7 +404,7 @@ public void putHPCDN(final String container) throws CloudException, InternalExce headers = headResource(HPCDN.SERVICE, HPCDN.RESOURCE, container); if( headers == null ) { - throw new CloudException("No container enabled"); + throw new InternalException("No container enabled"); } } catch (NovaException ex) { @@ -426,7 +424,7 @@ public void postHPCDN(@Nonnull final String container, @Nonnull final Map current = cache.get(ctx); AuthenticationContext authenticationContext = null; @@ -201,11 +195,9 @@ else if( getCloudProvider().equals(OpenStackProvider.RACKSPACE) ) { } } catch( CloudException e ) { - e.printStackTrace(); return null; } catch( InternalException e ) { - e.printStackTrace(); return null; } return new SwiftStorageServices(this); @@ -349,7 +341,7 @@ public boolean isPostCactus() throws CloudException, InternalException { return (getMajorVersion() > 1 || getMinorVersion() > 0); } - static public long parseTimestamp(String time) throws CloudException { + static public long parseTimestamp(String time) throws InternalException { if( time == null ) { return 0L; } @@ -381,7 +373,7 @@ static public long parseTimestamp(String time) throws CloudException { return fmt.parse(time).getTime(); } catch( ParseException because ) { - throw new CloudException("Could not parse date: " + time); + throw new InternalException("Could not parse date: " + time); } } } diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/SwiftMethod.java b/src/main/java/org/dasein/cloud/openstack/nova/os/SwiftMethod.java index 0642336..c681f33 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/SwiftMethod.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/SwiftMethod.java @@ -47,7 +47,7 @@ public void delete(@Nonnull String bucket) throws CloudException, InternalExcept String endpoint = context.getStorageUrl(); if( endpoint == null ) { - throw new CloudException("No storage endpoint exists for " + context.getMyRegion()); + throw new InternalException("No storage endpoint exists for " + context.getMyRegion()); } try { delete(context.getAuthToken(), endpoint, "/" + bucket); @@ -70,7 +70,7 @@ public void delete(@Nonnull String bucket, @Nonnull String object) throws CloudE String endpoint = context.getStorageUrl(); if( endpoint == null ) { - throw new CloudException("No storage endpoint exists for " + context.getMyRegion()); + throw new InternalException("No storage endpoint exists for " + context.getMyRegion()); } try { delete(context.getAuthToken(), endpoint, "/" + bucket + "/" + object); @@ -92,7 +92,7 @@ public void delete(@Nonnull String bucket, @Nonnull String object) throws CloudE String endpoint = context.getStorageUrl(); if( endpoint == null ) { - throw new CloudException("No storage endpoint exists for " + context.getMyRegion()); + throw new InternalException("No storage endpoint exists for " + context.getMyRegion()); } try { String response = getString(context.getAuthToken(), endpoint, bucket == null ? "/" : "/" + bucket); @@ -134,7 +134,7 @@ public void delete(@Nonnull String bucket, @Nonnull String object) throws CloudE String endpoint = context.getStorageUrl(); if( endpoint == null ) { - throw new CloudException("No storage endpoint exists for " + context.getMyRegion()); + throw new InternalException("No storage endpoint exists for " + context.getMyRegion()); } try { return getStream(context.getAuthToken(), endpoint, "/" + bucket + "/" + object); @@ -157,7 +157,7 @@ public void delete(@Nonnull String bucket, @Nonnull String object) throws CloudE String endpoint = context.getStorageUrl(); if( endpoint == null ) { - throw new CloudException("No storage endpoint exists for " + context.getMyRegion()); + throw new InternalException("No storage endpoint exists for " + context.getMyRegion()); } try { return head(context.getAuthToken(), endpoint, "/" + bucket); @@ -179,7 +179,7 @@ public void delete(@Nonnull String bucket, @Nonnull String object) throws CloudE String endpoint = context.getStorageUrl(); if( endpoint == null ) { - throw new CloudException("No storage endpoint exists for " + context.getMyRegion()); + throw new InternalException("No storage endpoint exists for " + context.getMyRegion()); } try { return head(context.getAuthToken(), endpoint, "/" + bucket + "/" + object); @@ -201,7 +201,7 @@ public void put(@Nonnull String bucket) throws CloudException, InternalException String endpoint = context.getStorageUrl(); if( endpoint == null ) { - throw new CloudException("No storage endpoint exists for " + context.getMyRegion()); + throw new InternalException("No storage endpoint exists for " + context.getMyRegion()); } try { putString(context.getAuthToken(), endpoint, "/" + bucket, null); @@ -223,7 +223,7 @@ public void put(@Nonnull String bucket, @Nonnull String object, @Nullable String String endpoint = context.getStorageUrl(); if( endpoint == null ) { - throw new CloudException("No storage endpoint exists for " + context.getMyRegion()); + throw new InternalException("No storage endpoint exists for " + context.getMyRegion()); } try { putStream(context.getAuthToken(), endpoint, "/" + bucket + "/" + object, md5Hash, payload); @@ -244,7 +244,7 @@ public void put(@Nonnull String bucket, @Nonnull String prefix, @Nonnull Tag ... AuthenticationContext context = provider.getAuthenticationContext(); String endpoint = context.getStorageUrl(); if( endpoint == null ) { - throw new CloudException("No storage endpoint exists for " + context.getMyRegion()); + throw new InternalException("No storage endpoint exists for " + context.getMyRegion()); } try { HashMap customHeaders = new HashMap(); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshot.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshot.java index c6e0cf6..f67d270 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshot.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshot.java @@ -20,12 +20,7 @@ package org.dasein.cloud.openstack.nova.os.compute; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -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.*; import org.dasein.cloud.compute.AbstractSnapshotSupport; import org.dasein.cloud.compute.Snapshot; import org.dasein.cloud.compute.SnapshotCapabilities; @@ -43,9 +38,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Locale; +import java.util.*; /** * Implements support for snapshots from the OpenStack Cinder API. @@ -66,12 +59,12 @@ public CinderSnapshot(NovaOpenStack provider) { } private @Nonnull String getTenantId() throws CloudException, InternalException { - return ((NovaOpenStack)getProvider()).getContext().getAccountNumber(); + return getContext().getAccountNumber(); } private @Nonnull String getResource() { // hp seems to be used the regular grizzly resource - // return (((NovaOpenStack)getProvider()).isHP() ? "/os-snapshots" : "/snapshots"); + // return ((getProvider()).isHP() ? "/os-snapshots" : "/snapshots"); return "/snapshots"; } @@ -85,9 +78,9 @@ public CinderSnapshot(NovaOpenStack provider) { throw new OperationNotSupportedException("Snapshot copying is not supported in " + getProvider().getCloudName()); } - HashMap wrapper = new HashMap(); - HashMap json = new HashMap(); - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + Map wrapper = new HashMap<>(); + Map json = new HashMap<>(); + NovaMethod method = new NovaMethod(getProvider()); json.put("volume_id", volumeId); json.put("display_name", options.getName()); @@ -106,14 +99,12 @@ public CinderSnapshot(NovaOpenStack provider) { } catch( JSONException e ) { logger.error("create(): Unable to understand create response: " + e.getMessage()); - if( logger.isTraceEnabled() ) { - e.printStackTrace(); - } - throw new CloudException(e); + throw new CommunicationException("Unable to understand create response: " + e.getMessage(), e); + } } logger.error("snapshot(): No snapshot was created by the create attempt, and no error was returned"); - throw new CloudException("No snapshot was created"); + throw new GeneralCloudException("No listener was created", CloudErrorType.GENERAL); } finally { @@ -122,11 +113,12 @@ public CinderSnapshot(NovaOpenStack provider) { } private transient volatile CinderSnapshotCapabilities capabilities; + @Nonnull @Override public SnapshotCapabilities getCapabilities() throws CloudException, InternalException { if( capabilities == null ) { - capabilities = new CinderSnapshotCapabilities((NovaOpenStack)getProvider()); + capabilities = new CinderSnapshotCapabilities(getProvider()); } return capabilities; } @@ -135,7 +127,7 @@ public SnapshotCapabilities getCapabilities() throws CloudException, InternalExc public @Nullable Snapshot getSnapshot(@Nonnull String snapshotId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Snapshot.getSnapshot"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getResource(SERVICE, getResource(), snapshotId, true); if( ob == null ) { @@ -148,7 +140,7 @@ public SnapshotCapabilities getCapabilities() throws CloudException, InternalExc } catch( JSONException e ) { logger.error("getSnapshot(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for snapshot"); + throw new CommunicationException("Unable to identify expected values in JSON: " + e.getMessage(), e); } return null; } @@ -161,8 +153,8 @@ public SnapshotCapabilities getCapabilities() throws CloudException, InternalExc public @Nonnull Iterable listSnapshotStatus() throws InternalException, CloudException { APITrace.begin(getProvider(), "Snapshot.listSnapshotStatus"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); - ArrayList snapshots = new ArrayList(); + NovaMethod method = new NovaMethod(getProvider()); + List snapshots = new ArrayList<>(); JSONObject json = method.getResource(SERVICE, getResource(), null, false); @@ -179,7 +171,7 @@ public SnapshotCapabilities getCapabilities() throws CloudException, InternalExc } } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for snapshots in " + json.toString()); + throw new CommunicationException("Unable to parse response: " + e.getMessage(), e); } } return snapshots; @@ -198,7 +190,7 @@ public boolean isPublic(@Nonnull String snapshotId) throws InternalException, Cl public boolean isSubscribed() throws InternalException, CloudException { APITrace.begin(getProvider(), "Snapshot.isSubscribed"); try { - return (((NovaOpenStack)getProvider()).getAuthenticationContext().getServiceUrl(SERVICE) != null); + return (getProvider().getAuthenticationContext().getServiceUrl(SERVICE) != null); } finally { APITrace.end(); @@ -209,8 +201,8 @@ public boolean isSubscribed() throws InternalException, CloudException { public @Nonnull Iterable listSnapshots() throws InternalException, CloudException { APITrace.begin(getProvider(), "Snapshot.listSnapshots"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); - ArrayList snapshots = new ArrayList(); + NovaMethod method = new NovaMethod(getProvider()); + List snapshots = new ArrayList<>(); JSONObject json = method.getResource(SERVICE, getResource(), null, false); @@ -228,8 +220,7 @@ public boolean isSubscribed() throws InternalException, CloudException { } catch( JSONException e ) { logger.error("listSnapshots(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for snapshots in " + json.toString()); + throw new CommunicationException("Unable to parse response " + e.getMessage(), e); } } return snapshots; @@ -262,7 +253,7 @@ public void remove(@Nonnull String snapshotId) throws InternalException, CloudEx try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } } - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); method.deleteResource(SERVICE, getResource(), snapshotId, null); timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 5L); @@ -290,8 +281,8 @@ public void remove(@Nonnull String snapshotId) throws InternalException, CloudEx public @Nonnull Iterable searchSnapshots(@Nonnull SnapshotFilterOptions options) throws InternalException, CloudException { APITrace.begin(getProvider(), "Snapshot.searchSnapshots"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); - ArrayList snapshots = new ArrayList(); + NovaMethod method = new NovaMethod(getProvider()); + List snapshots = new ArrayList<>(); JSONObject json = method.getResource(SERVICE, getResource(), null, false); @@ -309,8 +300,7 @@ public void remove(@Nonnull String snapshotId) throws InternalException, CloudEx } catch( JSONException e ) { logger.error("searchSnapshots(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for snapshots in " + json.toString()); + throw new CommunicationException("Unable to identify expected values in JSON: " + e.getMessage(), e); } } return snapshots; @@ -379,10 +369,10 @@ else if( status.equalsIgnoreCase("creating") ) { logger.warn("DEBUG: Unknown OpenStack snapshot state: " + status); } } - long created = (json.has("createdAt") ? ((NovaOpenStack)getProvider()).parseTimestamp(json.getString("createdAt")) : -1L); + long created = (json.has("createdAt") ? getProvider().parseTimestamp(json.getString("createdAt")) : -1L); if( created < 1L ) { - created = (json.has("created_at") ? ((NovaOpenStack)getProvider()).parseTimestamp(json.getString("created_at")) : -1L); + created = (json.has("created_at") ? getProvider().parseTimestamp(json.getString("created_at")) : -1L); } int size = (json.has("size") ? json.getInt("size") : 0); @@ -400,7 +390,7 @@ else if( status.equalsIgnoreCase("creating") ) { return snapshot; } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to parse response: " + e.getMessage(), e); } } @@ -436,7 +426,7 @@ else if( status.equalsIgnoreCase("creating") ) { return new ResourceStatus(snapshotId, state); } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to parse response: " + e.getMessage(), e); } } @@ -444,7 +434,7 @@ else if( status.equalsIgnoreCase("creating") ) { public void setTags(@Nonnull String snapshotId, @Nonnull Tag... tags) throws CloudException, InternalException { APITrace.begin(getProvider(), "Snapshot.setTags"); try { - ((NovaOpenStack) getProvider()).createTags( SERVICE, "/snapshots", snapshotId, tags); + getProvider().createTags( SERVICE, "/snapshots", snapshotId, tags); } finally { APITrace.end(); @@ -462,7 +452,7 @@ public void setTags(@Nonnull String[] snapshotIds, @Nonnull Tag... tags) throws public void updateTags(@Nonnull String snapshotId, @Nonnull Tag... tags) throws CloudException, InternalException { APITrace.begin(getProvider(), "Snapshot.updateTags"); try { - ((NovaOpenStack) getProvider()).updateTags( SERVICE, "/snapshots", snapshotId, tags); + getProvider().updateTags( SERVICE, "/snapshots", snapshotId, tags); } finally { APITrace.end(); @@ -480,7 +470,7 @@ public void updateTags(@Nonnull String[] snapshotIds, @Nonnull Tag... tags) thro public void removeTags(@Nonnull String snapshotId, @Nonnull Tag... tags) throws CloudException, InternalException { APITrace.begin(getProvider(), "Snapshot.removeTags"); try { - ((NovaOpenStack) getProvider()).removeTags( SERVICE, "/snapshots", snapshotId, tags); + getProvider().removeTags( SERVICE, "/snapshots", snapshotId, tags); } finally { APITrace.end(); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java index f27724c..353f822 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java @@ -20,13 +20,7 @@ package org.dasein.cloud.openstack.nova.os.compute; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.OperationNotSupportedException; -import org.dasein.cloud.Requirement; -import org.dasein.cloud.ResourceStatus; -import org.dasein.cloud.Tag; +import org.dasein.cloud.*; import org.dasein.cloud.compute.AbstractVolumeSupport; import org.dasein.cloud.compute.Platform; import org.dasein.cloud.compute.Volume; @@ -50,11 +44,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; +import java.util.*; /** * Support for the Cinder volumes API in Dasein Cloud. @@ -63,7 +53,7 @@ * @version 2012.09.1 copied over from volume extension for HP * @since 2012.09.1 */ -public class CinderVolume extends AbstractVolumeSupport { +public class CinderVolume extends AbstractVolumeSupport { static private final Logger logger = NovaOpenStack.getLogger(CinderVolume.class, "std"); static public final String SERVICE = "volume"; @@ -79,7 +69,7 @@ public CinderVolume(@Nonnull NovaOpenStack provider) { private @Nonnull String getResource() { // 20130930 dmayne: seems like hp may have upgraded and uses the same resource return "/volumes"; - // return (((NovaOpenStack)getProvider()).isHP() ? "/os-volumes" : "/volumes"); + // return ((getProvider()).isHP() ? "/os-volumes" : "/volumes"); } private @Nonnull String getTypesResource() { @@ -90,16 +80,16 @@ public CinderVolume(@Nonnull NovaOpenStack provider) { public void attach(@Nonnull String volumeId, @Nonnull String toServer, @Nonnull String device) throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.attach"); try { - HashMap attachment = new HashMap(); - HashMap wrapper = new HashMap(); - NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider())); + Map attachment = new HashMap<>(); + Map wrapper = new HashMap<>(); + NovaMethod method = new NovaMethod(getProvider()); attachment.put("volumeId", volumeId); attachment.put("device", device); wrapper.put("volumeAttachment", attachment); if( method.postString(NovaServer.SERVICE, "/servers", toServer, getAttachmentsResource(), new JSONObject(wrapper)) == null ) { - throw new CloudException("No response from the cloud"); + throw new CommunicationException("No response from the cloud"); } } finally { @@ -114,9 +104,9 @@ public void attach(@Nonnull String volumeId, @Nonnull String toServer, @Nonnull } APITrace.begin(getProvider(), "Volume.createVolume"); try { - HashMap wrapper = new HashMap(); - HashMap json = new HashMap(); - NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider())); + Map wrapper = new HashMap<>(); + Map json = new HashMap<>(); + NovaMethod method = new NovaMethod(getProvider()); json.put("display_name", options.getName()); json.put("display_description", options.getDescription()); @@ -144,8 +134,7 @@ else if( getMaximumVolumeSize() != null && size.intValue() > getMaximumVolumeSiz } if( options.getVolumeProductId() != null ) { // TODO: cinder was broken and expected the name prior Grizzly - json.put("volume_type", options.getVolumeProductId()); - + json.put("volume_type", options.getVolumeProductId()); } wrapper.put("volume", json); JSONObject result = method.postString(SERVICE, getResource(), null, new JSONObject(wrapper), true); @@ -160,14 +149,11 @@ else if( getMaximumVolumeSize() != null && size.intValue() > getMaximumVolumeSiz } catch( JSONException e ) { logger.error("create(): Unable to understand create response: " + e.getMessage()); - if( logger.isTraceEnabled() ) { - e.printStackTrace(); - } - throw new CloudException(e); + throw new CommunicationException("Unable to understand createVolume response: " + e.getMessage(), e); } } logger.error("create(): No volume was created by the create attempt, and no error was returned"); - throw new CloudException("No volume was created"); + throw new ResourceNotFoundException("No volume was created"); } finally { @@ -182,12 +168,12 @@ public void detach(@Nonnull String volumeId, boolean force) throws InternalExcep Volume volume = getVolume(volumeId); if( volume == null ) { - throw new CloudException("No such volume: " + volumeId); + throw new ResourceNotFoundException("No such volume: " + volumeId); } if( volume.getProviderVirtualMachineId() == null ) { - throw new CloudException("Volume " + volumeId + " is not attached"); + throw new ResourceNotFoundException("Volume " + volumeId + " is not attached"); } - NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider())); + NovaMethod method = new NovaMethod(getProvider()); method.deleteResource(NovaServer.SERVICE, "/servers", volume.getProviderVirtualMachineId(), getAttachmentsResource() + "/" + volumeId); } @@ -197,42 +183,20 @@ public void detach(@Nonnull String volumeId, boolean force) throws InternalExcep } private transient volatile CinderVolumeCapabilities capabilities; + @Override public VolumeCapabilities getCapabilities() throws CloudException, InternalException { if( capabilities == null ) { - capabilities = new CinderVolumeCapabilities((NovaOpenStack)getProvider()); + capabilities = new CinderVolumeCapabilities(getProvider()); } return capabilities; } - @Override - public int getMaximumVolumeCount() throws InternalException, CloudException { - return -2; - } - - @Override - public Storage getMaximumVolumeSize() throws InternalException, CloudException { - return new Storage(1024, Storage.GIGABYTE); - } - - @Override - public @Nonnull Storage getMinimumVolumeSize() throws InternalException, CloudException { - if( ((NovaOpenStack)getProvider()).isRackspace() ) { - return new Storage(100, Storage.GIGABYTE); - } - return new Storage(1, Storage.GIGABYTE); - } - - @Override - public @Nonnull String getProviderTermForVolume(@Nonnull Locale locale) { - return "volume"; - } - @Override public @Nullable Volume getVolume(@Nonnull String volumeId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.getVolume"); try { - NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider())); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getResource(SERVICE, getResource(), volumeId, true); if( ob == null ) { @@ -245,7 +209,7 @@ public Storage getMaximumVolumeSize() throws InternalException, CloudE } catch( JSONException e ) { logger.error("getVolume(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for volume"); + throw new CommunicationException("Unable to understand getVolume response: " + e.getMessage(), e); } return null; } @@ -254,51 +218,6 @@ public Storage getMaximumVolumeSize() throws InternalException, CloudE } } - @Override - public @Nonnull Requirement getVolumeProductRequirement() throws InternalException, CloudException { - return (((NovaOpenStack)getProvider()).isHP() ? Requirement.NONE : Requirement.OPTIONAL); - } - - @Override - public boolean isVolumeSizeDeterminedByProduct() throws InternalException, CloudException { - return false; - } - - @Override - public @Nonnull Iterable listPossibleDeviceIds(@Nonnull Platform platform) throws InternalException, CloudException { - ArrayList list = new ArrayList(); - - if( platform.isWindows() ) { - if (((NovaOpenStack)getProvider()).isHP()) { - list.add("/dev/vdf"); - list.add("/dev/vdg"); - list.add("/dev/vdh"); - list.add("/dev/vdi"); - list.add("/dev/vdj"); - } - else { - list.add("/dev/xvdf"); - list.add("/dev/xvdg"); - list.add("/dev/xvdh"); - list.add("/dev/xvdi"); - list.add("/dev/xvdj"); - } - } - else { - list.add("/dev/vdf"); - list.add("/dev/vdg"); - list.add("/dev/vdh"); - list.add("/dev/vdi"); - list.add("/dev/vdj"); - } - return list; - } - - @Override - public @Nonnull Iterable listSupportedFormats() throws InternalException, CloudException { - return Collections.singletonList(VolumeFormat.BLOCK); - } - @Override public @Nonnull Iterable listVolumeProducts() throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.listVolumeProducts"); @@ -309,8 +228,8 @@ public boolean isVolumeSizeDeterminedByProduct() throws InternalException, Cloud if( current != null ) { return current; } - NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider())); - ArrayList products = new ArrayList(); + NovaMethod method = new NovaMethod(getProvider()); + List products = new ArrayList<>(); JSONObject json = method.getResource(SERVICE, getTypesResource(), null, false); @@ -351,8 +270,7 @@ public boolean isVolumeSizeDeterminedByProduct() throws InternalException, Cloud } catch( JSONException e ) { logger.error("listVolumes(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for volumes in " + json.toString()); + throw new CommunicationException("Unable to understand listVolumes response: " + e.getMessage(), e); } } cache.put(getContext(), Collections.unmodifiableList(products)); @@ -367,8 +285,8 @@ public boolean isVolumeSizeDeterminedByProduct() throws InternalException, Cloud public @Nonnull Iterable listVolumeStatus() throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.listVolumeStatus"); try { - NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider())); - ArrayList volumes = new ArrayList(); + NovaMethod method = new NovaMethod(getProvider()); + List volumes = new ArrayList<>(); JSONObject json = method.getResource(SERVICE, getResource(), null, false); @@ -386,8 +304,7 @@ public boolean isVolumeSizeDeterminedByProduct() throws InternalException, Cloud } catch( JSONException e ) { logger.error("listVolumes(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for volumes in " + json.toString()); + throw new CommunicationException("Unable to understand listVolumeStatus response: " + e.getMessage(), e); } } return volumes; @@ -402,8 +319,8 @@ public boolean isVolumeSizeDeterminedByProduct() throws InternalException, Cloud APITrace.begin(getProvider(), "Volume.listVolumes"); try { Iterable products = listVolumeProducts(); - NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider())); - ArrayList volumes = new ArrayList(); + NovaMethod method = new NovaMethod(getProvider()); + List volumes = new ArrayList<>(); JSONObject json = method.getResource(SERVICE, getResource(), null, false); @@ -422,8 +339,7 @@ public boolean isVolumeSizeDeterminedByProduct() throws InternalException, Cloud } catch( JSONException e ) { logger.error("listVolumes(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for volumes in " + json.toString()); + throw new CommunicationException("Unable to understand listVolumes response: " + e.getMessage(), e); } } return volumes; @@ -437,7 +353,7 @@ public boolean isVolumeSizeDeterminedByProduct() throws InternalException, Cloud public boolean isSubscribed() throws CloudException, InternalException { APITrace.begin(getProvider(), "Volume.isSubscribed"); try { - return (((NovaOpenStack)getProvider()).getAuthenticationContext().getServiceUrl(SERVICE) != null); + return getProvider().getAuthenticationContext().getServiceUrl(SERVICE) != null; } finally { APITrace.end(); @@ -467,7 +383,7 @@ public void remove(@Nonnull String volumeId) throws InternalException, CloudExce // ignore } } - NovaMethod method = new NovaMethod(((NovaOpenStack)getProvider())); + NovaMethod method = new NovaMethod(getProvider()); method.deleteResource(SERVICE, getResource(), volumeId, null); @@ -534,7 +450,7 @@ else if( status.equals("attaching") ) { return new ResourceStatus(volumeId, state); } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to understand toStatus response: " + e.getMessage(), e); } } @@ -579,10 +495,10 @@ else if( status.equals("attaching") ) { } } - long created = (json.has("createdAt") ? ((NovaOpenStack)getProvider()).parseTimestamp(json.getString("createdAt")) : -1L); + long created = (json.has("createdAt") ? (getProvider()).parseTimestamp(json.getString("createdAt")) : -1L); if( created < 1L ) { - created = (json.has("created_at") ? ((NovaOpenStack)getProvider()).parseTimestamp(json.getString("created_at")) : -1L); + created = (json.has("created_at") ? (getProvider()).parseTimestamp(json.getString("created_at")) : -1L); } int size = 0; @@ -662,7 +578,7 @@ else if( status.equals("attaching") ) { volume.setProviderSnapshotId(snapshotId); volume.setProviderVirtualMachineId(vmId); volume.setProviderVolumeId(volumeId); - volume.setSize(new Storage(size, Storage.GIGABYTE)); + volume.setSize(new Storage<>(size, Storage.GIGABYTE)); if( productId != null ) { VolumeProduct match = null; @@ -694,7 +610,7 @@ else if( status.equals("attaching") ) { return volume; } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to understand toVolume response: " + e.getMessage(), e); } } @@ -702,7 +618,7 @@ else if( status.equals("attaching") ) { public void setTags(@Nonnull String volumeId, @Nonnull Tag... tags) throws CloudException, InternalException { APITrace.begin(getProvider(), "Volume.setTags"); try { - ((NovaOpenStack) getProvider()).createTags( SERVICE, "/volumes", volumeId, tags); + getProvider().createTags( SERVICE, "/volumes", volumeId, tags); } finally { APITrace.end(); @@ -720,7 +636,7 @@ public void setTags(@Nonnull String[] volumeIds, @Nonnull Tag... tags) throws Cl public void updateTags(@Nonnull String volumeId, @Nonnull Tag... tags) throws CloudException, InternalException { APITrace.begin(getProvider(), "Volume.updateTags"); try { - ((NovaOpenStack) getProvider()).updateTags( SERVICE, "/volumes", volumeId, tags); + getProvider().updateTags( SERVICE, "/volumes", volumeId, tags); } finally { APITrace.end(); @@ -738,7 +654,7 @@ public void updateTags(@Nonnull String[] volumeIds, @Nonnull Tag... tags) throws public void removeTags(@Nonnull String volumeId, @Nonnull Tag... tags) throws CloudException, InternalException { APITrace.begin(getProvider(), "Volume.removeTags"); try { - ((NovaOpenStack) getProvider()).removeTags( SERVICE, "/volumes", volumeId, tags); + getProvider().removeTags( SERVICE, "/volumes", volumeId, tags); } finally { APITrace.end(); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java index cb1f448..787f2d5 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java @@ -19,23 +19,14 @@ package org.dasein.cloud.openstack.nova.os.compute; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; +import java.util.*; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.http.HttpStatus; import org.apache.log4j.Logger; -import org.dasein.cloud.AsynchronousTask; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.Requirement; -import org.dasein.cloud.ResourceStatus; -import org.dasein.cloud.Tag; +import org.dasein.cloud.*; import org.dasein.cloud.compute.AbstractImageSupport; import org.dasein.cloud.compute.Architecture; import org.dasein.cloud.compute.ComputeServices; @@ -68,13 +59,13 @@ public class NovaImage extends AbstractImageSupport { } private @Nonnull String getTenantId() throws CloudException, InternalException { - return ((NovaOpenStack)getProvider()).getContext().getAccountNumber(); + return getContext().getAccountNumber(); } public @Nullable String getImageRef(@Nonnull String machineImageId) throws CloudException, InternalException { APITrace.begin(getProvider(), "Image.getImageRef"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers("/images", machineImageId, true); if( ob == null ) { @@ -102,7 +93,7 @@ else if( def == null ) { } catch( JSONException e ) { logger.error("getImageRef(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for images: " + e.getMessage()); + throw new CommunicationException("Missing JSON element for images: " + e.getMessage(), e); } } finally { @@ -114,8 +105,8 @@ else if( def == null ) { protected MachineImage capture(@Nonnull ImageCreateOptions options, @Nullable AsynchronousTask task) throws CloudException, InternalException { APITrace.begin(getProvider(), "Image.capture"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); - HashMap action = new HashMap(); + NovaMethod method = new NovaMethod(getProvider()); + Map action = new HashMap(); action.put("name", options.getName()); if( task != null ) { @@ -140,7 +131,7 @@ protected MachineImage capture(@Nonnull ImageCreateOptions options, @Nullable As } } if( vm == null ) { - throw new CloudException("No such virtual machine: " + vmId); + throw new ResourceNotFoundException("No such virtual machine: " + vmId); } platform = vm.getPlatform(); if( !VmState.PENDING.equals(vm.getCurrentState()) ) { @@ -160,9 +151,9 @@ protected MachineImage capture(@Nonnull ImageCreateOptions options, @Nullable As } JSONObject result; - if( ((NovaOpenStack)getProvider()).isPostCactus() ) { - HashMap json = new HashMap(); - HashMap metaData = new HashMap(); + if( getProvider().isPostCactus() ) { + Map json = new HashMap(); + Map metaData = new HashMap(); metaData.put("org.dasein.description", options.getDescription()); if( platform != null ) { @@ -174,7 +165,7 @@ protected MachineImage capture(@Nonnull ImageCreateOptions options, @Nullable As result = method.postServers("/servers", vmId, new JSONObject(json), true); } else { - HashMap json = new HashMap(); + Map json = new HashMap(); action.put("serverId", String.valueOf(vmId)); json.put("image", action); @@ -193,7 +184,7 @@ protected MachineImage capture(@Nonnull ImageCreateOptions options, @Nullable As } } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Invalid response", e); } } else if( result != null && result.has("location") ) { @@ -220,11 +211,11 @@ else if( result != null && result.has("location") ) { } } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Invalid response", e); } } logger.error("No image was created by the imaging attempt, and no error was returned"); - throw new CloudException("No image was created"); + throw new GeneralCloudException("No image was created", CloudErrorType.GENERAL); } finally { APITrace.end(); @@ -235,7 +226,7 @@ else if( result != null && result.has("location") ) { @Override public ImageCapabilities getCapabilities() throws CloudException, InternalException { if( capabilities == null ) { - capabilities = new NovaImageCapabilities((NovaOpenStack)getProvider()); + capabilities = new NovaImageCapabilities(getProvider()); } return capabilities; } @@ -244,7 +235,7 @@ public ImageCapabilities getCapabilities() throws CloudException, InternalExcept public MachineImage getImage(@Nonnull String providerImageId) throws CloudException, InternalException { APITrace.begin(getProvider(), "Image.getImage"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers("/images", providerImageId, true); if( ob == null ) { @@ -262,7 +253,7 @@ public MachineImage getImage(@Nonnull String providerImageId) throws CloudExcept } catch( JSONException e ) { logger.error("getMachineImage(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for images: " + e.getMessage()); + throw new CommunicationException("Missing JSON element for images: " + e.getMessage(), e); } return null; } @@ -271,21 +262,6 @@ public MachineImage getImage(@Nonnull String providerImageId) throws CloudExcept } } - @Override - public @Nonnull String getProviderTermForImage(@Nonnull Locale locale, @Nonnull ImageClass cls) { - switch( cls ) { - case MACHINE: return "machine image"; - case KERNEL: return "kernel image"; - case RAMDISK: return "ramdisk image"; - } - return "image"; - } - - @Override - public boolean hasPublicLibrary() { - return true; - } - @Override public boolean isImageSharedWithPublic(@Nonnull String machineImageId) throws CloudException, InternalException { APITrace.begin(getProvider(), "Image.isImageSharedWithPublic"); @@ -320,7 +296,7 @@ public boolean isSubscribed() throws CloudException, InternalException { } NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/images", null, true); - ArrayList images = new ArrayList(); + List images = new ArrayList(); try { if( ob != null && ob.has("images") ) { @@ -338,7 +314,7 @@ public boolean isSubscribed() throws CloudException, InternalException { } } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for images: " + e.getMessage()); + throw new CommunicationException("Missing JSON element for images: " + e.getMessage(), e); } return images; } @@ -363,7 +339,7 @@ public boolean isSubscribed() throws CloudException, InternalException { } NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/images", null, true); - ArrayList images = new ArrayList(); + List images = new ArrayList(); try { if( ob != null && ob.has("images") ) { @@ -380,7 +356,7 @@ public boolean isSubscribed() throws CloudException, InternalException { } } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for images: " + e.getMessage()); + throw new CommunicationException("Missing JSON element for images: " + e.getMessage(), e); } return images; } @@ -420,7 +396,7 @@ public void remove(@Nonnull String providerImageId, boolean checkState) throws C try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/images", null, true); - ArrayList images = new ArrayList(); + List images = new ArrayList(); String me = getTenantId(); try { @@ -438,7 +414,7 @@ public void remove(@Nonnull String providerImageId, boolean checkState) throws C } } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for images: " + e.getMessage()); + throw new CommunicationException("Missing JSON element for images: " + e.getMessage(), e); } return images; } @@ -447,11 +423,6 @@ public void remove(@Nonnull String providerImageId, boolean checkState) throws C } } - @Override - public boolean supportsCustomImages() { - return true; - } - public @Nullable MachineImage toImage(@Nullable JSONObject json) throws CloudException, InternalException { Logger logger = NovaOpenStack.getLogger(NovaImage.class, "std"); @@ -529,7 +500,7 @@ else if( md.has("image_type") && !md.isNull("image_type") && md.getString("image owner = getTenantId(); } } - long created = (json.has("created") ? ((NovaOpenStack)getProvider()).parseTimestamp(json.getString("created")) : -1L); + long created = (json.has("created") ? getProvider().parseTimestamp(json.getString("created")) : -1L); MachineImageState currentState = MachineImageState.PENDING; @@ -599,7 +570,7 @@ else if( platform.equals(Platform.UNIX) ) { return image; } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Invalid response", e); } } finally { @@ -614,7 +585,7 @@ else if( platform.equals(Platform.UNIX) ) { if( json == null ) { return null; } - String owner = ((NovaOpenStack)getProvider()).getCloudProvider().getDefaultImageOwner(getTenantId()); + String owner = getProvider().getCloudProvider().getDefaultImageOwner(getTenantId()); MachineImageState state = MachineImageState.PENDING; String id = null; @@ -657,7 +628,7 @@ else if( s.equals("failed") ) { } } catch( JSONException e ) { - throw new InternalException(e); + throw new CommunicationException("Unable to parse", e); } if( !owner.equals(getTenantId()) ) { return null; diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java index 86fe610..5345f48 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java @@ -81,7 +81,7 @@ public class NovaServer extends AbstractVMSupport { } @Nonnull protected String getTenantId() throws CloudException, InternalException { - return getProvider().getContext().getAccountNumber(); + return getContext().getAccountNumber(); } private transient volatile NovaServerCapabilities capabilities; @@ -159,9 +159,9 @@ protected Platform getPlatform(String vmName, String vmDescription, String image VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new CloudException("No such virtual machine: " + vmId); + throw new ResourceNotFoundException("No such virtual machine: " + vmId); } - Map json = new HashMap(); + Map json = new HashMap<>(); json.put("os-getConsoleOutput", new HashMap()); @@ -247,7 +247,7 @@ protected OpenStackProvider getCloudProvider() { } catch( JSONException e ) { logger.error("getVirtualMachine(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers"); + throw new CommunicationException("Missing JSON element for servers", e); } return null; } @@ -263,7 +263,7 @@ protected OpenStackProvider getCloudProvider() { return ob.getJSONObject("server").getString("status"); } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to parse the server status response", e); } finally { APITrace.end(); @@ -274,8 +274,8 @@ protected OpenStackProvider getCloudProvider() { public @Nonnull VirtualMachine alterVirtualMachineProduct(@Nonnull String virtualMachineId, @Nonnull String productId) throws InternalException, CloudException { APITrace.begin(getProvider(), "VM.resize"); try { - Map json = new HashMap(); - Map action = new HashMap(); + Map json = new HashMap<>(); + Map action = new HashMap<>(); action.put("flavorRef", productId); json.put("resize", action); @@ -296,7 +296,8 @@ protected OpenStackProvider getCloudProvider() { } VirtualMachine vm = getVirtualMachine(virtualMachineId); if( status.equals("ACTIVE") && !( vm.getProductId().equals(productId) ) ) { - throw new CloudException("Failed to resize VM from " + getProduct(vm.getProductId()).getName() + " to " + getProduct(productId).getName()); + throw new GeneralCloudException("Failed to resize VM from " + getProduct(vm.getProductId()).getName() + " to " + getProduct(productId).getName(), + CloudErrorType.GENERAL); } return vm; } @@ -363,7 +364,7 @@ protected void prepareVlanForLaunch(VMLaunchOptions options, Map } catch (CloudException e) { if (e.getHttpCode() != 403) { - throw new CloudException(e.getMessage()); + throw e; } logger.warn("Unable to create port - trying to launch into general network"); @@ -385,7 +386,7 @@ protected void prepareVlanForLaunch(VMLaunchOptions options, Map try { MachineImage targetImage = getImage(options.getMachineImageId()); if( targetImage == null ) { - throw new CloudException("No such machine image: " + options.getMachineImageId()); + throw new ResourceNotFoundException("No such machine image: " + options.getMachineImageId()); } //Additional LPAR Call boolean isBareMetal = isBareMetal(options.getMachineImageId()); @@ -480,21 +481,18 @@ protected void prepareVlanForLaunch(VMLaunchOptions options, Map vm = getVirtualMachine(vmId); } if( vm == null || vm.getCurrentState() == null ) { - throw new CloudException("VM failed to launch with a meaningful status"); + throw new GeneralCloudException("VM failed to launch with a meaningful status", CloudErrorType.GENERAL); } return vm; } } catch( JSONException e ) { logger.error("launch(): Unable to understand launch response: " + e.getMessage()); - if( logger.isTraceEnabled() ) { - e.printStackTrace(); - } - throw new CloudException(e); + throw new CommunicationException("Invalid response", e); } } logger.error("launch(): No server was created by the launch attempt, and no error was returned"); - throw new CloudException("No virtual machine was launched"); + throw new GeneralCloudException("No virtual machine was launched", CloudErrorType.GENERAL); } finally { @@ -554,7 +552,7 @@ public static int roundUpToGB(Long size) { firewalls = Collections.emptyList(); } JSONArray groups = server.getJSONArray("security_groups"); - List results = new ArrayList(); + List results = new ArrayList<>(); for( int i=0; i results = new ArrayList(); + List results = new ArrayList<>(); JSONObject ob = getMethod().getServers("/os-security-groups/servers", vmId + "/os-security-groups", true); @@ -599,8 +597,8 @@ else if( name.equals(fw.getName()) ) { } } catch( JSONException e ) { - throw new CloudException(e); - } + logger.error("Unable to understand listFirewalls response: " + e.getMessage()); + throw new CommunicationException("Unable to understand listFirewalls response: " + e.getMessage(), e); } } @Override @@ -618,11 +616,11 @@ else if( name.equals(fw.getName()) ) { return listFirewalls(vmId, server); } - throw new CloudException("No such server: " + vmId); + throw new ResourceNotFoundException("No such server found for " + vmId); } catch( JSONException e ) { logger.error("listFirewalls(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers"); + throw new CommunicationException("Unable to understand listFirewalls response: " + e.getMessage(), e); } } finally { @@ -659,7 +657,7 @@ protected void cacheFlavors(Iterable refs) throws InternalException { } JSONObject ob = getMethod().getServers("/flavors", null, true); - List flavors = new ArrayList(); + List flavors = new ArrayList<>(); try { if( ob != null && ob.has("flavors") ) { @@ -703,7 +701,7 @@ protected void cacheFlavors(Iterable refs) throws InternalException { } catch( JSONException e ) { logger.error("listProducts(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors: " + e.getMessage()); + throw new CommunicationException("Unable to understand listProducts response: " + e.getMessage(), e); } cacheFlavors(flavors); return flavors; @@ -742,7 +740,7 @@ else if( def == null && link[1] != null ) { APITrace.begin(getProvider(), "VM.listProducts"); try { - List products = new ArrayList(); + List products = new ArrayList<>(); for( FlavorRef flavor : listFlavors() ) { if (options != null) { @@ -766,7 +764,7 @@ else if( def == null && link[1] != null ) { APITrace.begin(getProvider(), "VM.listVirtualMachineStatus"); try { JSONObject ob = getMethod().getServers("/servers", null, true); - List servers = new ArrayList(); + List servers = new ArrayList<>(); try { if( ob != null && ob.has("servers") ) { @@ -779,13 +777,12 @@ else if( def == null && link[1] != null ) { if( vm != null ) { servers.add(vm); } - } } } catch( JSONException e ) { - logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers in " + ob.toString()); + logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); + throw new CommunicationException("Unable to understand listVirtualMachines response: " + e.getMessage(), e); } return servers; } @@ -799,7 +796,7 @@ else if( def == null && link[1] != null ) { APITrace.begin(getProvider(), "VM.listVirtualMachines"); try { JSONObject ob = getMethod().getServers("/servers", null, true); - List servers = new ArrayList(); + List servers = new ArrayList<>(); Iterable ipv4 = Collections.emptyList(), ipv6 = Collections.emptyList(); Iterable nets = Collections.emptyList(); @@ -831,8 +828,8 @@ else if( def == null && link[1] != null ) { } } catch( JSONException e ) { - logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for servers in " + ob.toString()); + logger.error("listVirtualMachines(): Unable to identify expected values in JSON: " + e.getMessage()); + throw new CommunicationException("Unable to understand listVirtualMachines response: " + e.getMessage(), e); } return servers; } @@ -848,12 +845,12 @@ public void pause(@Nonnull String vmId) throws InternalException, CloudException VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new CloudException("No such virtual machine: " + vmId); + throw new ResourceNotFoundException("No such virtual machine found for " + vmId); } if( !getCapabilities().supportsPause() ) { throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName()); } - Map json = new HashMap(); + Map json = new HashMap<>(); json.put("pause", null); @@ -871,12 +868,12 @@ public void resume(@Nonnull String vmId) throws InternalException, CloudExceptio VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new CloudException("No such virtual machine: " + vmId); + throw new ResourceNotFoundException("No such virtual machine found for " + vmId); } if( !getCapabilities().supportsResume() ) { throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName()); } - Map json = new HashMap(); + Map json = new HashMap<>(); json.put("resume", null); @@ -894,12 +891,12 @@ public void start(@Nonnull String vmId) throws InternalException, CloudException VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new CloudException("No such virtual machine: " + vmId); + throw new ResourceNotFoundException("No such virtual machine found for " + vmId); } if( !getCapabilities().supportsStart() ) { throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName()); } - Map json = new HashMap(); + Map json = new HashMap<>(); json.put("os-start", null); @@ -917,12 +914,12 @@ public void stop(@Nonnull String vmId, boolean force) throws InternalException, VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new CloudException("No such virtual machine: " + vmId); + throw new ResourceNotFoundException("No such virtual machine found for " + vmId); } if( !getCapabilities().supportsStop() ) { throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName()); } - Map json = new HashMap(); + Map json = new HashMap<>(); json.put("os-stop", null); @@ -940,12 +937,12 @@ public void suspend(@Nonnull String vmId) throws InternalException, CloudExcepti VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new CloudException("No such virtual machine: " + vmId); + throw new ResourceNotFoundException("No such virtual machine found for " + vmId); } if( !getCapabilities().supportsSuspend() ) { throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName()); } - Map json = new HashMap(); + Map json = new HashMap<>(); json.put("suspend", null); @@ -963,12 +960,12 @@ public void unpause(@Nonnull String vmId) throws InternalException, CloudExcepti VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new CloudException("No such virtual machine: " + vmId); + throw new ResourceNotFoundException("No such virtual machine found for " + vmId); } if( !getCapabilities().supportsUnPause() ) { throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName()); } - Map json = new HashMap(); + Map json = new HashMap<>(); json.put("unpause", null); @@ -983,8 +980,8 @@ public void unpause(@Nonnull String vmId) throws InternalException, CloudExcepti public void reboot(@Nonnull String vmId) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.reboot"); try { - Map json = new HashMap(); - Map action = new HashMap(); + Map json = new HashMap<>(); + Map action = new HashMap<>(); action.put("type", "HARD"); json.put("reboot", action); @@ -1056,10 +1053,10 @@ public void terminate(@Nonnull String vmId, @Nullable String explanation) throws product.setDescription(json.getString("description")); } if( json.has("ram") ) { - product.setRamSize(new Storage(json.getInt("ram"), Storage.MEGABYTE)); + product.setRamSize(new Storage<>(json.getInt("ram"), Storage.MEGABYTE)); } if( json.has("disk") ) { - product.setRootVolumeSize(new Storage(json.getInt("disk"), Storage.GIGABYTE)); + product.setRootVolumeSize(new Storage<>(json.getInt("disk"), Storage.GIGABYTE)); } product.setCpuCount(1); @@ -1177,12 +1174,12 @@ else if( s.equals("reboot") || s.equals("hard_reboot") ) { } JSONObject md = (server.has("metadata") && !server.isNull("metadata")) ? server.getJSONObject("metadata") : null; - Map map = new HashMap(); + Map map = new HashMap<>(); boolean imaging = false; if( md != null ) { if( md.has("org.dasein.description") && vm.getDescription() == null ) { - description = md.getString("org.dasein.description"); + description = md.getString("org.dasein.description"); } else if( md.has("Server Label") ) { description = md.getString("Server Label"); @@ -1311,8 +1308,8 @@ else if( s.equals("reboot") || s.equals("hard_reboot") ) { String[] names = JSONObject.getNames(addrs); if( names != null && names.length > 0 ) { - List pub = new ArrayList(); - List priv = new ArrayList(); + List pub = new ArrayList<>(); + List priv = new ArrayList<>(); for( String name : names ) { JSONArray arr = addrs.getJSONArray(name); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/hp/cdn/HPCDN.java b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/hp/cdn/HPCDN.java index 65b0ddd..7c748c3 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/hp/cdn/HPCDN.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/hp/cdn/HPCDN.java @@ -20,11 +20,7 @@ package org.dasein.cloud.openstack.nova.os.ext.hp.cdn; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.*; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.openstack.nova.os.NovaMethod; import org.dasein.cloud.openstack.nova.os.NovaOpenStack; @@ -181,8 +177,7 @@ public boolean isSubscribed() throws InternalException, CloudException { } catch( IOException e ) { logger.error("list(): I/O error parsing response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidResponse", "I/O error parsing " + response); + throw new CommunicationException("I/O error parsing " + response); } return distributions; } @@ -214,8 +209,7 @@ public boolean isSubscribed() throws InternalException, CloudException { } } catch( IOException e ) { - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidResponse", "I/O error parsing " + response); + throw new CommunicationException("I/O error parsing " + response); } return distributions; } @@ -289,7 +283,7 @@ else if( key.equalsIgnoreCase("X-CDN-URI") ) { } } catch( URISyntaxException e ) { - throw new CloudException(e); + throw new GeneralCloudException("Unable to parse the service URL from " + uriString, CloudErrorType.GENERAL); } Distribution distribution = new Distribution(); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/hp/db/HPRDBMS.java b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/hp/db/HPRDBMS.java index c354f7c..eb7c098 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/hp/db/HPRDBMS.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/hp/db/HPRDBMS.java @@ -20,11 +20,7 @@ package org.dasein.cloud.openstack.nova.os.ext.hp.db; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.*; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.openstack.nova.os.NovaMethod; import org.dasein.cloud.openstack.nova.os.NovaOpenStack; @@ -57,22 +53,15 @@ public class HPRDBMS extends AbstractRelationalDatabaseSupport { public HPRDBMS(NovaOpenStack provider) { super(provider); } private @Nonnull String getTenantId() throws CloudException, InternalException { - return getProvider().getContext().getAccountNumber(); + return getContext().getAccountNumber(); } @Override public @Nonnull String createFromScratch(@Nonnull String dataSourceName, @Nonnull DatabaseProduct product, @Nonnull String databaseVersion, @Nonnull String withAdminUser, @Nonnull String withAdminPassword, int hostPort) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.createFromScratch"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - - Map wrapper = new HashMap(); - Map json = new HashMap(); + Map wrapper = new HashMap<>(); + Map json = new HashMap<>(); NovaMethod method = new NovaMethod(getProvider()); json.put("flavorRef", getFlavorRef(product.getProductSize())); @@ -80,7 +69,7 @@ public class HPRDBMS extends AbstractRelationalDatabaseSupport { json.put("name", dataSourceName); json.put("port", hostPort > 0 ? hostPort : 3306); if( product.getEngine().equals(DatabaseEngine.MYSQL) ) { - Map type = new HashMap(); + Map type = new HashMap<>(); type.put("name", "mysql"); if( databaseVersion != null ) { @@ -99,14 +88,14 @@ else if( product.getEngine().equals(DatabaseEngine.MYSQL50) ) { json.put("dbtype", type); } else { - throw new CloudException("Unsupported database product: " + product); + throw new InternalException("Unsupported database product: " + product); } wrapper.put("instance", json); JSONObject result = method.postString(SERVICE, RESOURCE, null, new JSONObject(wrapper), true); if( result != null && result.has("instance") ) { try { - Database db = toDatabase(ctx, result.getJSONObject("instance")); + Database db = toDatabase(result.getJSONObject("instance")); if( db != null ) { return db.getProviderDatabaseId(); @@ -114,12 +103,11 @@ else if( product.getEngine().equals(DatabaseEngine.MYSQL50) ) { } catch( JSONException e ) { logger.error("createFromScratch(): Unable to understand create response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Unable to understand create response: " + e.getMessage(), e); } } logger.error("createFromScratch(): No database was created by the create attempt, and no error was returned"); - throw new CloudException("No database was created"); + throw new GeneralCloudException("No database was created", CloudErrorType.GENERAL); } finally { @@ -139,7 +127,7 @@ public String createFromLatest(String dataSourceName, String providerDatabaseId, } } if( snapshot == null ) { - throw new CloudException("No snapshots exist from which to create a new database instance"); + throw new InternalException("No snapshots exist from which to create a new database instance"); } return createFromSnapshot(dataSourceName, providerDatabaseId, snapshot.getProviderSnapshotId(), productSize, providerDataCenterId, hostPort); } @@ -152,15 +140,8 @@ public String createFromLatest(String dataSourceName, String providerDatabaseId, public String createFromSnapshot(String dataSourceName, String providerDatabaseId, String providerDbSnapshotId, String productSize, String providerDataCenterId, int hostPort) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.createFromSnapshot"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - - Map wrapper = new HashMap(); - Map json = new HashMap(); + Map wrapper = new HashMap<>(); + Map json = new HashMap<>(); NovaMethod method = new NovaMethod(getProvider()); json.put("flavorRef", getFlavorRef(productSize)); @@ -174,7 +155,7 @@ public String createFromSnapshot(String dataSourceName, String providerDatabaseI if( result != null && result.has("instance") ) { try { - Database db = toDatabase(ctx, result.getJSONObject("instance")); + Database db = toDatabase(result.getJSONObject("instance")); if( db != null ) { return db.getProviderDatabaseId(); @@ -182,12 +163,11 @@ public String createFromSnapshot(String dataSourceName, String providerDatabaseI } catch( JSONException e ) { logger.error("createFromSnapshot(): Unable to understand create response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Unable to understand create response: " + e.getMessage(), e); } } logger.error("createFromSnapshot(): No database was created by the create attempt, and no error was returned"); - throw new CloudException("No database was created"); + throw new GeneralCloudException("No database was created", CloudErrorType.GENERAL); } finally { @@ -207,7 +187,7 @@ public String createFromTimestamp(String dataSourceName, String providerDatabase } } if( snapshot == null ) { - throw new CloudException("No snapshots exist from which to create a new database instance"); + throw new InternalException("No snapshots exist from which to create a new database instance"); } return createFromSnapshot(dataSourceName, providerDatabaseId, snapshot.getProviderSnapshotId(), productSize, providerDataCenterId, hostPort); } @@ -235,12 +215,6 @@ public RelationalDatabaseCapabilities getCapabilities() throws InternalException public @Nullable Database getDatabase(@Nonnull String providerDatabaseId) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.getDatabase"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getResource(SERVICE, RESOURCE, providerDatabaseId, false); @@ -249,12 +223,12 @@ public RelationalDatabaseCapabilities getCapabilities() throws InternalException } try { if( ob.has("instance") ) { - return toDatabase(ctx, ob.getJSONObject("instance")); + return toDatabase(ob.getJSONObject("instance")); } } catch( JSONException e ) { logger.error("getDatabase(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for instance"); + throw new CommunicationException("Unable to understand create response: " + e.getMessage(), e); } return null; } @@ -308,17 +282,11 @@ public Iterable getDatabaseProducts(DatabaseEngine forEngine) t std.trace("ENTER: " + HPRDBMS.class.getName() + ".getDatabaseProducts()"); } try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - std.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); JSONObject json = method.getResource(SERVICE, "/flavors", null, false); - List products = new ArrayList(); + List products = new ArrayList<>(); if( json != null && json.has("flavors") ) { try { @@ -329,7 +297,7 @@ public Iterable getDatabaseProducts(DatabaseEngine forEngine) t if( flavor != null ) { for( int size : new int[] { 2, 5, 10, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200, 250, 300, 400, 500, 600, 700, 800, 900, 1000 } ) { - DatabaseProduct product = toProduct(ctx, size, flavor); + DatabaseProduct product = toProduct(size, flavor); if( product != null ) { products.add(product); @@ -340,8 +308,7 @@ public Iterable getDatabaseProducts(DatabaseEngine forEngine) t } catch( JSONException e ) { std.error("getDatabaseProducts(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors in " + json.toString()); + throw new CommunicationException("Unable to identify expected values in JSON: " + e.getMessage(), e); } } return products; @@ -360,23 +327,15 @@ public Iterable getDatabaseProducts(DatabaseEngine forEngine) t @Override public Iterable listDatabaseProducts(DatabaseEngine databaseEngine) throws CloudException, InternalException { if( DatabaseEngine.MYSQL.equals(databaseEngine) ) { - Logger std = NovaOpenStack.getLogger(HPRDBMS.class, "std"); - - if( std.isTraceEnabled() ) { - std.trace("ENTER: " + HPRDBMS.class.getName() + ".getDatabaseProducts()"); + if( logger.isTraceEnabled() ) { + logger.trace("ENTER: " + HPRDBMS.class.getName() + ".getDatabaseProducts()"); } try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - std.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); JSONObject json = method.getResource(SERVICE, "/flavors", null, false); - List products = new ArrayList(); + List products = new ArrayList<>(); if( json != null && json.has("flavors") ) { try { @@ -387,7 +346,7 @@ public Iterable listDatabaseProducts(DatabaseEngine databaseEng if( flavor != null ) { for( int size : new int[] { 2, 5, 10, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200, 250, 300, 400, 500, 600, 700, 800, 900, 1000 } ) { - DatabaseProduct product = toProduct(ctx, size, flavor); + DatabaseProduct product = toProduct(size, flavor); if( product != null ) { products.add(product); @@ -397,16 +356,15 @@ public Iterable listDatabaseProducts(DatabaseEngine databaseEng } } catch( JSONException e ) { - std.error("getDatabaseProducts(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors in " + json.toString()); + logger.error("getDatabaseProducts(): Unable to identify expected values in JSON: " + e.getMessage()); + throw new CommunicationException("Unable to identify expected values in JSON: " + e.getMessage(), e); } } return products; } finally { - if( std.isTraceEnabled() ) { - std.trace("exit - " + HPRDBMS.class.getName() + ".getDatabaseProducts()"); + if( logger.isTraceEnabled() ) { + logger.trace("exit - " + HPRDBMS.class.getName() + ".getDatabaseProducts()"); } } } @@ -416,18 +374,10 @@ public Iterable listDatabaseProducts(DatabaseEngine databaseEng } private @Nullable String getFlavorRef(@Nonnull String productId) throws CloudException, InternalException { - Logger std = NovaOpenStack.getLogger(HPRDBMS.class, "std"); - - if( std.isTraceEnabled() ) { - std.trace("ENTER: " + HPRDBMS.class.getName() + ".getFlavorRef(" + productId + ")"); + if( logger.isTraceEnabled() ) { + logger.trace("ENTER: " + HPRDBMS.class.getName() + ".getFlavorRef(" + productId + ")"); } try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - std.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } int idx = productId.indexOf(":"); if( idx > -1 ) { @@ -460,16 +410,15 @@ public Iterable listDatabaseProducts(DatabaseEngine databaseEng } } catch( JSONException e ) { - std.error("getFlavorRef(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors in " + json.toString()); + logger.error("getFlavorRef(): Unable to identify expected values in JSON: " + e.getMessage()); + throw new CommunicationException("Unable to identify expected values in JSON: " + e.getMessage(), e); } } return null; } finally { - if( std.isTraceEnabled() ) { - std.trace("exit - " + HPRDBMS.class.getName() + ".getFlavorRef()"); + if( logger.isTraceEnabled() ) { + logger.trace("exit - " + HPRDBMS.class.getName() + ".getFlavorRef()"); } } } @@ -478,12 +427,6 @@ public Iterable listDatabaseProducts(DatabaseEngine databaseEng public DatabaseSnapshot getSnapshot(String providerDbSnapshotId) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.getSnapshot"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getResource(SERVICE, SNAPSHOTS, providerDbSnapshotId, false); @@ -492,12 +435,12 @@ public DatabaseSnapshot getSnapshot(String providerDbSnapshotId) throws CloudExc } try { if( ob.has("snapshot") ) { - return toSnapshot(ctx, ob.getJSONObject("snapshot")); + return toSnapshot(ob.getJSONObject("snapshot")); } } catch( JSONException e ) { logger.error("getSnapshot(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for snapshots"); + throw new CommunicationException("Unable to identify expected values in JSON: " + e.getMessage(), e); } return null; } @@ -532,7 +475,7 @@ public Iterable listConfigurations() throws CloudExceptio APITrace.begin(getProvider(), "RDBMS.listDatabaseStatus"); try { NovaMethod method = new NovaMethod(getProvider()); - List databases = new ArrayList(); + List databases = new ArrayList<>(); JSONObject json = method.getResource(SERVICE, RESOURCE, null, false); @@ -549,8 +492,7 @@ public Iterable listConfigurations() throws CloudExceptio } } catch( JSONException e ) { - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for instances in " + json.toString()); + throw new CommunicationException("Unable to identify expected values in JSON: " + e.getMessage(), e); } } return databases; @@ -564,14 +506,8 @@ public Iterable listConfigurations() throws CloudExceptio public Iterable listDatabases() throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.listDatabases"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); - List databases = new ArrayList(); + List databases = new ArrayList<>(); JSONObject json = method.getResource(SERVICE, RESOURCE, null, false); @@ -580,7 +516,7 @@ public Iterable listDatabases() throws CloudException, InternalExcepti JSONArray list = json.getJSONArray("instances"); for( int i=0; i listDatabases() throws CloudException, InternalExcepti } catch( JSONException e ) { logger.error("listDatabases(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for instances in " + json.toString()); + throw new CommunicationException("Unable to identify expected values in JSON: " + e.getMessage(), e); } } return databases; @@ -609,12 +544,6 @@ public Collection listParameters(String forProviderConfi public Iterable listSnapshots(String forOptionalProviderDatabaseId) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.listSnapshots"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); List snapshots = new ArrayList(); @@ -625,7 +554,7 @@ public Iterable listSnapshots(String forOptionalProviderDataba JSONArray list = json.getJSONArray("snapshots"); for( int i=0; i listSnapshots(String forOptionalProviderDataba } catch( JSONException e ) { logger.error("listSnapshots(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for snapshots in " + json.toString()); + throw new CommunicationException("Unable to identify expected values in JSON: " + e.getMessage(), e); } } return snapshots; @@ -649,12 +577,6 @@ public Iterable listSnapshots(String forOptionalProviderDataba public void removeDatabase(String providerDatabaseId) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.removeDatabase"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); method.deleteResource(SERVICE, RESOURCE, providerDatabaseId, null); @@ -668,14 +590,7 @@ public void removeDatabase(String providerDatabaseId) throws CloudException, Int public void removeSnapshot(String providerSnapshotId) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.removeSnapshot"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); - method.deleteResource(SERVICE, SNAPSHOTS, providerSnapshotId, null); } finally { @@ -692,15 +607,7 @@ public void resetConfiguration(String providerConfigurationId, String... paramet public void restart(String providerDatabaseId, boolean blockUntilDone) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.restart"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - NovaMethod method = new NovaMethod(getProvider()); - method.postResourceHeaders(SERVICE, RESOURCE, providerDatabaseId + "/restart", new HashMap()); } @@ -713,15 +620,8 @@ public void restart(String providerDatabaseId, boolean blockUntilDone) throws Cl public DatabaseSnapshot snapshot(String providerDatabaseId, String name) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.snapshot"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - - Map wrapper = new HashMap(); - Map json = new HashMap(); + Map wrapper = new HashMap<>(); + Map json = new HashMap<>(); NovaMethod method = new NovaMethod(getProvider()); json.put("name", name); @@ -732,7 +632,7 @@ public DatabaseSnapshot snapshot(String providerDatabaseId, String name) throws if( result != null && result.has("snapshot") ) { try { - DatabaseSnapshot snapshot = toSnapshot(ctx, result.getJSONObject("snapshot")); + DatabaseSnapshot snapshot = toSnapshot(result.getJSONObject("snapshot")); if( snapshot != null ) { return snapshot; @@ -740,12 +640,11 @@ public DatabaseSnapshot snapshot(String providerDatabaseId, String name) throws } catch( JSONException e ) { logger.error("snapshot(): Unable to understand create response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Unable to understand create response: " + e.getMessage(), e); } } logger.error("snapshot(): No snapshot was created by the create attempt, and no error was returned"); - throw new CloudException("No snapshot was created"); + throw new GeneralCloudException("No snapshot was created", CloudErrorType.GENERAL); } finally { @@ -758,12 +657,12 @@ public DatabaseSnapshot snapshot(String providerDatabaseId, String name) throws return new String[0]; } - private @Nullable Database toDatabase(@Nonnull ProviderContext ctx, @Nullable JSONObject json) throws CloudException, InternalException { + private @Nullable Database toDatabase(@Nullable JSONObject json) throws CloudException, InternalException { if( json == null ) { return null; } - String regionId = ctx.getRegionId(); + String regionId = getContext().getRegionId(); try { String dbId = (json.has("id") ? json.getString("id") : null); @@ -792,7 +691,7 @@ else if( status.equalsIgnoreCase("running") ) { currentState = DatabaseState.AVAILABLE; } else { - System.out.println("DEBUG OS DB STATE: " + status); + logger.debug("DEBUG OS DB STATE: " + status); } } long created = (json.has("created") ? getProvider().parseTimestamp(json.getString("created")) : -1L); @@ -847,13 +746,13 @@ else if( version.startsWith("5.0") ) { } else { */ - System.out.println("DEBUG OS UNKNOWN MYSQL VERSION " + version); + logger.debug("DEBUG OS UNKNOWN MYSQL VERSION " + version); engine = DatabaseEngine.MYSQL; // } } } else { - System.out.println("DEBUG OS UNKNOWN DB: " + db + " " + version); + logger.debug("DEBUG OS UNKNOWN DB: " + db + " " + version); } } DatabaseProduct product = (flavor == null ? null : getDatabaseProduct(flavor)); @@ -871,24 +770,24 @@ else if( version.startsWith("5.0") ) { database.setName(name); database.setProductSize(flavor); database.setProviderDatabaseId(dbId); - database.setProviderRegionId(ctx.getRegionId()); + database.setProviderRegionId(getContext().getRegionId()); database.setProviderDataCenterId(regionId + "-a"); database.setProviderOwnerId(getTenantId()); database.setProviderRegionId(regionId); return database; } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to understand response: " + e.getMessage(), e); } } - private @Nullable DatabaseSnapshot toSnapshot(@Nonnull ProviderContext ctx, @Nullable JSONObject json) throws CloudException, InternalException { + private @Nullable DatabaseSnapshot toSnapshot(@Nullable JSONObject json) throws CloudException, InternalException { if( json == null ) { return null; } try { - String regionId = ctx.getRegionId(); + String regionId = getContext().getRegionId(); String snapshotId = (json.has("id") ? json.getString("id") : null); @@ -911,7 +810,7 @@ else if( status.equalsIgnoreCase("deleted") ) { currentState = DatabaseSnapshotState.DELETED; } else { - System.out.println("DEBUG OS DBSNAP STATE: " + status); + logger.debug("DEBUG OS DBSNAP STATE: " + status); } } long created = (json.has("created") ? getProvider().parseTimestamp(json.getString("created")) : -1L); @@ -929,11 +828,11 @@ else if( status.equalsIgnoreCase("deleted") ) { return snapshot; } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to understand response: " + e.getMessage(), e); } } - private @Nullable DatabaseProduct toProduct(@Nonnull ProviderContext ctx, @Nonnegative int size, @Nullable JSONObject json) throws CloudException, InternalException { + private @Nullable DatabaseProduct toProduct(@Nonnegative int size, @Nullable JSONObject json) throws CloudException, InternalException { if( json == null ) { return null; } @@ -954,7 +853,7 @@ else if( status.equalsIgnoreCase("deleted") ) { } id = id + ":" + size; - String regionId = ctx.getRegionId(); + String regionId = getContext().getRegionId(); if( regionId == null ) { throw new InternalException("No region is associated with this request"); @@ -978,7 +877,7 @@ else if( status.equalsIgnoreCase("deleted") ) { return product; } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to understand response: " + e.getMessage(), e); } } @@ -1008,13 +907,13 @@ else if( status.equalsIgnoreCase("running") ) { currentState = DatabaseState.AVAILABLE; } else { - System.out.println("DEBUG OS DB STATE: " + status); + logger.debug("DEBUG OS DB STATE: " + status); } } return new ResourceStatus(dbId, currentState); } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to understand response: " + e.getMessage(), e); } } } diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/cdn/RackspaceCDN.java b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/cdn/RackspaceCDN.java index 39681a9..3149d37 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/cdn/RackspaceCDN.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/cdn/RackspaceCDN.java @@ -313,7 +313,7 @@ else if( key.equalsIgnoreCase("X-CDN-SSL-URI") ) { } } catch( URISyntaxException e ) { - throw new CloudException(e); + throw new InternalException(e); } Distribution distribution = new Distribution(); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/db/RackspaceRDBMS.java b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/db/RackspaceRDBMS.java index b3d22bf..4f66951 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/db/RackspaceRDBMS.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/db/RackspaceRDBMS.java @@ -20,11 +20,7 @@ package org.dasein.cloud.openstack.nova.os.ext.rackspace.db; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.*; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.openstack.nova.os.NovaMethod; import org.dasein.cloud.openstack.nova.os.NovaOpenStack; @@ -59,29 +55,22 @@ public RackspaceRDBMS(NovaOpenStack provider) { } private @Nonnull String getTenantId() throws CloudException, InternalException { - return getProvider().getContext().getAccountNumber(); + return getContext().getAccountNumber(); } @Override public @Nonnull String createFromScratch(@Nonnull String dataSourceName, @Nonnull DatabaseProduct product, @Nonnull String databaseVersion, @Nonnull String withAdminUser, @Nonnull String withAdminPassword, int hostPort) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.createFromScratch"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - - Map wrapper = new HashMap(); - Map json = new HashMap(); + Map wrapper = new HashMap<>(); + Map json = new HashMap<>(); NovaMethod method = new NovaMethod(getProvider()); - Map database = new HashMap(); + Map database = new HashMap<>(); database.put("name", dataSourceName); - List> dblist= new ArrayList>(); + List> dblist= new ArrayList<>(); dblist.add(database); @@ -93,14 +82,14 @@ public RackspaceRDBMS(NovaOpenStack provider) { json.put("flavorRef", getFlavorRef(id)); json.put("name", dataSourceName); if( withAdminUser != null && withAdminPassword != null ) { - List> users = new ArrayList>(); - Map entry = new HashMap(); + List> users = new ArrayList<>(); + Map entry = new HashMap<>(); entry.put("name", withAdminUser); entry.put("password", withAdminPassword); - List> dbaccess = new ArrayList>(); - Map oneDb = new HashMap(); + List> dbaccess = new ArrayList<>(); + Map oneDb = new HashMap<>(); oneDb.put("name", dataSourceName); dbaccess.add(oneDb); @@ -114,7 +103,7 @@ public RackspaceRDBMS(NovaOpenStack provider) { if( size < 1 ) { size = 5; } - Map volume = new HashMap(); + Map volume = new HashMap<>(); volume.put("size", String.valueOf(size)); @@ -128,7 +117,7 @@ public RackspaceRDBMS(NovaOpenStack provider) { if( result != null && result.has("instance") ) { try { - Database db = toDatabase(ctx, result.getJSONObject("instance")); + Database db = toDatabase(result.getJSONObject("instance")); if( db != null ) { return db.getProviderDatabaseId(); @@ -136,12 +125,12 @@ public RackspaceRDBMS(NovaOpenStack provider) { } catch( JSONException e ) { logger.error("createFromScratch(): Unable to understand create response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Unable to parse the response", e); } } logger.error("createFromScratch(): No database was created by the create attempt, and no error was returned"); - throw new CloudException("No database was created"); + throw new GeneralCloudException("No database was created", CloudErrorType.GENERAL); + } finally { @@ -168,12 +157,6 @@ public RackspaceRDBMS(NovaOpenStack provider) { public @Nullable Database getDatabase(@Nonnull String providerDatabaseId) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.getDatabase"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getResource(SERVICE, RESOURCE, providerDatabaseId, false); @@ -182,12 +165,12 @@ public RackspaceRDBMS(NovaOpenStack provider) { } try { if( ob.has("instance") ) { - return toDatabase(ctx, ob.getJSONObject("instance")); + return toDatabase(ob.getJSONObject("instance")); } } catch( JSONException e ) { logger.error("getDatabase(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for instance"); + throw new CommunicationException("Missing JSON element for instance", e); } return null; } @@ -217,15 +200,10 @@ public Iterable getSupportedVersions(DatabaseEngine forEngine) throws Cl return Collections.emptyList(); } + public @Nullable DatabaseProduct getDatabaseProduct(@Nonnull String flavor) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.getDatabaseProduct"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } int idx = flavor.indexOf(":"); int size = 5; @@ -239,12 +217,11 @@ public Iterable getSupportedVersions(DatabaseEngine forEngine) throws Cl if( json != null && json.has("flavor") ) { try { - return toProduct(ctx, size, json.getJSONObject("flavor")); + return toProduct(size, json.getJSONObject("flavor")); } catch( JSONException e ) { logger.error("getDatabaseProduct(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors in " + json.toString()); + throw new CommunicationException("Missing JSON element for flavors ", e); } } return null; @@ -259,23 +236,15 @@ public Iterable listDatabaseProducts(DatabaseEngine databaseEng APITrace.begin(getProvider(), "RDBMS.getDatabaseProducts"); try { if( DatabaseEngine.MYSQL.equals(databaseEngine) ) { - Logger std = NovaOpenStack.getLogger(RackspaceRDBMS.class, "std"); - - if( std.isTraceEnabled() ) { - std.trace("ENTER: " + RackspaceRDBMS.class.getName() + ".getDatabaseProducts()"); + if( logger.isTraceEnabled() ) { + logger.trace("ENTER: " + RackspaceRDBMS.class.getName() + ".getDatabaseProducts()"); } try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - std.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); JSONObject json = method.getResource(SERVICE, "/flavors", null, false); - List products = new ArrayList(); + List products = new ArrayList<>(); if( json != null && json.has("flavors") ) { try { @@ -286,7 +255,7 @@ public Iterable listDatabaseProducts(DatabaseEngine databaseEng if( flavor != null ) { for( int size : new int[] { 2, 5, 10, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100, 150}) { //150 is max size , 200, 250, 300, 400, 500, 600, 700, 800, 900, 1000 } ) { - DatabaseProduct product = toProduct(ctx, size, flavor); + DatabaseProduct product = toProduct(size, flavor); if( product != null ) { products.add(product); @@ -296,16 +265,15 @@ public Iterable listDatabaseProducts(DatabaseEngine databaseEng } } catch( JSONException e ) { - std.error("getDatabaseProducts(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors in " + json.toString()); + logger.error("getDatabaseProducts(): Unable to identify expected values in JSON: " + e.getMessage()); + throw new CommunicationException("Unable to parse the response", e); } } return products; } finally { - if( std.isTraceEnabled() ) { - std.trace("exit - " + RackspaceRDBMS.class.getName() + ".getDatabaseProducts()"); + if( logger.isTraceEnabled() ) { + logger.trace("exit - " + RackspaceRDBMS.class.getName() + ".getDatabaseProducts()"); } } } @@ -321,12 +289,6 @@ public Iterable listDatabaseProducts(DatabaseEngine databaseEng private @Nullable String getFlavorRef(@Nonnull String productId) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.getFlavorRef"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } int idx = productId.indexOf(":"); if( idx > -1 ) { @@ -360,8 +322,7 @@ public Iterable listDatabaseProducts(DatabaseEngine databaseEng } catch( JSONException e ) { logger.error("getFlavorRef(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for flavors in " + json.toString()); + throw new CommunicationException("Unable to parse the response", e); } } return null; @@ -391,11 +352,6 @@ public boolean isSubscribed() throws CloudException, InternalException { public @Nonnull Iterable listDatabaseStatus() throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.listDatabaseStatus"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); List databases = new ArrayList(); @@ -414,7 +370,7 @@ public boolean isSubscribed() throws CloudException, InternalException { } } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for instances in " + json.toString()); + throw new CommunicationException("Missing JSON element for instances", e); } } return databases; @@ -428,14 +384,8 @@ public boolean isSubscribed() throws CloudException, InternalException { public Iterable listDatabases() throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.listDatabases"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); - List databases = new ArrayList(); + List databases = new ArrayList<>(); JSONObject json = method.getResource(SERVICE, RESOURCE, null, false); @@ -444,7 +394,7 @@ public Iterable listDatabases() throws CloudException, InternalExcepti JSONArray list = json.getJSONArray("instances"); for( int i=0; i listDatabases() throws CloudException, InternalExcepti } catch( JSONException e ) { logger.error("listDatabases(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for instances in " + json.toString()); + throw new CommunicationException("Missing JSON element for instances", e); } } return databases; @@ -468,12 +417,6 @@ public Iterable listDatabases() throws CloudException, InternalExcepti public void removeDatabase(String providerDatabaseId) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.removeDatabase"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(getProvider()); method.deleteResource(SERVICE, RESOURCE, providerDatabaseId, null); @@ -509,15 +452,8 @@ public void resetConfiguration(String providerConfigurationId, String... paramet public void restart(String providerDatabaseId, boolean blockUntilDone) throws CloudException, InternalException { APITrace.begin(getProvider(), "RDBMS.restart"); try { - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - NovaMethod method = new NovaMethod(getProvider()); - Map wrapper = new HashMap(); + Map wrapper = new HashMap<>(); wrapper.put("restart", new HashMap()); method.postString(SERVICE, RESOURCE, "action", new JSONObject(wrapper), false); @@ -532,12 +468,12 @@ public void restart(String providerDatabaseId, boolean blockUntilDone) throws Cl return new String[0]; } - private @Nullable Database toDatabase(@Nonnull ProviderContext ctx, @Nullable JSONObject json) throws CloudException, InternalException { + private @Nullable Database toDatabase(@Nullable JSONObject json) throws CloudException, InternalException { if( json == null ) { return null; } - String regionId = ctx.getRegionId(); + String regionId = getContext().getRegionId(); try { String dbId = (json.has("id") ? json.getString("id") : null); @@ -617,11 +553,11 @@ else if( status.equalsIgnoreCase("BLOCKED") ) { return database; } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to parse the response", e); } } - private @Nullable DatabaseProduct toProduct(@Nonnull ProviderContext ctx, @Nonnegative int size, @Nullable JSONObject json) throws CloudException, InternalException { + private @Nullable DatabaseProduct toProduct(@Nonnegative int size, @Nullable JSONObject json) throws CloudException, InternalException { if( json == null ) { return null; } @@ -642,7 +578,7 @@ else if( status.equalsIgnoreCase("BLOCKED") ) { } id = id + ":" + size; - String regionId = ctx.getRegionId(); + String regionId = getContext().getRegionId(); if( regionId == null ) { throw new InternalException("No region is associated with this request"); @@ -666,7 +602,7 @@ else if( status.equalsIgnoreCase("BLOCKED") ) { return product; } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to parse the response", e); } } @@ -707,7 +643,7 @@ else if( status.equalsIgnoreCase("BLOCKED") ) { return new ResourceStatus(dbId, currentState); } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to parse the response", e); } } } \ No newline at end of file diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/dns/RackspaceCloudDNS.java b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/dns/RackspaceCloudDNS.java index b8dd2d7..b3091aa 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/dns/RackspaceCloudDNS.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/dns/RackspaceCloudDNS.java @@ -20,11 +20,7 @@ package org.dasein.cloud.openstack.nova.os.ext.rackspace.dns; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.*; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.network.DNSRecord; import org.dasein.cloud.network.DNSRecordType; @@ -77,7 +73,7 @@ public class RackspaceCloudDNS implements DNSSupport { DNSZone zone = getDnsZone(providerDnsZoneId); if( zone == null ) { - throw new CloudException("No such zone: " + providerDnsZoneId); + throw new InternalException("No such zone: " + providerDnsZoneId); } if( recordType.equals(DNSRecordType.A) || recordType.equals(DNSRecordType.AAAA) || recordType.equals(DNSRecordType.CNAME) || recordType.equals(DNSRecordType.MX) ) { if( name.endsWith(zone.getDomainName() + ".") ) { @@ -133,14 +129,13 @@ else if( !name.endsWith(zone.getDomainName()) ) { } catch( JSONException e ) { logger.error("createDnsZone(): JSON error parsing response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidResponse", "JSON error parsing " + response); + throw new CommunicationException("Unable to understand parsing response: " + e.getMessage(), e); } } } if( lastRecord == null ) { logger.error("addDnsRecord(): No record was created, but no error specified"); - throw new CloudException("No record was created, but no error specified"); + throw new GeneralCloudException("No record was created, but no error specified", CloudErrorType.GENERAL); } return lastRecord; } @@ -194,11 +189,11 @@ else if( !name.endsWith(zone.getDomainName()) ) { } catch( JSONException e ) { logger.error("createDnsZone(): JSON error parsing response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidResponse", "JSON error parsing " + response); + throw new CommunicationException("Unable to understand createDnsZone() response: " + e.getMessage(), e); } logger.error("createDnsZone(): No zone was created, but no error specified"); - throw new CloudException("No zone was created, but no error specified"); + throw new GeneralCloudException("No zone was created, but no error specified", CloudErrorType.GENERAL); + } finally { APITrace.end(); @@ -245,8 +240,7 @@ else if( !name.endsWith(zone.getDomainName()) ) { } catch( JSONException e ) { logger.error("lookupRecord(): JSON error parsing response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidResponse", "JSON error parsing " + response); + throw new GeneralCloudException("createDnsZone(): JSON error parsing response", CloudErrorType.GENERAL); } return ids; } @@ -324,7 +318,7 @@ private void listSubdomains(@Nonnull ProviderContext ctx, @Nonnull List } } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to understand response: " + e.getMessage(), e); } } @@ -380,8 +374,7 @@ private CompleteDNS getCompleteDNS(@Nonnull String providerDnsZoneId, boolean wi } catch( JSONException e ) { std.error("getCompleteDNS(): JSON error parsing response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidResponse", "JSON error parsing " + response); + throw new CommunicationException("Unable to understand getCompleteDNS() response: " + e.getMessage(), e); } return null; } @@ -409,7 +402,7 @@ private CompleteDNS getCompleteDNS(@Nonnull String providerDnsZoneId, boolean wi DNSZone zone = getDnsZone(providerDnsZoneId); if( zone == null ) { - throw new CloudException("No such zone: " + providerDnsZoneId); + throw new InternalException("No such zone: " + providerDnsZoneId); } ProviderContext ctx = provider.getContext(); @@ -458,8 +451,7 @@ private CompleteDNS getCompleteDNS(@Nonnull String providerDnsZoneId, boolean wi } catch( JSONException e ) { logger.error("listDnsRecords(): JSON error parsing response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidResponse", "JSON error parsing " + response); + throw new CommunicationException("Unable to understand listDnsRecords() response: " + e.getMessage(), e); } return records; } @@ -514,7 +506,7 @@ private CompleteDNS getCompleteDNS(@Nonnull String providerDnsZoneId, boolean wi } } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidResponse", "JSON error parsing " + response); + throw new CommunicationException("Invalid response: " + e.getMessage(), e); } return zones; } @@ -576,8 +568,7 @@ private CompleteDNS getCompleteDNS(@Nonnull String providerDnsZoneId, boolean wi } catch( JSONException e ) { logger.error("listDnsZones(): JSON error parsing response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidResponse", "JSON error parsing " + response); + throw new CommunicationException("Unable to understand listDnsZones() response: " + e.getMessage(), e); } return zones; } @@ -641,7 +632,7 @@ public boolean isSubscribed() throws CloudException, InternalException { return record; } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to understand response: " + e.getMessage(), e); } } @@ -694,7 +685,7 @@ public boolean isSubscribed() throws CloudException, InternalException { return zone; } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to understand response: " + e.getMessage(), e); } } @@ -712,12 +703,12 @@ private JSONObject waitForJob(String jobId) throws CloudException, InternalExcep JSONObject response = method.getResource(SERVICE, "/status", jobId + "?showDetails=true", false); if( response == null ) { - throw new CloudException("Job disappeared"); + throw new GeneralCloudException("Job disappeared", CloudErrorType.GENERAL); } String status = (response.has("status")? response.getString("status") : null); if( status == null ) { - throw new CloudException("No job status"); + throw new GeneralCloudException("No job status", CloudErrorType.GENERAL); } if( status.equalsIgnoreCase("completed") ) { if( response.has("response") ) { @@ -729,21 +720,21 @@ else if( status.equalsIgnoreCase("error") ) { JSONObject error = response.getJSONObject("error"); if( error == null ) { - throw new CloudException("Unknown error"); + throw new InternalException("Unknown error"); } int code = (error.has("code") ? error.getInt("code") : 418); throw new NovaException(NovaException.parseException(code, error.toString())); } - throw new CloudException("Unknown error"); + throw new InternalException("Unknown error"); } } catch( JSONException e ) { - throw new CloudException("Invalid JSON from server: " + e.getMessage()); + throw new CommunicationException("Unable to understand response: " + e.getMessage(), e); } try { Thread.sleep(CalendarWrapper.SECOND * 30); } catch( InterruptedException ignore ) { } } - throw new CloudException("Operation timed out"); + throw new GeneralCloudException("Operation timed out", CloudErrorType.GENERAL); } } \ No newline at end of file diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLBCapabilities.java b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLBCapabilities.java index 852a661..f1dd219 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLBCapabilities.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLBCapabilities.java @@ -227,7 +227,8 @@ else if( name.equalsIgnoreCase("https") ) { } } catch( JSONException e ) { - throw new CloudException("Unable to parse protocols from Rackspace: " + e.getMessage()); + throw new CommunicationException("Unable to parse protocols from Rackspace:" + e.getMessage(), e); + } cache.put(getContext(), list); return list; diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLoadBalancers.java b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLoadBalancers.java index f2b1d43..f598031 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLoadBalancers.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLoadBalancers.java @@ -21,36 +21,13 @@ import org.apache.http.HttpStatus; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.OperationNotSupportedException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.Requirement; -import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.*; import org.dasein.cloud.compute.VirtualMachine; -import org.dasein.cloud.network.AbstractLoadBalancerSupport; -import org.dasein.cloud.network.IPVersion; -import org.dasein.cloud.network.LbAlgorithm; -import org.dasein.cloud.network.LbEndpointState; -import org.dasein.cloud.network.LbEndpointType; -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.LoadBalancerCapabilities; -import org.dasein.cloud.network.LoadBalancerCreateOptions; -import org.dasein.cloud.network.LoadBalancerEndpoint; -import org.dasein.cloud.network.LoadBalancerState; -import org.dasein.cloud.network.RawAddress; +import org.dasein.cloud.network.*; import org.dasein.cloud.openstack.nova.os.NovaException; import org.dasein.cloud.openstack.nova.os.NovaMethod; import org.dasein.cloud.openstack.nova.os.NovaOpenStack; import org.dasein.cloud.util.APITrace; -import org.dasein.cloud.util.Cache; -import org.dasein.cloud.util.CacheLevel; import org.dasein.util.CalendarWrapper; import org.json.JSONArray; import org.json.JSONException; @@ -58,13 +35,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.TreeSet; +import java.util.*; public class RackspaceLoadBalancers extends AbstractLoadBalancerSupport { @@ -81,19 +52,19 @@ public RackspaceLoadBalancers(NovaOpenStack provider) { } private @Nonnull String getTenantId() throws CloudException, InternalException { - return getProvider().getContext().getAccountNumber(); + return getContext().getAccountNumber(); } public void addIPEndpoints(@Nonnull String toLoadBalancerId, @Nonnull String ... ipAddresses) throws CloudException, InternalException { APITrace.begin(provider, "LB.addIPEndpoints"); try { - ArrayList> nodes = new ArrayList>(); + List> nodes = new ArrayList<>(); LoadBalancer lb = getLoadBalancer(toLoadBalancerId); int port = -1; if( lb == null ) { logger.error("No such load balancer: " + toLoadBalancerId); - throw new CloudException("No such load balancer: " + toLoadBalancerId); + throw new GeneralCloudException("No such load balancer: " + toLoadBalancerId, CloudErrorType.GENERAL); } long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 5L); @@ -133,14 +104,14 @@ public void addIPEndpoints(@Nonnull String toLoadBalancerId, @Nonnull String ... } if( port == -1 ) { logger.error("Could not determine a proper private port for mapping"); - throw new CloudException("No port understanding exists for this load balancer"); + throw new GeneralCloudException("No port understanding exists for this load balancer", CloudErrorType.GENERAL); } } for( String address : ipAddresses ) { if( logger.isTraceEnabled() ) { logger.trace("Adding " + address + "..."); } - HashMap node = new HashMap(); + Map node = new HashMap<>(); node.put("address", address); @@ -149,7 +120,7 @@ public void addIPEndpoints(@Nonnull String toLoadBalancerId, @Nonnull String ... nodes.add(node); } if( !nodes.isEmpty() ) { - HashMap json = new HashMap(); + Map json = new HashMap<>(); json.put("nodes", nodes); NovaMethod method = new NovaMethod(provider); @@ -172,13 +143,13 @@ public void addIPEndpoints(@Nonnull String toLoadBalancerId, @Nonnull String ... public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String... serverIdsToAdd) throws CloudException, InternalException { APITrace.begin(provider, "LB.addServers"); try { - ArrayList> nodes = new ArrayList>(); + List> nodes = new ArrayList<>(); LoadBalancer lb = getLoadBalancer(toLoadBalancerId); int port = -1; if( lb == null ) { logger.error("addServers(): No such load balancer: " + toLoadBalancerId); - throw new CloudException("No such load balancer: " + toLoadBalancerId); + throw new GeneralCloudException("No such load balancer: " + toLoadBalancerId, CloudErrorType.GENERAL); } long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 5L); @@ -218,7 +189,7 @@ public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String... serv } if( port == -1 ) { logger.error("addServers(): Could not determine a proper private port for mapping"); - throw new CloudException("No port understanding exists for this load balancer"); + throw new GeneralCloudException("No port mapping exists for this load balancer", CloudErrorType.GENERAL); } } for( String id : serverIdsToAdd ) { @@ -229,11 +200,11 @@ public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String... serv if( vm == null ) { logger.error("addServers(): Failed to add " + id + " because it does not exist"); - throw new CloudException("No such server: " + id); + throw new ResourceNotFoundException("No such server: " + id); } String address = null; - if( vm.getProviderRegionId().equals(provider.getContext().getRegionId()) ) { + if( vm.getProviderRegionId().equals(getContext().getRegionId()) ) { RawAddress[] possibles = vm.getPrivateAddresses(); address = ((possibles != null && possibles.length > 0) ? possibles[0].getIpAddress() : null); @@ -245,12 +216,12 @@ public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String... serv } if( address == null ) { logger.error("addServers(): No address exists for mapping the load balancer to this server"); - throw new CloudException("The virtual machine " + id + " has no mappable addresses"); + throw new ResourceNotFoundException("The virtual machine " + id + " has no mappable addresses"); } if( logger.isDebugEnabled() ) { logger.debug("addServers(): Mapping IP is: " + address); } - HashMap node = new HashMap(); + Map node = new HashMap<>(); node.put("address", address); @@ -259,7 +230,7 @@ public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String... serv nodes.add(node); } if( !nodes.isEmpty() ) { - HashMap json = new HashMap(); + Map json = new HashMap<>(); json.put("nodes", nodes); NovaMethod method = new NovaMethod(provider); @@ -286,9 +257,9 @@ public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String... serv if( listeners == null || listeners.length < 1 ) { logger.error("create(): Call failed to specify any listeners"); - throw new CloudException("Rackspace requires exactly one listener"); + throw new InternalException("Rackspace requires exactly one listener"); } - HashMap lb = new HashMap(); + Map lb = new HashMap<>(); lb.put("name", options.getName()); lb.put("port", listeners[0].getPublicPort()); @@ -303,7 +274,7 @@ else if( listeners[0].getNetworkProtocol().equals(LbProtocol.RAW_TCP) ) { } else { logger.error("Invalid protocol: " + listeners[0].getNetworkProtocol()); - throw new CloudException("Unsupported protocol: " + listeners[0].getNetworkProtocol()); + throw new InternalException("Unsupported protocol: " + listeners[0].getNetworkProtocol()); } if( listeners[0].getAlgorithm().equals(LbAlgorithm.LEAST_CONN) ) { lb.put("algorithm", "LEAST_CONNECTIONS"); @@ -313,20 +284,20 @@ else if( listeners[0].getAlgorithm().equals(LbAlgorithm.ROUND_ROBIN) ) { } else { logger.error("create(): Invalid algorithm: " + listeners[0].getAlgorithm()); - throw new CloudException("Unsupported algorithm: " + listeners[0].getAlgorithm()); + throw new InternalException("Unsupported algorithm: " + listeners[0].getAlgorithm()); } - ArrayList> ips = new ArrayList>(); - HashMap ip = new HashMap(); + List> ips = new ArrayList<>(); + Map ip = new HashMap<>(); ip.put("type", "PUBLIC"); ips.add(ip); lb.put("virtualIps", ips); - ArrayList> nodes = new ArrayList>(); + List> nodes = new ArrayList<>(); LoadBalancerEndpoint[] endpoints = options.getEndpoints(); if( endpoints != null ) { - TreeSet addresses = new TreeSet(); + Set addresses = new TreeSet(); for( LoadBalancerEndpoint endpoint : endpoints ) { String address = null; @@ -338,7 +309,7 @@ else if( listeners[0].getAlgorithm().equals(LbAlgorithm.ROUND_ROBIN) ) { VirtualMachine vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(endpoint.getEndpointValue()); if( vm != null ) { - if( vm.getProviderRegionId().equals(provider.getContext().getRegionId()) ) { + if( vm.getProviderRegionId().equals(getContext().getRegionId()) ) { RawAddress[] tmp = vm.getPrivateAddresses(); if( tmp != null && tmp.length > 0 ) { @@ -355,7 +326,7 @@ else if( listeners[0].getAlgorithm().equals(LbAlgorithm.ROUND_ROBIN) ) { } } if( address != null && !addresses.contains(address) ) { - HashMap node = new HashMap(); + Map node = new HashMap<>(); node.put("address", address); node.put("condition", "ENABLED"); @@ -367,11 +338,11 @@ else if( listeners[0].getAlgorithm().equals(LbAlgorithm.ROUND_ROBIN) ) { } if( nodes.isEmpty() ) { logger.error("create(): Rackspace requires at least one node assignment"); - throw new CloudException("Rackspace requires at least one node assignment"); + throw new InternalException("Rackspace requires at least one node assignment"); } lb.put("nodes", nodes); - HashMap json = new HashMap(); + Map json = new HashMap<>(); json.put("loadBalancer", lb); NovaMethod method = new NovaMethod(provider); @@ -383,7 +354,7 @@ else if( listeners[0].getAlgorithm().equals(LbAlgorithm.ROUND_ROBIN) ) { if( result == null ) { logger.error("create(): Method executed successfully, but no load balancer was created"); - throw new CloudException("Method executed successfully, but no load balancer was created"); + throw new GeneralCloudException("Method executed successfully, but no load balancer was created", CloudErrorType.GENERAL); } try{ if( result.has("loadBalancer") ) { @@ -394,11 +365,12 @@ else if( listeners[0].getAlgorithm().equals(LbAlgorithm.ROUND_ROBIN) ) { } } logger.error("create(): Method executed successfully, but no load balancer was found in JSON"); - throw new CloudException("Method executed successfully, but no load balancer was found in JSON"); + throw new CommunicationException("Method executed successfully, but no load balancer was found in JSON"); } catch( JSONException e ) { logger.error("create(): Failed to identify a load balancer ID in the cloud response: " + e.getMessage()); - throw new CloudException("Failed to identify a load balancer ID in the cloud response: " + e.getMessage()); + throw new CommunicationException("Failed to identify a load balancer ID in the cloud response: " + e.getMessage(), e); + } } finally { @@ -406,14 +378,6 @@ else if( listeners[0].getAlgorithm().equals(LbAlgorithm.ROUND_ROBIN) ) { } } - public @Nonnull Iterable listSupportedEndpointTypes() throws CloudException, InternalException { - ArrayList types = new ArrayList(); - - types.add(LbEndpointType.IP); - types.add(LbEndpointType.VM); - return types; - } - private String matchProtocol(int port) throws CloudException, InternalException { NovaMethod method = new NovaMethod(provider); JSONObject ob = method.getResource(SERVICE, RESOURCE, "protocols", false); @@ -435,7 +399,8 @@ private String matchProtocol(int port) throws CloudException, InternalException } } catch( JSONException e ) { - throw new CloudException("Unable to parse protocols from Rackspace: " + e.getMessage()); + throw new CommunicationException("Unable to parse protocols from Rackspace: " + e.getMessage(), e); + } } return "TCP"; @@ -446,13 +411,6 @@ private String matchProtocol(int port) throws CloudException, InternalException public @Nullable LoadBalancer getLoadBalancer(@Nonnull String loadBalancerId) throws CloudException, InternalException { APITrace.begin(provider, "LB.getLoadBalancer"); try { - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - NovaMethod method = new NovaMethod(provider); JSONObject ob = method.getResource(SERVICE, RESOURCE, loadBalancerId, false); @@ -473,7 +431,7 @@ private String matchProtocol(int port) throws CloudException, InternalException } catch( JSONException e ) { logger.error("listLoadBalancers(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for load balancers: " + e.getMessage()); + throw new CommunicationException("Unable to identify expected values in JSON" + e.getMessage(), e); } } finally { @@ -495,13 +453,6 @@ public LoadBalancerCapabilities getCapabilities() throws CloudException, Interna public @Nonnull Iterable listEndpoints(@Nonnull String loadBalancerId) throws CloudException, InternalException { APITrace.begin(provider, "LB.listEndpoints"); try { - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - NovaMethod method = new NovaMethod(provider); JSONObject ob = method.getResource(SERVICE, RESOURCE, loadBalancerId, false); @@ -513,7 +464,7 @@ public LoadBalancerCapabilities getCapabilities() throws CloudException, Interna JSONObject json = ob.getJSONObject("loadBalancer"); if( json.has("nodes") ) { - ArrayList endpoints = new ArrayList(); + List endpoints = new ArrayList<>(); JSONArray arr = json.getJSONArray("nodes"); for( int i=0; i listEndpoints(@Nonnull String loadBalancerId, @Nonnull LbEndpointType type, @Nonnull String ... values) throws CloudException, InternalException { APITrace.begin(provider, "LB.listEndpoints"); try { - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - NovaMethod method = new NovaMethod(provider); JSONObject ob = method.getResource(SERVICE, RESOURCE, loadBalancerId, false); @@ -591,7 +535,7 @@ public LoadBalancerCapabilities getCapabilities() throws CloudException, Interna JSONObject json = ob.getJSONObject("loadBalancer"); if( json.has("nodes") ) { - ArrayList endpoints = new ArrayList(); + List endpoints = new ArrayList<>(); JSONArray arr = json.getJSONArray("nodes"); for( int i=0; i listLoadBalancerStatus() throws CloudException, InternalException { APITrace.begin(provider, "LB.listLoadBalancerStatus"); try { - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(provider); JSONObject ob = method.getResource(SERVICE, RESOURCE, null, false); @@ -689,7 +628,7 @@ else if( node == null && type.equals(LbEndpointType.IP) ) { return Collections.emptyList(); } try { - ArrayList loadBalancers = new ArrayList(); + List loadBalancers = new ArrayList<>(); if( ob.has("loadBalancers") ) { JSONArray lbs = ob.getJSONArray("loadBalancers"); @@ -715,7 +654,7 @@ else if( node == null && type.equals(LbEndpointType.IP) ) { return loadBalancers; } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for load balancers: " + e.getMessage()); + throw new CommunicationException("Missing JSON elements for loadbalancers" + e.getMessage(), e); } } finally { @@ -732,17 +671,11 @@ public boolean isSubscribed() throws CloudException, InternalException { public @Nonnull Iterable listLoadBalancers() throws CloudException, InternalException { APITrace.begin(provider, "LB.listLoadBalancers"); try { - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } NovaMethod method = new NovaMethod(provider); JSONObject ob = method.getResource(SERVICE, RESOURCE, null, false); try { - ArrayList loadBalancers = new ArrayList(); + List loadBalancers = new ArrayList<>(); if( ob.has("loadBalancers") ) { JSONArray lbs = ob.getJSONArray("loadBalancers"); @@ -771,7 +704,7 @@ public boolean isSubscribed() throws CloudException, InternalException { } catch( JSONException e ) { logger.error("listLoadBalancers(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for load balancers: " + e.getMessage()); + throw new CommunicationException("Unable to identify expected values in JSON" + e.getMessage(), e); } } finally { @@ -834,7 +767,7 @@ static private class Node { public @Nonnull Collection getNodes(@Nonnull String loadBalancerId) throws CloudException, InternalException { APITrace.begin(provider, "LB.getNodes"); try { - ArrayList nodes = new ArrayList(); + List nodes = new ArrayList<>(); NovaMethod method = new NovaMethod(provider); JSONObject response = method.getResource(SERVICE, RESOURCE, loadBalancerId + "/nodes", false); @@ -852,7 +785,7 @@ static private class Node { } } catch( JSONException e ) { - throw new CloudException("Unable to read nodes: " + e.getMessage()); + throw new CommunicationException("Unable to read nodes: " + e.getMessage(), e); } } return nodes; @@ -942,23 +875,17 @@ public void removeIPEndpoints(@Nonnull String fromLoadBalancerId, @Nonnull Strin LoadBalancer lb = getLoadBalancer(fromLoadBalancerId); if( lb == null || LoadBalancerState.TERMINATED.equals(lb.getCurrentState()) ) { - throw new CloudException("No such load balancer: " + fromLoadBalancerId); + throw new ResourceNotFoundException("No such load balancer: " + fromLoadBalancerId); } while( LoadBalancerState.PENDING.equals(lb.getCurrentState()) ) { try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } lb = getLoadBalancer(fromLoadBalancerId); if( lb == null || LoadBalancerState.TERMINATED.equals(lb.getCurrentState()) ) { - throw new CloudException("No such load balancer: " + fromLoadBalancerId); + throw new ResourceNotFoundException("No such load balancer: " + fromLoadBalancerId); } } - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - throw new InternalException("No context exists for this request"); - } - Collection nodeIds = mapIPs(fromLoadBalancerId, addresses); if( nodeIds.size() < 1 ) { @@ -989,24 +916,18 @@ public void removeServers(@Nonnull String fromLoadBalancerId, @Nonnull String... LoadBalancer lb = getLoadBalancer(fromLoadBalancerId); if( lb == null || LoadBalancerState.TERMINATED.equals(lb.getCurrentState()) ) { - throw new CloudException("No such load balancer: " + fromLoadBalancerId); + throw new ResourceNotFoundException("No such load balancer: " + fromLoadBalancerId); } while( LoadBalancerState.PENDING.equals(lb.getCurrentState()) ) { try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } lb = getLoadBalancer(fromLoadBalancerId); if( lb == null || LoadBalancerState.TERMINATED.equals(lb.getCurrentState()) ) { - throw new CloudException("No such load balancer: " + fromLoadBalancerId); + throw new ResourceNotFoundException("No such load balancer: " + fromLoadBalancerId); } } - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - throw new InternalException("No context exists for this request"); - } - - Collection nodeIds = mapNodes(ctx, fromLoadBalancerId, serverIdsToRemove); + Collection nodeIds = mapNodes(getContext(), fromLoadBalancerId, serverIdsToRemove); if( nodeIds.size() < 1 ) { return; @@ -1045,7 +966,7 @@ public void removeServers(@Nonnull String fromLoadBalancerId, @Nonnull String... return null; } if( regionId == null ) { - throw new CloudException("No region was set for this request"); + throw new InternalException("No region was set for this request"); } if( name == null ) { name = id; @@ -1091,7 +1012,7 @@ else if( s.equalsIgnoreCase("pending_delete") || s.equalsIgnoreCase("deleted") ) if( address == null ) { return null; } - ArrayList nodes = new ArrayList(); + List nodes = new ArrayList<>(); int privatePort = -1; if( json.has("nodes") ) { @@ -1186,7 +1107,7 @@ else if( a.equals("least_connections") ) { return lb; } catch( JSONException e ) { - throw new CloudException(e); + throw new CommunicationException("Unable to parse response: " + e.getMessage(), e); } } diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypair.java b/src/main/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypair.java index fa2d419..d594fa3 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypair.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypair.java @@ -21,15 +21,11 @@ import org.apache.http.HttpStatus; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.Requirement; +import org.dasein.cloud.*; +import org.dasein.cloud.identity.AbstractShellKeySupport; import org.dasein.cloud.identity.SSHKeypair; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.identity.ShellKeyCapabilities; -import org.dasein.cloud.identity.ShellKeySupport; import org.dasein.cloud.openstack.nova.os.NovaException; import org.dasein.cloud.openstack.nova.os.NovaMethod; import org.dasein.cloud.openstack.nova.os.NovaOpenStack; @@ -42,10 +38,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Locale; +import java.util.*; /** * OpenStack Nova SSH keypairs @@ -54,31 +47,24 @@ * @version 2011.10 * @version 2012.04.1 Added some intelligence around features Rackspace does not support */ -public class NovaKeypair implements ShellKeySupport { +public class NovaKeypair extends AbstractShellKeySupport { static private final Logger logger = NovaOpenStack.getLogger(NovaKeypair.class, "std"); - private NovaOpenStack provider; private transient volatile NovaKeypairCapabilities capabilities; - NovaKeypair(@Nonnull NovaOpenStack cloud) { provider = cloud; } + NovaKeypair(@Nonnull NovaOpenStack cloud) { super(cloud); } private @Nonnull String getTenantId() throws CloudException, InternalException { - return provider.getContext().getAccountNumber(); + return getContext().getAccountNumber(); } @Override public @Nonnull SSHKeypair createKeypair(@Nonnull String name) throws InternalException, CloudException { - APITrace.begin(provider, "Keypair.createKeypair"); + APITrace.begin(getProvider(), "Keypair.createKeypair"); try { - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - HashMap wrapper = new HashMap(); - HashMap json = new HashMap(); - NovaMethod method = new NovaMethod(provider); + Map wrapper = new HashMap<>(); + Map json = new HashMap<>(); + NovaMethod method = new NovaMethod(getProvider()); json.put("name", name); wrapper.put("keypair", json); @@ -88,23 +74,20 @@ public class NovaKeypair implements ShellKeySupport { try { JSONObject ob = result.getJSONObject("keypair"); - SSHKeypair kp = toKeypair(ctx, ob); + SSHKeypair kp = toKeypair(ob); if( kp == null ) { - throw new CloudException("No matching keypair was generated from " + ob.toString()); + throw new CommunicationException("No matching keypair was generated from " + ob.toString()); } return kp; } catch( JSONException e ) { logger.error("createKeypair(): Unable to understand create response: " + e.getMessage()); - if( logger.isTraceEnabled() ) { - e.printStackTrace(); - } - throw new CloudException(e); + throw new CommunicationException("Invalid response", e); } } logger.error("createKeypair(): No keypair was created by the create attempt, and no error was returned"); - throw new CloudException("No keypair was created"); + throw new GeneralCloudException("No keypair was created", CloudErrorType.GENERAL); } finally { @@ -114,15 +97,9 @@ public class NovaKeypair implements ShellKeySupport { @Override public void deleteKeypair(@Nonnull String keypairId) throws InternalException, CloudException { - APITrace.begin(provider, "Keypair.deleteKeypair"); + APITrace.begin(getProvider(), "Keypair.deleteKeypair"); try { - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - NovaMethod method = new NovaMethod(provider); + NovaMethod method = new NovaMethod(getProvider()); long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR; do { @@ -146,7 +123,7 @@ public void deleteKeypair(@Nonnull String keypairId) throws InternalException, C @Override public @Nullable String getFingerprint(@Nonnull String keypairId) throws InternalException, CloudException { - APITrace.begin(provider, "Keypair.getFingerprint"); + APITrace.begin(getProvider(), "Keypair.getFingerprint"); try { SSHKeypair kp = getKeypair(keypairId); @@ -157,23 +134,11 @@ public void deleteKeypair(@Nonnull String keypairId) throws InternalException, C } } - @Override - @Deprecated - public Requirement getKeyImportSupport() throws CloudException, InternalException { - return Requirement.OPTIONAL; - } - @Override public @Nullable SSHKeypair getKeypair(@Nonnull String keypairId) throws InternalException, CloudException { - APITrace.begin(provider, "Keypair.getKeypair"); + APITrace.begin(getProvider(), "Keypair.getKeypair"); try { - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - NovaMethod method = new NovaMethod(provider); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers("/os-keypairs", null, false); try { @@ -187,7 +152,7 @@ public Requirement getKeyImportSupport() throws CloudException, InternalExceptio if( json.has("keypair") ) { JSONObject kp = json.getJSONObject("keypair"); - SSHKeypair k = toKeypair(ctx, kp); + SSHKeypair k = toKeypair(kp); if( k != null && keypairId.equals(k.getProviderKeypairId()) ) { return k; @@ -196,7 +161,7 @@ public Requirement getKeyImportSupport() throws CloudException, InternalExceptio } catch( JSONException e ) { logger.error("Invalid JSON from cloud: " + e.getMessage()); - throw new CloudException("Invalid JSON from cloud: " + e.getMessage()); + throw new CommunicationException("Invalid JSON from cloud: " + e.getMessage(), e); } } } @@ -204,8 +169,7 @@ public Requirement getKeyImportSupport() throws CloudException, InternalExceptio } catch( JSONException e ) { logger.error("list(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for keypair in " + ob.toString()); + throw new CommunicationException("Missing JSON element for keypair in " + ob.toString(), e); } } finally { @@ -222,24 +186,18 @@ public Requirement getKeyImportSupport() throws CloudException, InternalExceptio @Override public @Nonnull ShellKeyCapabilities getCapabilities() throws CloudException, InternalException { if( capabilities == null ) { - capabilities = new NovaKeypairCapabilities(provider); + capabilities = new NovaKeypairCapabilities(getProvider()); } return capabilities; } @Override public @Nonnull SSHKeypair importKeypair(@Nonnull String name, @Nonnull String publicKey) throws InternalException, CloudException { - APITrace.begin(provider, "Keypair.importKeypair"); + APITrace.begin(getProvider(), "Keypair.importKeypair"); try { - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - HashMap wrapper = new HashMap(); - HashMap json = new HashMap(); - NovaMethod method = new NovaMethod(provider); + Map wrapper = new HashMap<>(); + Map json = new HashMap<>(); + NovaMethod method = new NovaMethod(getProvider()); json.put("name", name); json.put("public_key", publicKey); @@ -250,21 +208,20 @@ public Requirement getKeyImportSupport() throws CloudException, InternalExceptio try { JSONObject ob = result.getJSONObject("keypair"); - SSHKeypair kp = toKeypair(ctx, ob); + SSHKeypair kp = toKeypair(ob); if( kp == null ) { - throw new CloudException("No matching keypair was generated from " + ob.toString()); + throw new CommunicationException("No matching keypair was generated from " + ob.toString()); } return kp; } catch( JSONException e ) { logger.error("importKeypair(): Unable to understand create response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Invalid response", e); } } logger.error("importKeypair(): No keypair was created by the create attempt, and no error was returned"); - throw new CloudException("No keypair was created"); + throw new GeneralCloudException("No keypair was created", CloudErrorType.GENERAL); } finally { @@ -273,9 +230,9 @@ public Requirement getKeyImportSupport() throws CloudException, InternalExceptio } private boolean verifySupport() throws InternalException, CloudException { - APITrace.begin(provider, "Keypair.verifySupport"); + APITrace.begin(getProvider(), "Keypair.verifySupport"); try { - NovaMethod method = new NovaMethod(provider); + NovaMethod method = new NovaMethod(getProvider()); try { method.getServers("/os-keypairs", null, false); @@ -295,9 +252,9 @@ private boolean verifySupport() throws InternalException, CloudException { @Override public boolean isSubscribed() throws InternalException, CloudException { - APITrace.begin(provider, "Keypair.isSubscribed"); + APITrace.begin(getProvider(), "Keypair.isSubscribed"); try { - return (provider.getComputeServices().getVirtualMachineSupport().isSubscribed() && verifySupport()); + return (getProvider().getComputeServices().getVirtualMachineSupport().isSubscribed() && verifySupport()); } finally { APITrace.end(); @@ -306,17 +263,11 @@ public boolean isSubscribed() throws InternalException, CloudException { @Override public @Nonnull Collection list() throws InternalException, CloudException { - APITrace.begin(provider, "Keypair.list"); + APITrace.begin(getProvider(), "Keypair.list"); try { - ProviderContext ctx = provider.getContext(); - - if( ctx == null ) { - logger.error("No context exists for this request"); - throw new InternalException("No context exists for this request"); - } - NovaMethod method = new NovaMethod(provider); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers("/os-keypairs", null, false); - ArrayList keypairs = new ArrayList(); + List keypairs = new ArrayList<>(); try { if( ob != null && ob.has("keypairs") ) { @@ -329,20 +280,19 @@ public boolean isSubscribed() throws InternalException, CloudException { if( json.has("keypair") ) { JSONObject kp = json.getJSONObject("keypair"); - keypairs.add(toKeypair(ctx, kp)); + keypairs.add(toKeypair(kp)); } } catch( JSONException e ) { logger.error("Invalid JSON from cloud: " + e.getMessage()); - throw new CloudException("Invalid JSON from cloud: " + e.getMessage()); + throw new CommunicationException("Invalid JSON from cloud: " + e.getMessage(), e); } } } } catch( JSONException e ) { logger.error("list(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for keypair in " + ob.toString()); + throw new CommunicationException("Missing JSON element for keypair in " + ob.toString(), e); } return keypairs; } @@ -356,7 +306,7 @@ public boolean isSubscribed() throws InternalException, CloudException { return new String[0]; } - private @Nullable SSHKeypair toKeypair(@Nonnull ProviderContext ctx, @Nullable JSONObject json) throws InternalException, CloudException { + private @Nullable SSHKeypair toKeypair(@Nullable JSONObject json) throws InternalException, CloudException { if( json == null ) { return null; } @@ -382,16 +332,14 @@ public boolean isSubscribed() throws InternalException, CloudException { kp.setName(name); kp.setProviderKeypairId(name); kp.setProviderOwnerId(getTenantId()); - String regionId = ctx.getRegionId(); + String regionId = getContext().getRegionId(); kp.setProviderRegionId(regionId == null ? "" : regionId); return kp; } catch( UnsupportedEncodingException e ) { - e.printStackTrace(); throw new InternalException(e); } catch( JSONException e ) { - e.printStackTrace(); throw new InternalException(e); } } diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java index 2e18eef..1c26ef2 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java @@ -3,10 +3,7 @@ import org.apache.commons.net.util.SubnetUtils; import org.apache.http.HttpStatus; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ResourceStatus; -import org.dasein.cloud.VisibleScope; +import org.dasein.cloud.*; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.network.*; import org.dasein.cloud.openstack.nova.os.NovaException; @@ -132,7 +129,7 @@ public boolean isSubscribed() throws CloudException, InternalException { if( result == null ) { logger.error("create(): Method executed successfully, but no load balancer was created"); - throw new CloudException("Method executed successfully, but no load balancer was created"); + throw new GeneralCloudException("No loadbalancer was created", CloudErrorType.GENERAL); } try{ if( result.has("pool") ) { @@ -144,7 +141,8 @@ public boolean isSubscribed() throws CloudException, InternalException { } catch ( Throwable e ) { getMethod().deleteNetworks(getLoadBalancersResource(), lbId); - throw new CloudException(e); + throw new GeneralCloudException("No listener was created", CloudErrorType.GENERAL); + } if( options.getEndpoints() != null ) { for( LoadBalancerEndpoint endpoint : options.getEndpoints() ) { @@ -158,11 +156,12 @@ public boolean isSubscribed() throws CloudException, InternalException { } } logger.error("create(): Method executed successfully, but no load balancer was found in JSON"); - throw new CloudException("Method executed successfully, but no load balancer was found in JSON"); + throw new ResourceNotFoundException("Method executed successfully, but no load balancer was found in JSON"); } catch( JSONException e ) { logger.error("create(): Failed to identify a load balancer ID in the cloud response: " + e.getMessage()); - throw new CloudException("Failed to identify a load balancer ID in the cloud response: " + e.getMessage()); + throw new CommunicationException("Failed to identify a load balancer ID in the cloud response: " + e.getMessage(), e); + } } finally { @@ -185,7 +184,8 @@ public boolean isSubscribed() throws CloudException, InternalException { } } catch( JSONException e ) { - throw new CloudException("Unable to parse list load balancers response", e); + throw new CommunicationException("Unable to parse list load balancers response" + e.getMessage(), e); + } } return results; @@ -276,7 +276,7 @@ public void removeIPEndpoints(@Nonnull String fromLoadBalancerId, @Nonnull Strin } } catch( JSONException e ) { - e.printStackTrace(); + throw new CommunicationException("Unable to parse response", e); } } } @@ -329,7 +329,8 @@ public void attachHealthCheckToLoadBalancer(@Nonnull String providerLoadBalancer JSONObject result = getMethod().postNetworks(getLoadBalancersResource(), providerLoadBalancerId, new JSONObject(json), "health_monitors"); if( result == null ) { logger.error("create(): Method executed successfully, but no health monitor was attached"); - throw new CloudException("Method executed successfully, but no health monitor was attached"); + throw new GeneralCloudException("Method executed successfully, but no health monitor was attached", CloudErrorType.GENERAL); + } } finally { @@ -355,7 +356,7 @@ public Iterable listLBHealthChecks(@Nullable HealthChec } catch( JSONException e ) { logger.error("Unable to identify expected values in JSON:" + e.getMessage()); - throw new CloudException(e); + throw new CommunicationException("Unable to identify expected values in JSON: " + e.getMessage(), e); } } return healthMonitors; @@ -375,13 +376,15 @@ public LoadBalancerHealthCheck getLoadBalancerHealthCheck(@Nonnull String provid if( result == null ) { logger.error("create(): Method executed successfully, but no health monitor was found"); - throw new CloudException("Method executed successfully, but no health monitor was found"); + throw new GeneralCloudException("Method executed successfully, but no health monitor was found", CloudErrorType.GENERAL); + } try { return toLoadBalancerHealthCheck(result.getJSONObject("health_monitor")); } catch( JSONException e ) { - throw new CloudException("Unable to parse a health check object", e); + throw new CommunicationException("Unable to parse a health check object " + e.getMessage(), e); + } } finally { @@ -457,11 +460,12 @@ protected LoadBalancerHealthCheck createHealthMonitor(@Nonnull List load if( result == null ) { logger.error("create(): Method executed successfully, but no health monitor was created"); - throw new CloudException("Method executed successfully, but no health monitor was created"); + throw new GeneralCloudException("Method executed successfully, but no health monitor was created", CloudErrorType.GENERAL); + } LoadBalancerHealthCheck hc = toLoadBalancerHealthCheck(result.getJSONObject("health_monitor")); if( hc == null ) { - throw new CloudException("Unable to create loadbalancer health check"); + throw new GeneralCloudException("Unable to create loadbalancer health check" , CloudErrorType.GENERAL); } for( String lbId : loadbalancerIds ) { attachHealthCheckToLoadBalancer(lbId, hc.getProviderLBHealthCheckId()); @@ -469,7 +473,8 @@ protected LoadBalancerHealthCheck createHealthMonitor(@Nonnull List load return hc; } catch( JSONException e ) { - throw new CloudException("Unable to parse create health monitor response", e); + throw new CommunicationException("Unable to parse create health monitor response" + e.getMessage(), e); + } finally { APITrace.end(); @@ -564,7 +569,8 @@ protected void createListener(@Nonnull String lbId, String subnetId, @Nonnull Lb if( result == null ) { logger.error("create(): Method executed successfully, but no listener was created"); - throw new CloudException("Method executed successfully, but no listener was created"); + throw new GeneralCloudException("No listener was created", CloudErrorType.GENERAL); + } } finally { @@ -591,7 +597,8 @@ protected void createMember(@Nonnull String lbId, String address, int privatePor JSONObject result = getMethod().postNetworks(getMembersResource(), null, new JSONObject(json), false); if( result == null ) { logger.error("create(): Method executed successfully, but no load balancer member was created"); - throw new CloudException("Method executed successfully, but no load balancer member was created"); + throw new GeneralCloudException("Method executed successfully, but no load balancer member was created", CloudErrorType.GENERAL); + } } finally { @@ -621,7 +628,7 @@ protected List findAllVips(@Nullable String loadBalancerId) throws C } catch( JSONException e ) { logger.error("Unable to understand listVips response: " + e.getMessage()); - throw new CloudException(e); + throw new CommunicationException("Unable to understand listVips response: " + e.getMessage(), e); } } return listeners; @@ -650,7 +657,7 @@ protected List findAllMembers(@Nullable String loadBalancerId) throw } catch( JSONException e ) { logger.error("Unable to understand listMembers response: " + e.getMessage()); - throw new CloudException(e); + throw new CommunicationException("Unable to understand listMembers response: " + e.getMessage(), e); } } return members; @@ -685,7 +692,7 @@ protected List findLoadBalancers(@Nullable String loadBalancerId) } catch( JSONException e ) { logger.error("Unable to understand listPools response: " + e.getMessage()); - throw new CloudException(e); + throw new GeneralCloudException("Unable to understand listPools response: ", CloudErrorType.GENERAL); } } else if( result != null && result.has("pool")) { @@ -694,7 +701,7 @@ else if( result != null && result.has("pool")) { } catch( JSONException e ) { logger.error("Unable to understand getPool response: " + e.getMessage()); - throw new CloudException(e); + throw new CommunicationException("Unable to understand getPool response: " + e.getMessage(), e); } } @@ -807,7 +814,9 @@ private LoadBalancerEndpoint toLoadBalancerEnpoint(JSONObject member) throws Clo "ACTIVE".equalsIgnoreCase(member.getString("status")) ? LbEndpointState.ACTIVE : LbEndpointState.INACTIVE); } catch( JSONException e ) { - throw new CloudException("Unable to parse load balancer member", e); + throw new CommunicationException("Unable to parse load balancer member" + e.getMessage(), e); + + } } diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaFloatingIP.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaFloatingIP.java index 8b3e6f0..ef7f84d 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaFloatingIP.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaFloatingIP.java @@ -21,13 +21,7 @@ import org.apache.http.HttpStatus; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.OperationNotSupportedException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.Requirement; -import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.*; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.network.AbstractIpAddressSupport; import org.dasein.cloud.network.AddressType; @@ -93,7 +87,7 @@ public void assign(@Nonnull String addressId, @Nonnull String serverId) throws I IpAddress addr = getIpAddress(addressId); if( addr == null ) { - throw new CloudException("No such IP address: " + addressId); + throw new ResourceNotFoundException("No such IP address: " + addressId); } //action.put("server", serverId); action.put("address",addr.getRawAddress().getIpAddress()); @@ -119,6 +113,7 @@ public void assignToNetworkInterface(@Nonnull String addressId, @Nonnull String } private transient volatile FloatingIPCapabilities capabilities; + @Nonnull @Override public IPAddressCapabilities getCapabilities() throws CloudException, InternalException { @@ -150,7 +145,7 @@ public IPAddressCapabilities getCapabilities() throws CloudException, InternalEx } catch( JSONException e ) { logger.error("getIpAddress(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for IP address"); + throw new CommunicationException("Missing JSON element for IP address", e); } return null; } @@ -159,51 +154,6 @@ public IPAddressCapabilities getCapabilities() throws CloudException, InternalEx } } - @Override - public @Nonnull String getProviderTermForIpAddress(@Nonnull Locale locale) { - return "floating IP"; - } - - @Override - public @Nonnull Requirement identifyVlanForVlanIPRequirement() throws CloudException, InternalException { - return Requirement.NONE; - } - - @Override - public boolean isAssigned(@Nonnull AddressType type) { - return (type.equals(AddressType.PUBLIC) || type.equals(AddressType.PRIVATE)); - } - - @Override - public boolean isAssigned(@Nonnull IPVersion version) throws CloudException, InternalException { - return getVersions().contains(version); - } - - @Override - public boolean isAssignablePostLaunch(@Nonnull IPVersion version) throws CloudException, InternalException { - return getVersions().contains(version); - } - - @Override - public boolean isForwarding() { - return false; - } - - @Override - public boolean isForwarding(IPVersion version) throws CloudException, InternalException { - return false; - } - - @Override - public boolean isRequestable(@Nonnull AddressType type) { - return (type.equals(AddressType.PUBLIC) || type.equals(AddressType.PRIVATE)); - } - - @Override - public boolean isRequestable(@Nonnull IPVersion version) throws CloudException, InternalException { - return getVersions().contains(version); - } - private boolean verifySupport() throws InternalException, CloudException { APITrace.begin(getProvider(), "IpAddress.verifySupport"); try { @@ -243,16 +193,6 @@ public boolean isSubscribed() throws CloudException, InternalException { } } - @Override - public @Nonnull Iterable listPrivateIpPool(boolean unassignedOnly) throws InternalException, CloudException { - return Collections.emptyList(); - } - - @Override - public @Nonnull Iterable listPublicIpPool(boolean unassignedOnly) throws InternalException, CloudException { - return listIpPool(IPVersion.IPV4, unassignedOnly); - } - @Override public @Nonnull Iterable listIpPool(@Nonnull IPVersion version, boolean unassignedOnly) throws InternalException, CloudException { APITrace.begin(getProvider(), "IpAddress.listIpPool"); @@ -363,15 +303,14 @@ public Iterable call() throws CloudException, InternalException { } catch( JSONException e ) { logger.error("Invalid JSON from cloud: " + e.getMessage()); - throw new CloudException("Invalid JSON from cloud: " + e.getMessage()); + throw new CommunicationException("Invalid JSON from cloud: " + e.getMessage(), e); } } } } catch( JSONException e ) { logger.error("list(): Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for floating IP in " + ob.toString()); + throw new CommunicationException("Missing JSON element for floating IP in " + ob.toString(), e); } return addresses; } @@ -386,7 +325,7 @@ public Iterable call() throws CloudException, InternalException { } NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers(getEndpoint(), null, false); - ArrayList addresses = new ArrayList(); + List addresses = new ArrayList(); try { if( ob != null && ob.has("floating_ips") ) { @@ -403,13 +342,13 @@ public Iterable call() throws CloudException, InternalException { } } catch( JSONException e ) { - throw new CloudException("Invalid JSON from cloud: " + e.getMessage()); + throw new CommunicationException("Invalid JSON from cloud: " + e.getMessage(), e); } } } } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for floating IP in " + ob.toString()); + throw new CommunicationException("Missing JSON element for floating IP in " + ob.toString(), e); } return addresses; } @@ -476,17 +415,17 @@ public void releaseFromPool(@Nonnull String addressId) throws InternalException, public void releaseFromServer(@Nonnull String addressId) throws InternalException, CloudException { APITrace.begin(getProvider(), "IpAddress.releaseFromServer"); try { - HashMap json = new HashMap(); - HashMap action = new HashMap(); + Map json = new HashMap(); + Map action = new HashMap(); IpAddress addr = getIpAddress(addressId); if( addr == null ) { - throw new CloudException("No such IP address: " + addressId); + throw new ResourceNotFoundException("No such IP address: " + addressId); } String serverId = addr.getServerId(); if( serverId == null ) { - throw new CloudException("IP address " + addressId + " is not attached to a server"); + throw new InvalidStateException("IP address " + addressId + " is not attached to a server"); } //action.put("server", serverId); action.put("address", addr.getRawAddress().getIpAddress()); @@ -504,8 +443,8 @@ public void releaseFromServer(@Nonnull String addressId) throws InternalExceptio private Iterable listPools() throws CloudException, InternalException { NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers("/os-floating-ip-pools", null, false); - ArrayList pools = new ArrayList(); - ArrayList tmp = new ArrayList(); + List pools = new ArrayList(); + List tmp = new ArrayList(); try { @@ -530,19 +469,11 @@ private Iterable listPools() throws CloudException, InternalException { } } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for IP address"); + throw new CommunicationException("Missing JSON element for IP address", e); } return pools; } - @Override - public @Nonnull String request(@Nonnull AddressType typeOfAddress) throws InternalException, CloudException { - if( typeOfAddress.equals(AddressType.PRIVATE) ) { - throw new OperationNotSupportedException("Requesting private IP addresses is not supported by OpenStack"); - } - return request(IPVersion.IPV4); - } - @Override public @Nonnull String request(@Nonnull IPVersion version) throws InternalException, CloudException { try { @@ -590,14 +521,11 @@ private Iterable listPools() throws CloudException, InternalException { } catch( JSONException e ) { logger.error("create(): Unable to understand create response: " + e.getMessage()); - if( logger.isTraceEnabled() ) { - e.printStackTrace(); - } - throw new CloudException(e); + throw new CommunicationException("Invalid response", e); } } logger.error("create(): No IP address was created by the create attempt, and no error was returned"); - throw new CloudException("No IP address was created"); + throw new GeneralCloudException("No IP address was created", CloudErrorType.GENERAL); } finally { @@ -620,11 +548,6 @@ public void stopForward(@Nonnull String ruleId) throws InternalException, CloudE throw new OperationNotSupportedException("Forwarding not supported"); } - @Override - public boolean supportsVLANAddresses(@Nonnull IPVersion ofVersion) throws InternalException, CloudException { - return false; - } - private IpAddress toIP(JSONObject json) throws JSONException, InternalException { if(json == null ) { return null; diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java index b991ddd..64cba79 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java @@ -21,12 +21,7 @@ import org.apache.http.HttpStatus; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudErrorType; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.OperationNotSupportedException; -import org.dasein.cloud.Requirement; -import org.dasein.cloud.ResourceStatus; +import org.dasein.cloud.*; import org.dasein.cloud.network.AbstractFirewallSupport; import org.dasein.cloud.network.Direction; import org.dasein.cloud.network.Firewall; @@ -49,11 +44,7 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; +import java.util.*; /** * Support for OpenStack security groups. @@ -63,7 +54,7 @@ * @version 2012.04.1 Added some intelligence around features Rackspace does not support * @version 2013.04 Added API tracing */ -public class NovaSecurityGroup extends AbstractFirewallSupport { +public class NovaSecurityGroup extends AbstractFirewallSupport { static private final Logger logger = NovaOpenStack.getLogger(NovaSecurityGroup.class, "std"); NovaSecurityGroup(NovaOpenStack cloud) { @@ -71,7 +62,7 @@ public class NovaSecurityGroup extends AbstractFirewallSupport { } private @Nonnull String getTenantId() throws CloudException, InternalException { - return ((NovaOpenStack)getProvider()).getContext().getAccountNumber(); + return getContext().getAccountNumber(); } @Override @@ -85,9 +76,9 @@ public class NovaSecurityGroup extends AbstractFirewallSupport { throw new OperationNotSupportedException(getProvider().getCloudName() + " dies not support deny rules.") ; } - HashMap wrapper = new HashMap(); - HashMap json = new HashMap(); - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + Map wrapper = new HashMap(); + Map json = new HashMap(); + NovaMethod method = new NovaMethod(getProvider()); json.put("ip_protocol", protocol.name().toLowerCase()); json.put("from_port", beginPort); @@ -109,7 +100,7 @@ public class NovaSecurityGroup extends AbstractFirewallSupport { Firewall targetGroup = getFirewall(sourceEndpoint.getProviderFirewallId()); if( targetGroup == null ) { - throw new CloudException("No such source endpoint firewall: " + sourceEndpoint.getProviderFirewallId()); + throw new ResourceNotFoundException("No such source endpoint firewall: " + sourceEndpoint.getProviderFirewallId()); } json.put("group_id", targetGroup.getProviderFirewallId()); @@ -128,11 +119,11 @@ public class NovaSecurityGroup extends AbstractFirewallSupport { } catch( JSONException e ) { logger.error("Invalid JSON returned from rule creation: " + e.getMessage()); - throw new CloudException(e); + throw new CommunicationException("Invalid JSON returned from rule creation: " + e.getMessage(), e); } } logger.error("authorize(): No firewall rule was created by the create attempt, and no error was returned"); - throw new CloudException("No firewall rule was created"); + throw new GeneralCloudException("No firewall rule was created", CloudErrorType.GENERAL); } finally { APITrace.end(); @@ -146,8 +137,8 @@ public class NovaSecurityGroup extends AbstractFirewallSupport { if( options.getProviderVlanId() != null ) { throw new OperationNotSupportedException("Creating IP addresses in VLANs is not supported"); } - HashMap wrapper = new HashMap(); - HashMap json = new HashMap(); + Map wrapper = new HashMap(); + Map json = new HashMap(); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); json.put("name", options.getName()); @@ -170,12 +161,11 @@ public class NovaSecurityGroup extends AbstractFirewallSupport { } catch( JSONException e ) { logger.error("create(): Unable to understand create response: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new CommunicationException("Invalid response", e); } } logger.error("create(): No firewall was created by the create attempt, and no error was returned"); - throw new CloudException("No firewall was created"); + throw new GeneralCloudException("No firewall was created", CloudErrorType.GENERAL); } finally { @@ -187,7 +177,7 @@ public class NovaSecurityGroup extends AbstractFirewallSupport { public void delete(@Nonnull String firewallId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.delete"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR; do { @@ -214,7 +204,7 @@ public void delete(@Nonnull String firewallId) throws InternalException, CloudEx @Override public FirewallCapabilities getCapabilities() throws CloudException, InternalException { if( capabilities == null ) { - capabilities = new SecurityGroupCapabilities((NovaOpenStack)getProvider()); + capabilities = new SecurityGroupCapabilities(getProvider()); } return capabilities; } @@ -223,7 +213,7 @@ public FirewallCapabilities getCapabilities() throws CloudException, InternalExc public @Nullable Firewall getFirewall(@Nonnull String firewallId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.getFirewall"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers("/os-security-groups", firewallId, false); if( ob == null ) { @@ -241,7 +231,7 @@ public FirewallCapabilities getCapabilities() throws CloudException, InternalExc } catch( JSONException e ) { logger.error("getRule(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security group"); + throw new CommunicationException("Missing JSON element for security group", e); } return null; } @@ -260,7 +250,7 @@ public FirewallCapabilities getCapabilities() throws CloudException, InternalExc APITrace.begin(getProvider(), "Firewall.getRules"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers("/os-security-groups", firewallId, false); if( ob == null ) { @@ -373,7 +363,7 @@ else if( endPort == -1 && startPort != -1 ) { } catch( JSONException e ) { logger.error("getRules(): Unable to identify expected values in JSON: " + e.getMessage()); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups"); + throw new CommunicationException("Missing JSON element for security groups"); } return Collections.emptyList(); } @@ -385,7 +375,7 @@ else if( endPort == -1 && startPort != -1 ) { private boolean verifySupport() throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.verifySupport"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); try { method.getServers("/os-security-groups", null, false); @@ -408,10 +398,11 @@ private boolean verifySupport() throws InternalException, CloudException { public boolean isSubscribed() throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.isSubscribed"); try { - if( ((NovaOpenStack)getProvider()).getMajorVersion() > 1 && ((NovaOpenStack)getProvider()).getComputeServices().getVirtualMachineSupport().isSubscribed() ) { + if( getProvider().getMajorVersion() > 1 && getProvider().getComputeServices().getVirtualMachineSupport().isSubscribed() ) { return verifySupport(); } - if( ((NovaOpenStack)getProvider()).getMajorVersion() == 1 && ((NovaOpenStack)getProvider()).getMinorVersion() >= 1 && ((NovaOpenStack)getProvider()).getComputeServices().getVirtualMachineSupport().isSubscribed() ) { + if( getProvider().getMajorVersion() == 1 && getProvider().getMinorVersion() >= 1 + && getProvider().getComputeServices().getVirtualMachineSupport().isSubscribed() ) { return verifySupport(); } return false; @@ -425,9 +416,9 @@ public boolean isSubscribed() throws InternalException, CloudException { public @Nonnull Collection list() throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.list"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers("/os-security-groups", null, false); - ArrayList firewalls = new ArrayList(); + List firewalls = new ArrayList(); try { if( ob != null && ob.has("security_groups") ) { @@ -444,8 +435,8 @@ public boolean isSubscribed() throws InternalException, CloudException { } } catch( JSONException e ) { - logger.error("list(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups in " + ob.toString()); + logger.error("list(): Unable to identify expected values in JSON: " + e.getMessage()); + throw new CommunicationException("Missing JSON element for security groups in " + ob.toString(), e); } return firewalls; } @@ -458,9 +449,9 @@ public boolean isSubscribed() throws InternalException, CloudException { public @Nonnull Iterable listFirewallStatus() throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.listFirewallStatus"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers("/os-security-groups", null, false); - ArrayList firewalls = new ArrayList(); + List firewalls = new ArrayList(); try { if( ob != null && ob.has("security_groups") ) { @@ -477,13 +468,13 @@ public boolean isSubscribed() throws InternalException, CloudException { } } catch( JSONException e ) { - throw new CloudException("Invalid JSON from cloud: " + e.getMessage()); + throw new CommunicationException("Invalid JSON from cloud: " + e.getMessage(), e); } } } } catch( JSONException e ) { - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups in " + ob.toString()); + throw new CommunicationException("Missing JSON element for security groups in " + ob.toString(), e); } return firewalls; } @@ -492,47 +483,11 @@ public boolean isSubscribed() throws InternalException, CloudException { } } - @Override - public @Nonnull Iterable listSupportedDestinationTypes(boolean inVlan) throws InternalException, CloudException { - if( inVlan ) { - return Collections.emptyList(); - } - return Collections.singletonList(RuleTargetType.GLOBAL); - } - - @Override - public @Nonnull Iterable listSupportedDirections(boolean inVlan) throws InternalException, CloudException { - if( inVlan ) { - return Collections.emptyList(); - } - return Collections.singletonList(Direction.INGRESS); - } - - @Override - public @Nonnull Iterable listSupportedPermissions(boolean inVlan) throws InternalException, CloudException { - if( inVlan ) { - return Collections.emptyList(); - } - return Collections.singletonList(Permission.ALLOW); - } - - @Override - public @Nonnull Iterable listSupportedSourceTypes(boolean inVlan) throws InternalException, CloudException { - if( inVlan ) { - return Collections.emptyList(); - } - ArrayList list= new ArrayList(); - - list.add(RuleTargetType.CIDR); - list.add(RuleTargetType.GLOBAL); - return list; - } - @Override public void revoke(@Nonnull String providerFirewallRuleId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.revoke"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR; do { @@ -650,7 +605,7 @@ else if( t.getRuleTargetType().equals(RuleTargetType.GLOBAL) && source.equals(t. } } if( targetRule == null ) { - throw new CloudException("No such firewall rule"); + throw new ResourceNotFoundException("No such firewall rule"); } revoke(targetRule.getProviderRuleId()); } @@ -659,11 +614,6 @@ else if( t.getRuleTargetType().equals(RuleTargetType.GLOBAL) && source.equals(t. } } - @Override - public boolean supportsFirewallSources() throws CloudException, InternalException { - return true; - } - private @Nullable Firewall toFirewall(@Nonnull JSONObject json) throws CloudException, InternalException { try { Firewall fw = new Firewall(); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/Quantum.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/Quantum.java index 13ca7e0..2efc98c 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/Quantum.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/Quantum.java @@ -165,9 +165,9 @@ public QuantumType getNetworkType() throws CloudException, InternalException { // check is the id passed in is actually for a network VLAN vlan = getVlan(subnetId); if (vlan != null) { - throw new CloudException("Cannot launch into the network without a subnet"); + throw new InternalException("Cannot launch into the network without a subnet"); } - throw new CloudException("Invalid id no network or subnet found for " + subnetId); + throw new ResourceNotFoundException("Invalid id no network or subnet found for " + subnetId); } Map wrapper = new HashMap(); Map json = new HashMap(); @@ -209,11 +209,11 @@ public QuantumType getNetworkType() throws CloudException, InternalException { } catch( JSONException e ) { logger.error("Unable to understand create response: " + e.getMessage()); - throw new CloudException(e); + throw new CommunicationException("Unable to parse the response", e); } } logger.error("No port was created by the create attempt, and no error was returned"); - throw new CloudException("No port was created"); + throw new GeneralCloudException("No port was created", CloudErrorType.GENERAL); } finally { @@ -243,7 +243,7 @@ public QuantumType getNetworkType() throws CloudException, InternalException { } } catch (JSONException e) { logger.error("Unable to understand listPorts response: " + e.getMessage()); - throw new CloudException(e); + throw new CommunicationException("Unable to understand listPorts response: " + e.getMessage(), e); } return portIds; } @@ -288,7 +288,7 @@ public QuantumType getNetworkType() throws CloudException, InternalException { } } catch (JSONException e) { logger.error("Unable to understand listPorts response: " + e.getMessage()); - throw new CloudException(e); + throw new CommunicationException("Unable to understand listPorts response: " + e.getMessage(), e); } return portIds; } @@ -321,7 +321,7 @@ public QuantumType getNetworkType() throws CloudException, InternalException { } } catch (JSONException e) { logger.error("Unable to understand listPorts response: " + e.getMessage()); - throw new CloudException(e); + throw new CommunicationException("Unable to understand listPorts response: " + e.getMessage(), e); } return portIds; } @@ -342,12 +342,12 @@ public QuantumType getNetworkType() throws CloudException, InternalException { VLAN vlan = getVlan(options.getProviderVlanId()); if( vlan == null ) { - throw new CloudException("No such VLAN: " + options.getProviderVlanId()); + throw new ResourceNotFoundException("No such VLAN: " + options.getProviderVlanId()); } - HashMap wrapper = new HashMap(); - HashMap json = new HashMap(); - HashMap md = new HashMap(); + Map wrapper = new HashMap(); + Map json = new HashMap(); + Map md = new HashMap(); json.put("name", options.getName()); json.put("cidr", options.getCidr()); @@ -385,17 +385,17 @@ else if( versions[0].equals(IPVersion.IPV6) ) { Subnet subnet = toSubnet(result.getJSONObject("subnet"), vlan); if( subnet == null ) { - throw new CloudException("No matching subnet was generated from " + ob.toString()); + throw new CommunicationException("No matching subnet was generated from " + ob.toString()); } return subnet; } catch( JSONException e ) { logger.error("Unable to understand create response: " + e.getMessage()); - throw new CloudException(e); + throw new CommunicationException("Unable to understand create response: " + e.getMessage(), e); } } logger.error("No subnet was created by the create attempt, and no error was returned"); - throw new CloudException("No subnet was created"); + throw new GeneralCloudException("No subnet was created", CloudErrorType.GENERAL); } finally { @@ -447,7 +447,7 @@ else if( versions[0].equals(IPVersion.IPV6) ) { JSONObject ob = result.getJSONObject("network"); VLAN vlan = toVLAN(result.getJSONObject("network")); if( vlan == null ) { - throw new CloudException("No matching network was generated from " + ob.toString()); + throw new CommunicationException("No matching network was generated from " + ob.toString()); } if( getNetworkType().equals(QuantumType.QUANTUM) && cidr != null ) { createSubnet(SubnetCreateOptions.getInstance(vlan.getProviderVlanId(), cidr, name + "-subnet", "Auto-created subnet")); @@ -456,11 +456,11 @@ else if( versions[0].equals(IPVersion.IPV6) ) { } catch( JSONException e ) { logger.error("Unable to understand create response: " + e.getMessage()); - throw new CloudException(e); + throw new CommunicationException("Unable to understand create response: " + e.getMessage(), e); } } logger.error("No VLAN was created by the create attempt, and no error was returned"); - throw new CloudException("No VLAN was created"); + throw new GeneralCloudException("No VLAN was created", CloudErrorType.GENERAL); } finally { @@ -520,22 +520,6 @@ else if( versions[0].equals(IPVersion.IPV6) ) { return type.getSubnetResource(); } - - @Override - public @Nonnull String getProviderTermForNetworkInterface(@Nonnull Locale locale) { - return "network interface"; - } - - @Override - public @Nonnull String getProviderTermForSubnet(@Nonnull Locale locale) { - return "subnet"; - } - - @Override - public @Nonnull String getProviderTermForVlan(@Nonnull Locale locale) { - return "network"; - } - @Override public Subnet getSubnet(@Nonnull String subnetId) throws CloudException, InternalException { APITrace.begin(getProvider(), "VLAN.getSubnet"); @@ -562,8 +546,7 @@ public Subnet getSubnet(@Nonnull String subnetId) throws CloudException, Interna } catch( JSONException e ) { logger.error("Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for subnet in " + ob.toString()); + throw new CommunicationException("Missing JSON element for subnet in " + ob.toString(), e); } return null; } @@ -597,8 +580,7 @@ public VLAN getVlan(@Nonnull String vlanId) throws CloudException, InternalExcep } catch( JSONException e ) { logger.error("Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for networks in " + ob.toString()); + throw new CommunicationException("Missing JSON element for networks in " + ob.toString(), e); } return null; } @@ -607,18 +589,6 @@ public VLAN getVlan(@Nonnull String vlanId) throws CloudException, InternalExcep } } - @Nullable - @Override - public String getAttachedInternetGatewayId(@Nonnull String vlanId) throws CloudException, InternalException { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - @Nullable - @Override - public InternetGateway getInternetGatewayById(@Nonnull String gatewayId) throws CloudException, InternalException { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - @Override public boolean isSubscribed() throws CloudException, InternalException { APITrace.begin(getProvider(), "VLAN.isSubscribed"); @@ -637,12 +607,6 @@ public boolean isSubscribed() throws CloudException, InternalException { } } - @Nonnull - @Override - public Collection listInternetGateways(@Nullable String vlanId) throws CloudException, InternalException { - return Collections.emptyList(); - } - protected @Nonnull ComputeServices getServices() throws CloudException, InternalException { return getProvider().getComputeServices(); } @@ -678,7 +642,7 @@ public Collection listInternetGateways(@Nullable String vlanId) if( !getNetworkType().equals(QuantumType.QUANTUM) ) { return Collections.emptyList(); } - JSONObject ob = null; + JSONObject ob; if (getNetworkType().equals(QuantumType.QUANTUM) ) { ob = getMethod().getNetworks(getSubnetResource(), null, false); @@ -703,8 +667,7 @@ public Collection listInternetGateways(@Nullable String vlanId) } catch( JSONException e ) { logger.error("Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for subnets in " + ob.toString()); + throw new CommunicationException("Missing JSON element for subnets in " + ob.toString(), e); } return subnets; } @@ -717,7 +680,7 @@ public Collection listInternetGateways(@Nullable String vlanId) public @Nonnull Iterable listVlanStatus() throws CloudException, InternalException { APITrace.begin(getProvider(), "VLAN.listVlanStatus"); try { - JSONObject ob = null; + JSONObject ob; if (getNetworkType().equals(QuantumType.QUANTUM) ) { ob = getMethod().getNetworks(getNetworkResource(), null, false); } @@ -746,8 +709,7 @@ public Collection listInternetGateways(@Nullable String vlanId) } catch( JSONException e ) { logger.error("Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for networks in " + ob.toString()); + throw new CommunicationException("Missing JSON element for networks in " + ob.toString(), e); } return networks; } @@ -787,8 +749,7 @@ public Collection listInternetGateways(@Nullable String vlanId) } catch( JSONException e ) { logger.error("Unable to identify expected values in JSON: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for networks in " + ob.toString()); + throw new CommunicationException("Missing JSON element for networks in " + ob.toString(), e); } return networks; } @@ -899,7 +860,7 @@ else if( s.equalsIgnoreCase("build") ) { return new ResourceStatus(id, s); } catch( JSONException e ) { - throw new CloudException("Invalid JSON from cloud: " + e.getMessage()); + throw new CommunicationException("Invalid JSON from cloud: " + e.getMessage(), e); } } @@ -1030,7 +991,7 @@ else if( end == null ) { return subnet; } catch( JSONException e ) { - throw new CloudException("Invalid JSON from cloud: " + e.getMessage()); + throw new CommunicationException("Invalid JSON from cloud: " + e.getMessage(), e); } } @@ -1130,7 +1091,7 @@ else if( n.startsWith("org.dasein.ntp.") && !n.equals("org.dasein.ntp.") && v.ge return v; } catch( JSONException e ) { - throw new CloudException("Invalid JSON from cloud: " + e.getMessage()); + throw new CommunicationException("Invalid JSON from cloud: " + e.getMessage(), e); } } } diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java b/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java index 8079bbe..95ba7c0 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java @@ -31,11 +31,7 @@ import java.util.Map; import org.apache.log4j.Logger; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.OperationNotSupportedException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.Tag; +import org.dasein.cloud.*; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.openstack.nova.os.AuthenticationContext; import org.dasein.cloud.openstack.nova.os.NovaOpenStack; @@ -75,21 +71,6 @@ public BlobStoreCapabilities getCapabilities() throws CloudException, InternalEx return capabilities; } - @Override - public boolean allowsNestedBuckets() throws CloudException, InternalException { - return false; - } - - @Override - public boolean allowsRootObjects() throws CloudException, InternalException { - return false; - } - - @Override - public boolean allowsPublicSharing() throws CloudException, InternalException { - return false; - } - @Override public @Nonnull Blob createBucket(@Nonnull String bucketName, boolean findFreeName) throws InternalException, CloudException { APITrace.begin(getProvider(), "Blob.createBucket"); @@ -97,19 +78,12 @@ public boolean allowsPublicSharing() throws CloudException, InternalException { if( bucketName.contains("/") ) { throw new OperationNotSupportedException("Nested buckets are not supported"); } - ProviderContext ctx = getProvider().getContext(); - - if( ctx == null ) { - throw new InternalException("No context was set for this request"); - } - String regionId = ctx.getRegionId(); + String regionId = getContext().getRegionId(); if( regionId == null ) { throw new InternalException("No region ID was specified for this request"); } - Logger logger = NovaOpenStack.getLogger(SwiftBlobStore.class, "std"); - if( logger.isTraceEnabled() ) { logger.trace("enter - " + SwiftBlobStore.class.getName() + ".createBucket(" + bucketName + "," + findFreeName + ")"); } @@ -117,7 +91,7 @@ public boolean allowsPublicSharing() throws CloudException, InternalException { try { if( exists(bucketName) ) { if( !findFreeName ) { - throw new CloudException("The bucket " + bucketName + " already exists."); + throw new InternalException("The bucket " + bucketName + " already exists."); } else { bucketName = findFreeName(bucketName); @@ -129,17 +103,14 @@ public boolean allowsPublicSharing() throws CloudException, InternalException { } catch( CloudException e ) { logger.error(e); - e.printStackTrace(); throw e; } catch(InternalException e ) { logger.error(e); - e.printStackTrace(); throw e; } catch( RuntimeException e ) { logger.error(e); - e.printStackTrace(); throw new InternalException(e); } } @@ -158,14 +129,11 @@ private void createBucket(@Nonnull String name) throws InternalException, CloudE APITrace.begin(getProvider(), "Blob.createBucket"); try { try { - SwiftMethod method = new SwiftMethod(getProvider()); - - method.put(name); + new SwiftMethod(getProvider()).put(name); } catch( RuntimeException e ) { logger.error("Could not create bucket: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new GeneralCloudException("Could not create bucket", e, CloudErrorType.GENERAL); } } finally { @@ -178,9 +146,7 @@ public boolean exists(@Nonnull String bucketName) throws InternalException, Clou APITrace.begin(getProvider(), "exists"); try { try { - SwiftMethod method = new SwiftMethod(getProvider()); - - for( String container : method.get(null) ) { + for( String container : new SwiftMethod(getProvider()).get(null) ) { if( container.equals(bucketName) ) { return true; } @@ -189,8 +155,7 @@ public boolean exists(@Nonnull String bucketName) throws InternalException, Clou } catch( RuntimeException e ) { logger.error("Could not retrieve file info for " + bucketName + ": " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new GeneralCloudException("Could not retrieve file info for bucket", e, CloudErrorType.GENERAL); } } finally { @@ -250,7 +215,7 @@ public String getSignedObjectUrl(@Nonnull String bucket, @Nonnull String object, APITrace.begin(getProvider(), "Blob.getObjectSize"); try { if( bucket == null ) { - throw new CloudException("Requested object size for object in null bucket"); + throw new ResourceNotFoundException("No such object: " + bucket ); } if( object == null ) { return null; @@ -267,18 +232,13 @@ public String getSignedObjectUrl(@Nonnull String bucket, @Nonnull String object, if( len < 0L ) { return null; } - return new Storage(len, Storage.BYTE); + return new Storage<>(len, Storage.BYTE); } finally { APITrace.end(); } } - @Override - public int getMaxBuckets() throws CloudException, InternalException { - return MAX_BUCKETS; - } - private @Nonnull String findFreeName(@Nonnull String bucket) throws InternalException, CloudException { int idx = bucket.lastIndexOf("."); String prefix, rawName; @@ -328,7 +288,7 @@ protected void get(@Nullable String bucket, @Nonnull String location, @Nonnull F APITrace.begin(getProvider(), "Blob.get"); try { if( bucket == null ) { - throw new OperationNotSupportedException("No such object: " + bucket + "/" + location); + throw new ResourceNotFoundException("No such object: " + bucket + "/" + location); } if( toFile.exists() ) { if( !toFile.delete() ) { @@ -340,7 +300,7 @@ protected void get(@Nullable String bucket, @Nonnull String location, @Nonnull F input = method.get(bucket, location); if( input == null ) { - throw new CloudException("No such object: " + bucket + "/" + location); + throw new ResourceNotFoundException("No such object: " + bucket + "/" + location); } try { copy(input, new FileOutputStream(toFile), transfer); @@ -354,17 +314,6 @@ protected void get(@Nullable String bucket, @Nonnull String location, @Nonnull F } } - @Override - public Storage getMaxObjectSize() { - return MAX_OBJECT_SIZE; - } - - @Override - public int getMaxObjectsPerBucket() throws CloudException, InternalException { - return MAX_OBJECTS; - } - - private long getMetaDataLength(@Nonnull Map meta) { return getMetaDataLong("Content-Length", meta); } @@ -392,16 +341,6 @@ private long getMetaDataLong(@Nonnull String key, @Nonnull Map me } */ - @Override - public @Nonnull String getProviderTermForBucket(@Nonnull Locale locale) { - return "bucket"; - } - - @Override - public @Nonnull String getProviderTermForObject(@Nonnull Locale locale) { - return "object"; - } - @Override public boolean isPublic(@Nullable String bucket, @Nullable String object) throws CloudException, InternalException { return false; @@ -423,19 +362,15 @@ public boolean isSubscribed() throws CloudException, InternalException { @Override public @Nonnull Collection list(final @Nullable String bucket) throws CloudException, InternalException { - final ProviderContext ctx = getProvider().getContext(); PopulatorThread populator; - if( ctx == null ) { - throw new CloudException("No context was specified for this request"); - } - final String regionId = ctx.getRegionId(); + final String regionId = getContext().getRegionId(); if( regionId == null ) { - throw new CloudException("No region ID was specified"); + throw new InternalException("No region ID was specified"); } getProvider().hold(); - populator = new PopulatorThread(new JiteratorPopulator() { + populator = new PopulatorThread<>(new JiteratorPopulator() { public void populate(@Nonnull Jiterator iterator) throws CloudException, InternalException { try { APITrace.begin(getProvider(), "Blob.list"); @@ -465,22 +400,18 @@ private void list(@Nonnull String regionId, @Nullable String bucket, @Nonnull Ji } private void loadBuckets(@Nonnull String regionId, @Nonnull Jiterator iterator) throws CloudException, InternalException { - Logger logger = NovaOpenStack.getLogger(SwiftBlobStore.class, "std"); - if( logger.isTraceEnabled() ) { logger.trace("enter - " + SwiftBlobStore.class.getName() + ".loadBuckets(" + regionId + "," + iterator + ")"); } try { SwiftMethod method = new SwiftMethod(getProvider()); Collection containers; - try { containers = method.get(null); } catch( RuntimeException e ) { logger.error("Could not load buckets: " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new GeneralCloudException("Could not load buckets ", e, CloudErrorType.GENERAL); } for( String container : containers ) { iterator.push(Blob.getInstance(regionId, "/" + container, container, 0L)); @@ -494,8 +425,6 @@ private void loadBuckets(@Nonnull String regionId, @Nonnull Jiterator iter } private void loadObjects(@Nonnull String regionId, @Nonnull String bucketName, @Nonnull Jiterator iterator) throws CloudException, InternalException { - Logger logger = NovaOpenStack.getLogger(SwiftBlobStore.class, "std"); - if( logger.isTraceEnabled() ) { logger.trace("enter - " + SwiftBlobStore.class.getName() + ".loadFiles(" + bucketName + "," + iterator + ")"); } @@ -513,8 +442,8 @@ private void loadObjects(@Nonnull String regionId, @Nonnull String bucketName, @ } catch( RuntimeException e ) { logger.error("Could not list files in " + bucketName + ": " + e.getMessage()); - e.printStackTrace(); - throw new CloudException(e); + throw new GeneralCloudException("Could not list files ", e, CloudErrorType.GENERAL); + } for( String info : files ) { Map metaData = method.head(bucketName, info); @@ -549,13 +478,13 @@ public void move(@Nullable String sourceBucket, @Nullable String object, @Nullab APITrace.begin(getProvider(), "Blob.move"); try { if( sourceBucket == null ) { - throw new CloudException("No source bucket was specified"); + throw new InternalException("No source bucket was specified"); } if( targetBucket == null ) { - throw new CloudException("No target bucket was specified"); + throw new InternalException("No target bucket was specified"); } if( object == null ) { - throw new CloudException("No source object was specified"); + throw new InternalException("No source object was specified"); } copy(sourceBucket, object, targetBucket, object); removeObject(sourceBucket, object); @@ -609,7 +538,6 @@ protected void put(@Nullable String bucket, @Nonnull String object, @Nonnull Str } catch( IOException e ) { logger.error("Failed to write file: " + e.getMessage()); - e.printStackTrace(); throw new InternalException(e); } } @@ -622,9 +550,7 @@ protected void put(@Nullable String bucket, @Nonnull String object, @Nonnull Str public void removeBucket(@Nonnull String bucket) throws CloudException, InternalException { APITrace.begin(getProvider(), "Blob.removeBucket"); try { - SwiftMethod method = new SwiftMethod(getProvider()); - - method.delete(bucket); + new SwiftMethod(getProvider()).delete(bucket); } finally { APITrace.end(); @@ -638,9 +564,7 @@ public void removeObject(@Nullable String bucket, @Nonnull String name) throws C if( bucket == null ) { throw new OperationNotSupportedException("Swift does not support root objects"); } - SwiftMethod method = new SwiftMethod(getProvider()); - - method.delete(bucket, name); + new SwiftMethod(getProvider()).delete(bucket, name); } finally { APITrace.end(); @@ -692,7 +616,7 @@ public void renameObject(@Nullable String bucket, @Nonnull String object, @Nonnu APITrace.begin(getProvider(), "Blob.removeObject"); try { if( bucket == null ) { - throw new CloudException("No bucket was specified"); + throw new InternalException("No bucket was specified"); } copy(bucket, object, bucket, newName); removeObject(bucket, object); @@ -720,20 +644,6 @@ public void renameObject(@Nullable String bucket, @Nonnull String object, @Nonnu } } - @Override - public @Nonnull - NamingConstraints getBucketNameRules() throws CloudException, InternalException { - //return NameRules.getInstance(minChars, maxChars, mixedCase, allowNumbers, latin1Only, specialChars); - return NamingConstraints.getAlphaNumeric(1, 255).lowerCaseOnly().limitedToLatin1().constrainedBy(new char[] { '-', '.' }); - //return NameRules.getInstance(1, 255, false, true, true, new char[] { '-', '.' }); - } - - @Override - public @Nonnull NamingConstraints getObjectNameRules() throws CloudException, InternalException { - return NamingConstraints.getAlphaNumeric(1, 255).lowerCaseOnly().limitedToLatin1().constrainedBy(new char[] { '-', '.', ',', '#', '+' }); - //return NameRules.getInstance(1, 255, false, true, true, new char[] { '-', '.', ',', '#', '+' }); - } - @Override public void updateTags(@Nonnull String bucketName, @Nonnull Tag ... tags) throws CloudException, InternalException { APITrace.begin(getProvider(), "Bucket.updateTags"); diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/AbstractMethodTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/AbstractMethodTest.java index 339c100..f72d67b 100644 --- a/src/test/java/org/dasein/cloud/openstack/nova/os/AbstractMethodTest.java +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/AbstractMethodTest.java @@ -62,7 +62,6 @@ public void postStringThrowsExceptionFor413() { when(response.getEntity()).thenReturn(entity); } catch( IOException e ) { - e.printStackTrace(); } try { @@ -79,10 +78,8 @@ public void postStringThrowsExceptionFor413() { assertEquals("Exception error type does not match", CloudErrorType.CAPACITY, e.getErrorType()); } catch( InternalException e ) { - e.printStackTrace(); } catch( IOException e ) { - e.printStackTrace(); } } } diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/NovaMethodTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/NovaMethodTest.java index 25d376e..f5cb8d0 100644 --- a/src/test/java/org/dasein/cloud/openstack/nova/os/NovaMethodTest.java +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/NovaMethodTest.java @@ -410,7 +410,6 @@ public void deleteHPCDNTest (){ } catch( InternalException | CloudException e) { - e.printStackTrace(); fail("Test failed " + e.getMessage()); } } diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java index 8704e98..ea8d1ea 100644 --- a/src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImplTest.java @@ -500,11 +500,8 @@ public void findAllVips() { assertEquals("Query is not correct", "?tenant_id="+ testOwnerId, queryCpt.getValue()); } - catch( CloudException e ) { - e.printStackTrace(); - } - catch( InternalException e ) { - e.printStackTrace(); + catch( CloudException | InternalException e ) { + fail("Test failed " + e.getMessage()); } } @@ -535,11 +532,8 @@ public void findAllMembers() { assertEquals("Query is not correct", "?tenant_id="+ testOwnerId, queryCpt.getValue()); } - catch( CloudException e ) { - e.printStackTrace(); - } - catch( InternalException e ) { - e.printStackTrace(); + catch( CloudException | InternalException e ) { + fail("Test failed " + e.getMessage()); } } @@ -587,13 +581,7 @@ public void findLoadBalancersWithoutId() { } - catch( CloudException e ) { - fail("Test failed " + e.getMessage()); - } - catch( InternalException e ) { - fail("Test failed " + e.getMessage()); - } - catch( JSONException e ) { + catch( CloudException | InternalException | JSONException e ) { fail("Test failed " + e.getMessage()); } @@ -643,17 +631,9 @@ public void findLoadBalancersWithId() { } - catch( CloudException e ) { - fail("Test failed " + e.getMessage()); - } - catch( InternalException e ) { + catch( CloudException | InternalException | JSONException e ) { fail("Test failed " + e.getMessage()); } - catch( JSONException e ) { - fail("Test failed " + e.getMessage()); - } - - } @Test @@ -714,7 +694,6 @@ public void toLoadBalancer() { assertEquals("LB visible scope is not as expected", VisibleScope.ACCOUNT_REGION, lb.getVisibleScope()); assertEquals("LB VLAN id should be null", null, lb.getProviderVlanId()); } catch( JSONException | InternalException | CloudException e ) { - e.printStackTrace(); fail("Test failed " + e.getMessage()); } } @@ -745,20 +724,10 @@ public void removeLoadBalancer() { lbSupport.getLoadBalancersResource(), resourceCpt.getAllValues().get(1)); assertEquals("Resource Id parameter when deleting a loadbalancer was wrong", testLbId, resourceIdCpt.getAllValues().get(1)); - - } - catch( CloudException e ) { - fail("Test failed " + e.getMessage()); - - } - catch( InternalException e ) { + catch( CloudException | InternalException | JSONException e ) { fail("Test failed " + e.getMessage()); } - catch( JSONException e ) { - fail("Test failed " + e.getMessage()); - } - } @Test From 7db7bbcf3f610cbf5751c9dc40a378ff3c04a099 Mon Sep 17 00:00:00 2001 From: mariapavlova Date: Fri, 12 Feb 2016 21:44:07 +0000 Subject: [PATCH 4/7] Image tests --- pom.xml | 21 +- .../openstack/nova/os/compute/NovaImage.java | 20 +- .../openstack/{nova/os => }/TestSuite.java | 2 +- .../nova/os/compute/NovaImageTest.java | 190 ++++++++++++++++++ .../nova/fixtures/images/create_image.json | 3 + .../nova/fixtures/images/get_image.json | 53 +++++ .../nova/fixtures/images/get_images.json | 48 +++++ 7 files changed, 325 insertions(+), 12 deletions(-) rename src/test/java/org/dasein/cloud/openstack/{nova/os => }/TestSuite.java (95%) create mode 100644 src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java create mode 100644 src/test/resources/nova/fixtures/images/create_image.json create mode 100644 src/test/resources/nova/fixtures/images/get_image.json create mode 100644 src/test/resources/nova/fixtures/images/get_images.json diff --git a/pom.xml b/pom.xml index d5277f6..7edf6d1 100644 --- a/pom.xml +++ b/pom.xml @@ -36,7 +36,7 @@ org.dasein dasein-cloud-core - 2016.02.1-SNAPSHOT + 0.9.0 compile false @@ -107,7 +107,18 @@ 1.2.3 test - + + org.powermock + powermock-module-junit4 + 1.5.6 + test + + + org.powermock + powermock-api-mockito + 1.5.6 + test + @@ -246,9 +257,9 @@ ${test.machineImage} - - **/TestSuite.java - + + **/TestSuite.java + diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java index 787f2d5..352d5ac 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java @@ -58,6 +58,10 @@ public class NovaImage extends AbstractImageSupport { super(provider); } + protected NovaMethod getMethod() { + return new NovaMethod(getProvider()); + } + private @Nonnull String getTenantId() throws CloudException, InternalException { return getContext().getAccountNumber(); } @@ -65,7 +69,7 @@ public class NovaImage extends AbstractImageSupport { public @Nullable String getImageRef(@Nonnull String machineImageId) throws CloudException, InternalException { APITrace.begin(getProvider(), "Image.getImageRef"); try { - NovaMethod method = new NovaMethod(getProvider()); + NovaMethod method = getMethod(); JSONObject ob = method.getServers("/images", machineImageId, true); if( ob == null ) { @@ -105,8 +109,8 @@ else if( def == null ) { protected MachineImage capture(@Nonnull ImageCreateOptions options, @Nullable AsynchronousTask task) throws CloudException, InternalException { APITrace.begin(getProvider(), "Image.capture"); try { - NovaMethod method = new NovaMethod(getProvider()); - Map action = new HashMap(); + NovaMethod method = getMethod(); + Map action = new HashMap<>(); action.put("name", options.getName()); if( task != null ) { @@ -120,7 +124,7 @@ protected MachineImage capture(@Nonnull ImageCreateOptions options, @Nullable As while( timeout > System.currentTimeMillis() ) { try { - ComputeServices services = getProvider().getComputeServices(); + ComputeServices services = getComputeServices(); VirtualMachine vm = null; if( services != null ) { @@ -131,7 +135,7 @@ protected MachineImage capture(@Nonnull ImageCreateOptions options, @Nullable As } } if( vm == null ) { - throw new ResourceNotFoundException("No such virtual machine: " + vmId); + throw new ResourceNotFoundException("vm", vmId); } platform = vm.getPlatform(); if( !VmState.PENDING.equals(vm.getCurrentState()) ) { @@ -222,6 +226,10 @@ else if( result != null && result.has("location") ) { } } + protected ComputeServices getComputeServices() { + return getProvider().getComputeServices(); + } + private transient volatile NovaImageCapabilities capabilities; @Override public ImageCapabilities getCapabilities() throws CloudException, InternalException { @@ -441,7 +449,7 @@ public void remove(@Nonnull String providerImageId, boolean checkState) throws C JSONObject md = (json.has("metadata") ? json.getJSONObject("metadata") : null); Architecture architecture = Architecture.I64; Platform platform = Platform.UNKNOWN; - String owner = ((NovaOpenStack)getProvider()).getCloudProvider().getDefaultImageOwner(getTenantId()); + String owner = getProvider().getCloudProvider().getDefaultImageOwner(getTenantId()); if( md != null ) { if( description == null && md.has("org.dasein.description") ) { diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/TestSuite.java b/src/test/java/org/dasein/cloud/openstack/TestSuite.java similarity index 95% rename from src/test/java/org/dasein/cloud/openstack/nova/os/TestSuite.java rename to src/test/java/org/dasein/cloud/openstack/TestSuite.java index a44eb6f..34eb771 100644 --- a/src/test/java/org/dasein/cloud/openstack/nova/os/TestSuite.java +++ b/src/test/java/org/dasein/cloud/openstack/TestSuite.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.dasein.cloud.openstack.nova.os; +package org.dasein.cloud.openstack; import org.dasein.cloud.test.GlobalTestSuite; diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java new file mode 100644 index 0000000..031f806 --- /dev/null +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java @@ -0,0 +1,190 @@ +package org.dasein.cloud.openstack.nova.os.compute; + +import org.dasein.cloud.AsynchronousTask; +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.ProviderContext; +import org.dasein.cloud.compute.ImageCreateOptions; +import org.dasein.cloud.compute.MachineImage; +import org.dasein.cloud.compute.Platform; +import org.dasein.cloud.compute.VirtualMachine; +import org.dasein.cloud.openstack.nova.os.NovaMethod; +import org.dasein.cloud.openstack.nova.os.NovaOpenStack; +import org.dasein.cloud.openstack.nova.os.OpenStackProvider; +import org.dasein.cloud.openstack.nova.os.OpenStackTest; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import static org.junit.Assert.*; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.*; + +/** + * Created by mariapavlova on 12/02/2016. + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(NovaImage.class) +public class NovaImageTest extends OpenStackTest { + private NovaMethod method; + private NovaImage imageSupport; + private NovaComputeServices computeServices; + private NovaServer vmSupport; + + private String testImageId = "testImageId"; + private String testImageName = "testImageName"; + private String testImageDescription = "testImageDescription"; + private String testVmId = "testVmId"; + private String testRegionId = "testRegionId"; + + @Before + public void setup() { + NovaOpenStack provider = mock(NovaOpenStack.class); + try { + when(provider.isPostCactus()).thenReturn(true); + when(provider.getCloudProvider()).thenReturn(OpenStackProvider.OTHER); + } + catch( CloudException | InternalException e ) { + e.printStackTrace(); + fail(); + } + ProviderContext context = mock(ProviderContext.class); + when(context.getRegionId()).thenReturn(testRegionId); + try { + PowerMockito.doReturn(provider).when(imageSupport, "getProvider"); + PowerMockito.doReturn(context).when(imageSupport, "getContext"); + } + catch( Exception e ) { + e.printStackTrace(); + fail("Exception occurred " + e.getMessage()); + } + + imageSupport = mock(NovaImage.class); + computeServices = mock(NovaComputeServices.class); + vmSupport = mock(NovaServer.class); + method = mock(NovaMethod.class); + when(imageSupport.getMethod()).thenReturn(method); + when(imageSupport.getComputeServices()).thenReturn(computeServices); + when(computeServices.getVirtualMachineSupport()).thenReturn(vmSupport); + } + + @Test + public void testGetImageRef() throws Exception { + // prepare mocks and data + JSONObject json = readJson("nova/fixtures/images/get_image.json"); + when(method.getServers(anyString(), anyString(), anyBoolean())).thenReturn(json); + when(imageSupport.getImageRef(anyString())).thenCallRealMethod(); + + // test invocation + String ref = imageSupport.getImageRef(testImageId); + + // verify + ArgumentCaptor imageIdCapt = ArgumentCaptor.forClass(String.class); + verify(method).getServers(anyString(), imageIdCapt.capture(), anyBoolean()); + assertEquals("Image Id parameter is not as expected", testImageId, imageIdCapt.getValue()); + assertEquals("Returned value is not as expected", + "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/11cdc38b-7d87-4ab9-86bd-19cf33056b81", + ref); + } + + @Test + public void testCapture() throws Exception { + // prepare mocks and data + JSONObject json = readJson("nova/fixtures/images/get_image.json"); + VirtualMachine vm = mock(VirtualMachine.class); + when(vm.getProviderVirtualMachineId()).thenReturn(testVmId); + when(vm.getPlatform()).thenReturn(Platform.CENT_OS); + when(vmSupport.getVirtualMachine(anyString())).thenReturn(vm); + when(method.postServers(anyString(), anyString(), any(JSONObject.class), anyBoolean())).thenReturn(json); + when(imageSupport.capture(any(ImageCreateOptions.class), any(AsynchronousTask.class))).thenCallRealMethod(); + when(imageSupport.toImage(any(JSONObject.class))).thenCallRealMethod(); + + // test invocation + MachineImage machineImage = imageSupport.capture(ImageCreateOptions.getInstance(vm, testImageName, testImageDescription), null); + + // verify + ArgumentCaptor resourceCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor jsonCapt = ArgumentCaptor.forClass(JSONObject.class); + ArgumentCaptor suffixCapt = ArgumentCaptor.forClass(Boolean.class); + + verify(method).postServers(resourceCapt.capture(), resourceIdCapt.capture(), jsonCapt.capture(), suffixCapt.capture()); + assertEquals("Requested resource is invalid", "/servers", resourceCapt.getValue()); + assertEquals("Requested resourceId is invalid", testVmId, resourceIdCapt.getValue()); + assertTrue("Requested JSON is invalid", jsonCapt.getValue().has("createImage")); + assertTrue("Requested suffix flag is invalid", suffixCapt.getValue()); + assertNotNull("Returned machine image is invalid", machineImage); + } + + @Test + public void testGetImage() throws Exception { +// fail("Test is not ready"); + } + + @Test + public void testIsImageSharedWithPublic() throws Exception { +// fail("Test is not ready"); + } + + @Test public void testIsSubscribed() throws Exception { + + } + + @Test public void testListImageStatus() throws Exception { + + } + + @Test public void testListImages() throws Exception { + + } + + @Test public void testRemove() throws Exception { + + } + + @Test public void testSearchPublicImages() throws Exception { + + } + + @Test public void testToImage() throws Exception { + + } + + @Test public void testToStatus() throws Exception { + + } + + @Test public void testSetTags() throws Exception { + + } + + @Test public void testSetTags1() throws Exception { + + } + + @Test public void testUpdateTags() throws Exception { + + } + + @Test public void testUpdateTags1() throws Exception { + + } + + @Test public void testRemoveTags() throws Exception { + + } + + @Test public void testRemoveTags1() throws Exception { + + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/images/create_image.json b/src/test/resources/nova/fixtures/images/create_image.json new file mode 100644 index 0000000..9bad3cf --- /dev/null +++ b/src/test/resources/nova/fixtures/images/create_image.json @@ -0,0 +1,3 @@ +{ + "location": "/testlocation" +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/images/get_image.json b/src/test/resources/nova/fixtures/images/get_image.json new file mode 100644 index 0000000..e263dea --- /dev/null +++ b/src/test/resources/nova/fixtures/images/get_image.json @@ -0,0 +1,53 @@ +{ + "image": { + "status": "ACTIVE", + "updated": "2016-02-08T07:11:42Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/11cdc38b-7d87-4ab9-86bd-19cf33056b81", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/11cdc38b-7d87-4ab9-86bd-19cf33056b81", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/11cdc38b-7d87-4ab9-86bd-19cf33056b81", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "11cdc38b-7d87-4ab9-86bd-19cf33056b81", + "OS-EXT-IMG-SIZE:size": 1653997568, + "name": "kstestubu1", + "created": "2016-02-08T07:11:03Z", + "minDisk": 20, + "server": { + "id": "405e9abf-82aa-46d2-8c94-6f14d78d0a26", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/servers/405e9abf-82aa-46d2-8c94-6f14d78d0a26", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/servers/405e9abf-82aa-46d2-8c94-6f14d78d0a26", + "rel": "bookmark" + } + ] + }, + "progress": 100, + "minRam": 0, + "metadata": { + "org.dasein.platform": "UBUNTU", + "image_location": "snapshot", + "image_state": "available", + "user_id": "e3ea2e865bcd43f59b97dfc76acd0e81", + "image_type": "snapshot", + "org.dasein.description": "kstestubu1", + "base_image_ref": "be75c519-a938-41e1-88bb-2af6d9e9c962", + "network_allocated": "True", + "instance_uuid": "405e9abf-82aa-46d2-8c94-6f14d78d0a26", + "owner_id": "94b7d98054db4d4eb5734e4a370805c7" + } + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/images/get_images.json b/src/test/resources/nova/fixtures/images/get_images.json new file mode 100644 index 0000000..00f77ff --- /dev/null +++ b/src/test/resources/nova/fixtures/images/get_images.json @@ -0,0 +1,48 @@ +{ + "images": [ + { + "status": "active", + "name": "cirros-0.3.2-x86_64-disk", + "tags": [], + "container_format": "bare", + "created_at": "2014-11-07T17:07:06Z", + "disk_format": "qcow2", + "updated_at": "2014-11-07T17:19:09Z", + "visibility": "public", + "self": "/v2/images/1bea47ed-f6a9-463b-b423-14b9cca9ad27", + "min_disk": 0, + "protected": false, + "id": "1bea47ed-f6a9-463b-b423-14b9cca9ad27", + "file": "/v2/images/1bea47ed-f6a9-463b-b423-14b9cca9ad27/file", + "checksum": "64d7c1cd2b6f60c92c14662941cb7913", + "owner": "5ef70662f8b34079a6eddb8da9d75fe8", + "size": 13167616, + "min_ram": 0, + "schema": "/v2/schemas/image", + "virtual_size": null + }, + { + "status": "active", + "name": "F17-x86_64-cfntools", + "tags": [], + "container_format": "bare", + "created_at": "2014-10-30T08:23:39Z", + "disk_format": "qcow2", + "updated_at": "2014-11-03T16:40:10Z", + "visibility": "public", + "self": "/v2/images/781b3762-9469-4cec-b58d-3349e5de4e9c", + "min_disk": 0, + "protected": false, + "id": "781b3762-9469-4cec-b58d-3349e5de4e9c", + "file": "/v2/images/781b3762-9469-4cec-b58d-3349e5de4e9c/file", + "checksum": "afab0f79bac770d61d24b4d0560b5f70", + "owner": "5ef70662f8b34079a6eddb8da9d75fe8", + "size": 476704768, + "min_ram": 0, + "schema": "/v2/schemas/image", + "virtual_size": null + } + ], + "schema": "/v2/schemas/images", + "first": "/v2/images" +} \ No newline at end of file From 2b8ef42cd68573174eeab9062bb660c58c94bfd3 Mon Sep 17 00:00:00 2001 From: mariapavlova Date: Tue, 16 Feb 2016 16:17:13 +0000 Subject: [PATCH 5/7] NovaImage unit tests --- .../openstack/nova/os/compute/NovaImage.java | 32 +- .../nova/os/compute/NovaImageTest.java | 299 +++++++++-- .../nova/fixtures/images/get_images.json | 469 ++++++++++++++++-- 3 files changed, 711 insertions(+), 89 deletions(-) diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java index 352d5ac..79800a1 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaImage.java @@ -52,7 +52,7 @@ public class NovaImage extends AbstractImageSupport { static private final Logger logger = NovaOpenStack.getLogger(NovaImage.class, "std"); - private static final String SERVICE = "compute"; + protected static final String SERVICE = "compute"; NovaImage(NovaOpenStack provider) { super(provider); @@ -62,7 +62,7 @@ protected NovaMethod getMethod() { return new NovaMethod(getProvider()); } - private @Nonnull String getTenantId() throws CloudException, InternalException { + protected @Nonnull String getTenantId() throws CloudException, InternalException { return getContext().getAccountNumber(); } @@ -243,7 +243,7 @@ public ImageCapabilities getCapabilities() throws CloudException, InternalExcept public MachineImage getImage(@Nonnull String providerImageId) throws CloudException, InternalException { APITrace.begin(getProvider(), "Image.getImage"); try { - NovaMethod method = new NovaMethod(getProvider()); + NovaMethod method = getMethod(); JSONObject ob = method.getServers("/images", providerImageId, true); if( ob == null ) { @@ -302,9 +302,9 @@ public boolean isSubscribed() throws CloudException, InternalException { if( !cls.equals(ImageClass.MACHINE) ) { return Collections.emptyList(); } - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers("/images", null, true); - List images = new ArrayList(); + List images = new ArrayList<>(); try { if( ob != null && ob.has("images") ) { @@ -377,7 +377,7 @@ public boolean isSubscribed() throws CloudException, InternalException { public void remove(@Nonnull String providerImageId, boolean checkState) throws CloudException, InternalException { APITrace.begin(getProvider(), "Image.remove"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR; do { @@ -402,9 +402,9 @@ public void remove(@Nonnull String providerImageId, boolean checkState) throws C public @Nonnull Iterable searchPublicImages(@Nonnull ImageFilterOptions options) throws InternalException, CloudException { APITrace.begin(getProvider(), "Image.searchPublicImages"); try { - NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); + NovaMethod method = new NovaMethod(getProvider()); JSONObject ob = method.getServers("/images", null, true); - List images = new ArrayList(); + List images = new ArrayList<>(); String me = getTenantId(); try { @@ -431,9 +431,7 @@ public void remove(@Nonnull String providerImageId, boolean checkState) throws C } } - public @Nullable MachineImage toImage(@Nullable JSONObject json) throws CloudException, InternalException { - Logger logger = NovaOpenStack.getLogger(NovaImage.class, "std"); - + protected @Nullable MachineImage toImage(@Nullable JSONObject json) throws CloudException, InternalException { if( logger.isTraceEnabled() ) { logger.trace("enter - " + NovaImage.class.getName() + ".toImage(" + json + ")"); } @@ -568,12 +566,12 @@ else if( platform.equals(Platform.UNIX) ) { } } } - boolean bMinSize = false; - if(json.has("minDisk")){ - bMinSize = true; - image.setTag("minDisk", json.getString("minDisk")); + if( json.has("minDisk") ){ + image.setMinimumDiskSizeGb(json.getLong("minDisk")); + } + else if( json.has("OS-EXT-IMG-SIZE:size") ) { + image.setMinimumDiskSizeGb(json.getLong("OS-EXT-IMG-SIZE:size")); } - if(!bMinSize)if(json.has("OS-EXT-IMG-SIZE:size"))image.setTag("minSize", json.getString("OS-EXT-IMG-SIZE:size")); return image; } @@ -588,7 +586,7 @@ else if( platform.equals(Platform.UNIX) ) { } } - public @Nullable ResourceStatus toStatus(@Nullable JSONObject json) throws CloudException, InternalException { + protected @Nullable ResourceStatus toStatus(@Nullable JSONObject json) throws CloudException, InternalException { if( json == null ) { return null; diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java index 031f806..e8cd3be 100644 --- a/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java @@ -1,18 +1,11 @@ package org.dasein.cloud.openstack.nova.os.compute; -import org.dasein.cloud.AsynchronousTask; -import org.dasein.cloud.CloudException; -import org.dasein.cloud.InternalException; -import org.dasein.cloud.ProviderContext; -import org.dasein.cloud.compute.ImageCreateOptions; -import org.dasein.cloud.compute.MachineImage; -import org.dasein.cloud.compute.Platform; -import org.dasein.cloud.compute.VirtualMachine; +import org.dasein.cloud.*; +import org.dasein.cloud.compute.*; import org.dasein.cloud.openstack.nova.os.NovaMethod; import org.dasein.cloud.openstack.nova.os.NovaOpenStack; import org.dasein.cloud.openstack.nova.os.OpenStackProvider; import org.dasein.cloud.openstack.nova.os.OpenStackTest; -import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; @@ -23,12 +16,16 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import java.util.Iterator; +import java.util.List; + import static org.junit.Assert.*; -import static org.powermock.api.mockito.PowerMockito.mock; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.whenNew; /** * Created by mariapavlova on 12/02/2016. @@ -40,16 +37,18 @@ public class NovaImageTest extends OpenStackTest { private NovaImage imageSupport; private NovaComputeServices computeServices; private NovaServer vmSupport; + private NovaOpenStack provider; private String testImageId = "testImageId"; private String testImageName = "testImageName"; private String testImageDescription = "testImageDescription"; private String testVmId = "testVmId"; private String testRegionId = "testRegionId"; + private String testOwnerId = "5ef70662f8b34079a6eddb8da9d75fe8"; @Before public void setup() { - NovaOpenStack provider = mock(NovaOpenStack.class); + provider = mock(NovaOpenStack.class); try { when(provider.isPostCactus()).thenReturn(true); when(provider.getCloudProvider()).thenReturn(OpenStackProvider.OTHER); @@ -60,6 +59,10 @@ public void setup() { } ProviderContext context = mock(ProviderContext.class); when(context.getRegionId()).thenReturn(testRegionId); + when(context.getAccountNumber()).thenReturn(testOwnerId); + + imageSupport = mock(NovaImage.class); + try { PowerMockito.doReturn(provider).when(imageSupport, "getProvider"); PowerMockito.doReturn(context).when(imageSupport, "getContext"); @@ -69,12 +72,25 @@ public void setup() { fail("Exception occurred " + e.getMessage()); } - imageSupport = mock(NovaImage.class); computeServices = mock(NovaComputeServices.class); vmSupport = mock(NovaServer.class); method = mock(NovaMethod.class); + try { + whenNew(NovaMethod.class).withAnyArguments().thenReturn(method); + } + catch( Exception e ) { + e.printStackTrace(); + fail("Couldn't create a mock for NovaMethod construction"); + } when(imageSupport.getMethod()).thenReturn(method); when(imageSupport.getComputeServices()).thenReturn(computeServices); + try { + when(imageSupport.getTenantId()).thenReturn(testOwnerId); + } + catch( CloudException | InternalException e ) { + e.printStackTrace(); + fail("Some kind of a problem while getting a tenant id"); + } when(computeServices.getVirtualMachineSupport()).thenReturn(vmSupport); } @@ -128,63 +144,288 @@ public void testCapture() throws Exception { @Test public void testGetImage() throws Exception { -// fail("Test is not ready"); + // prepare mocks and data + JSONObject json = readJson("nova/fixtures/images/get_image.json"); + MachineImage machineImage = mock(MachineImage.class); + + when(method.getServers(anyString(), anyString(), anyBoolean())).thenReturn(json); + when(imageSupport.toImage(any(JSONObject.class))).thenReturn(machineImage); + when(imageSupport.getImage(anyString())).thenCallRealMethod(); + + // test invocation + MachineImage machineImage1 = imageSupport.getImage(testImageId); + + // verify + ArgumentCaptor imageIdCapt = ArgumentCaptor.forClass(String.class); + verify(method).getServers(anyString(), imageIdCapt.capture(), anyBoolean()); + assertEquals("Image Id parameter is not as expected", testImageId, imageIdCapt.getValue()); + ArgumentCaptor jsonObjectArgumentCaptor = ArgumentCaptor.forClass(JSONObject.class); + verify(imageSupport).toImage(jsonObjectArgumentCaptor.capture()); + assertEquals("Json parameter not as expected", json.getJSONObject("image"), jsonObjectArgumentCaptor.getValue()); + assertEquals("Returned value is not as expected", + machineImage, machineImage1); } @Test public void testIsImageSharedWithPublic() throws Exception { -// fail("Test is not ready"); - } - - @Test public void testIsSubscribed() throws Exception { + MachineImage machineImage = MachineImage.getInstance(testOwnerId, testRegionId, testImageId, + ImageClass.MACHINE, MachineImageState.ACTIVE, "testName", "testDescription", + Architecture.I64, Platform.CENT_OS); + when(imageSupport.getImage(anyString())).thenReturn(machineImage); + when(imageSupport.isImageSharedWithPublic(anyString())).thenCallRealMethod(); + // test invocation + boolean test = imageSupport.isImageSharedWithPublic(testImageId); + ArgumentCaptor imageIdCapt = ArgumentCaptor.forClass(String.class); + verify(imageSupport).getImage(imageIdCapt.capture()); + assertEquals("getImage parameter is not as expected", testImageId, imageIdCapt.getValue()); + assertFalse("Result value is incorrect", test); } - @Test public void testListImageStatus() throws Exception { + @Test + public void testIsSubscribed() throws Exception { + when(provider.testContext()).thenReturn(testOwnerId); + when(imageSupport.isSubscribed()).thenCallRealMethod(); + boolean test = imageSupport.isSubscribed(); + assertTrue("Return value is incorrect", test); + } + @Test + public void testListImageStatus() throws Exception { + JSONObject json = readJson("nova/fixtures/images/get_images.json"); + when(method.getServers(anyString(), anyString(), anyBoolean())).thenReturn(json); + ResourceStatus dummy = new ResourceStatus("dummy", MachineImageState.ACTIVE); + when(imageSupport.toStatus(any(JSONObject.class))).thenReturn(dummy); + when(imageSupport.listImageStatus(any(ImageClass.class))).thenCallRealMethod(); + + Iterator resourceStatuses = imageSupport.listImageStatus(ImageClass.MACHINE).iterator(); + verify(imageSupport, times(11)).toStatus(any(JSONObject.class)); + int count = 0; + while( resourceStatuses.hasNext() ) { + count++; + resourceStatuses.next(); + } + assertEquals("The number of returned objects is incorrect", 11, count); } - @Test public void testListImages() throws Exception { + @Test + public void testListImages() throws Exception { + JSONObject json = readJson("nova/fixtures/images/get_images.json"); + when(method.getServers(anyString(), anyString(), anyBoolean())).thenReturn(json); + MachineImage dummy = MachineImage.getInstance(testOwnerId, testRegionId, "dummy", ImageClass.MACHINE, MachineImageState.ACTIVE, "dummy", "dummy", Architecture.I64, Platform.CENT_OS); + when(imageSupport.toImage(any(JSONObject.class))).thenReturn(dummy); + when(imageSupport.listImages(any(ImageFilterOptions.class))).thenCallRealMethod(); + // test invocation + Iterator images = imageSupport.listImages(ImageFilterOptions.getInstance()).iterator(); + verify(imageSupport, times(11)).toImage(any(JSONObject.class)); + int count = 0; + while( images.hasNext() ) { + count++; + images.next(); + } + assertEquals("The number of returned objects is incorrect", 11, count); } - @Test public void testRemove() throws Exception { + @Test + public void testRemove() throws Exception { + Mockito.doCallRealMethod().when(imageSupport).remove(anyString(), anyBoolean()); + imageSupport.remove(testImageId, true); + ArgumentCaptor machineImageIdArg = ArgumentCaptor.forClass(String.class); + verify(method).deleteServers(anyString(), machineImageIdArg.capture()); + assertEquals("Machine Image ID passed to the method is not as expected", testImageId, machineImageIdArg.getValue()); } - @Test public void testSearchPublicImages() throws Exception { + @Test + public void testSearchPublicImages() throws Exception { + JSONObject json = readJson("nova/fixtures/images/get_images.json"); + when(method.getServers(anyString(), anyString(), anyBoolean())).thenReturn(json); + MachineImage privateImage = MachineImage.getInstance(testOwnerId, testRegionId, "dummy", ImageClass.MACHINE, MachineImageState.ACTIVE, "dummy", "dummy", Architecture.I64, Platform.CENT_OS); + MachineImage publicImage = MachineImage.getInstance("-public-", testRegionId, "dummy", ImageClass.MACHINE, MachineImageState.ACTIVE, "dummy", "dummy", Architecture.I64, Platform.CENT_OS); + // return private image once, then public + when(imageSupport.toImage(any(JSONObject.class))).thenReturn(privateImage).thenReturn(publicImage); + when(imageSupport.searchPublicImages(any(ImageFilterOptions.class))).thenCallRealMethod(); + // test invocation + Iterator images = imageSupport.searchPublicImages(ImageFilterOptions.getInstance()).iterator(); + verify(imageSupport, times(11)).toImage(any(JSONObject.class)); + int count = 0; + while( images.hasNext() ) { + count++; + images.next(); + } + assertEquals("The number of returned objects is incorrect", 10, count); } - @Test public void testToImage() throws Exception { - + @Test + public void testToImage() throws Exception { + JSONObject json = readJson("nova/fixtures/images/get_image.json"); + when(imageSupport.toImage(any(JSONObject.class))).thenCallRealMethod(); + MachineImage image = imageSupport.toImage(json.getJSONObject("image")); + assertNotNull("Returned value is incorrect", image); + assertEquals("Minimum disk size is incorrect", 20, image.getMinimumDiskSizeGb()); + assertEquals("Architecture is incorrect", Architecture.I64, image.getArchitecture()); + assertEquals("Creation time is incorrect", 1454915463000L, image.getCreationTimestamp()); + assertEquals("Current state is incorrect", MachineImageState.ACTIVE, image.getCurrentState()); + assertEquals("Description is incorrect", "kstestubu1", image.getDescription()); + assertEquals("Image class is incorrect", ImageClass.MACHINE, image.getImageClass()); + assertEquals("Name is incorrect", "kstestubu1", image.getName()); + assertEquals("Platform is incorrect", Platform.UBUNTU, image.getPlatform()); + assertEquals("Machine image id is incorrect", "11cdc38b-7d87-4ab9-86bd-19cf33056b81", image.getProviderMachineImageId()); + assertEquals("Region id is incorrect", testRegionId, image.getProviderRegionId()); + assertEquals("Software is incorrect", "", image.getSoftware()); + assertEquals("Image type is incorrect", MachineImageType.VOLUME, image.getType()); + assertEquals("Number of tags is incorrect", 10, image.getTags().size()); + assertEquals("base_image_ref tag is incorrect", "be75c519-a938-41e1-88bb-2af6d9e9c962", image.getTag("base_image_ref")); + assertEquals("user_id tag is incorrect", "e3ea2e865bcd43f59b97dfc76acd0e81", image.getTag("user_id")); + assertEquals("org.dasein.description tag is incorrect", "kstestubu1", image.getTag("org.dasein.description")); + assertEquals("owner_id tag is incorrect", "94b7d98054db4d4eb5734e4a370805c7", image.getTag("owner_id")); + assertEquals("org.dasein.platform tag is incorrect", "UBUNTU", image.getTag("org.dasein.platform")); + assertEquals("image_location tag is incorrect", "snapshot", image.getTag("image_location")); + assertEquals("image_state tag is incorrect", "available", image.getTag("image_state")); + assertEquals("network_allocated tag is incorrect", "True", image.getTag("network_allocated")); + assertEquals("instance_uuid tag is incorrect", "405e9abf-82aa-46d2-8c94-6f14d78d0a26", image.getTag("instance_uuid")); + assertEquals("image_type tag is incorrect", "snapshot", image.getTag("image_type")); + assertFalse("Image should not be marked as shared with public", image.isPublic()); } - @Test public void testToStatus() throws Exception { + @Test + public void testToStatus() throws Exception { + JSONObject json = readJson("nova/fixtures/images/get_image.json"); + when(imageSupport.toStatus(any(JSONObject.class))).thenCallRealMethod(); + + // test invocation + ResourceStatus test = imageSupport.toStatus(json.getJSONObject("image")); + assertNotNull("Return value is incorrect", test); + assertEquals("Resource id is incorrect", "11cdc38b-7d87-4ab9-86bd-19cf33056b81", test.getProviderResourceId()); + assertEquals("Resource status is incorrect", MachineImageState.ACTIVE, test.getResourceStatus()); } - @Test public void testSetTags() throws Exception { + @Test + public void testSetTags() throws Exception { + // prepare + Mockito.doCallRealMethod().when(imageSupport).setTags(anyString(), any(Tag.class), any(Tag.class)); + Tag[] tags = { new Tag("a", "aa"), new Tag("b", "bb") } ; + + // run + imageSupport.setTags(testImageId, tags); + // verify + ArgumentCaptor serviceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor imageIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + ArgumentCaptor tag2Capt = ArgumentCaptor.forClass(Tag.class); + verify(provider).createTags(serviceIdCapt.capture(), resourceCapt.capture(), imageIdCapt.capture(), tag1Capt.capture(), tag2Capt.capture()); + assertEquals("Service id is incorrect", NovaImage.SERVICE, serviceIdCapt.getValue()); + assertEquals("Resource is incorrect", "/images", resourceCapt.getValue()); + assertEquals("Resource id is incorrect", testImageId, imageIdCapt.getValue()); + assertArrayEquals("Tags are incorrect", tags, new Tag[] { tag1Capt.getValue(), tag2Capt.getValue() } ); } - @Test public void testSetTags1() throws Exception { + @Test + public void testSetTags1() throws Exception { + // prepare + Mockito.doCallRealMethod().when(imageSupport).setTags(any(String[].class), any(Tag.class)); + Tag tag = new Tag("a", "aa"); + String anotherImageId = "anotherTestId"; + + // run + imageSupport.setTags(new String[] {testImageId, anotherImageId}, tag); + // verify + ArgumentCaptor imageIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + verify(imageSupport, times(2)).setTags(imageIdCapt.capture(), tag1Capt.capture()); + List imageIdValues = imageIdCapt.getAllValues(); + assertArrayEquals("Image ids were not correct", new String[]{testImageId, anotherImageId}, + imageIdValues.toArray(new String[imageIdValues.size()])); + assertEquals("Tag was not correct", tag, tag1Capt.getValue()); } - @Test public void testUpdateTags() throws Exception { + @Test + public void testUpdateTags() throws Exception { + // prepare + Mockito.doCallRealMethod().when(imageSupport).updateTags(anyString(), any(Tag.class), any(Tag.class)); + Tag[] tags = { new Tag("a", "aa"), new Tag("b", "bb") } ; + // run + imageSupport.updateTags(testImageId, tags); + + // verify + ArgumentCaptor serviceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor imageIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + ArgumentCaptor tag2Capt = ArgumentCaptor.forClass(Tag.class); + verify(provider).updateTags(serviceIdCapt.capture(), resourceCapt.capture(), imageIdCapt.capture(), tag1Capt.capture(), tag2Capt.capture()); + assertEquals("Service id is incorrect", NovaImage.SERVICE, serviceIdCapt.getValue()); + assertEquals("Resource is incorrect", "/images", resourceCapt.getValue()); + assertEquals("Resource id is incorrect", testImageId, imageIdCapt.getValue()); + assertArrayEquals("Tags are incorrect", tags, new Tag[] { tag1Capt.getValue(), tag2Capt.getValue() } ); } @Test public void testUpdateTags1() throws Exception { + // prepare + Mockito.doCallRealMethod().when(imageSupport).updateTags(any(String[].class), any(Tag.class)); + Tag tag = new Tag("a", "aa"); + String anotherImageId = "anotherTestId"; + + // run + imageSupport.updateTags(new String[] {testImageId, anotherImageId}, tag); + // verify + ArgumentCaptor imageIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + verify(imageSupport, times(2)).updateTags(imageIdCapt.capture(), tag1Capt.capture()); + List imageIdValues = imageIdCapt.getAllValues(); + assertArrayEquals("Image ids were not correct", new String[]{testImageId, anotherImageId}, + imageIdValues.toArray(new String[imageIdValues.size()])); + assertEquals("Tag was not correct", tag, tag1Capt.getValue()); } - @Test public void testRemoveTags() throws Exception { + @Test + public void testRemoveTags() throws Exception { + // prepare + Mockito.doCallRealMethod().when(imageSupport).removeTags(anyString(), any(Tag.class), any(Tag.class)); + Tag[] tags = { new Tag("a", "aa"), new Tag("b", "bb") } ; + + // run + imageSupport.removeTags(testImageId, tags); + + // verify + ArgumentCaptor serviceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor imageIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + ArgumentCaptor tag2Capt = ArgumentCaptor.forClass(Tag.class); + verify(provider).removeTags(serviceIdCapt.capture(), resourceCapt.capture(), imageIdCapt.capture(), tag1Capt.capture(), tag2Capt.capture()); + assertEquals("Service id is incorrect", NovaImage.SERVICE, serviceIdCapt.getValue()); + assertEquals("Resource is incorrect", "/images", resourceCapt.getValue()); + assertEquals("Resource id is incorrect", testImageId, imageIdCapt.getValue()); + assertArrayEquals("Tags are incorrect", tags, new Tag[] { tag1Capt.getValue(), tag2Capt.getValue() } ); } - @Test public void testRemoveTags1() throws Exception { + @Test + public void testRemoveTags1() throws Exception { + // prepare + Mockito.doCallRealMethod().when(imageSupport).removeTags(any(String[].class), any(Tag.class)); + Tag tag = new Tag("a", "aa"); + String anotherImageId = "anotherTestId"; + + // run + imageSupport.removeTags(new String[] {testImageId, anotherImageId}, tag); + // verify + ArgumentCaptor imageIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + verify(imageSupport, times(2)).removeTags(imageIdCapt.capture(), tag1Capt.capture()); + List imageIdValues = imageIdCapt.getAllValues(); + assertArrayEquals("Image ids were not correct", new String[]{testImageId, anotherImageId}, + imageIdValues.toArray(new String[imageIdValues.size()])); + assertEquals("Tag was not correct", tag, tag1Capt.getValue()); } } \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/images/get_images.json b/src/test/resources/nova/fixtures/images/get_images.json index 00f77ff..9901544 100644 --- a/src/test/resources/nova/fixtures/images/get_images.json +++ b/src/test/resources/nova/fixtures/images/get_images.json @@ -1,48 +1,431 @@ { "images": [ { - "status": "active", - "name": "cirros-0.3.2-x86_64-disk", - "tags": [], - "container_format": "bare", - "created_at": "2014-11-07T17:07:06Z", - "disk_format": "qcow2", - "updated_at": "2014-11-07T17:19:09Z", - "visibility": "public", - "self": "/v2/images/1bea47ed-f6a9-463b-b423-14b9cca9ad27", - "min_disk": 0, - "protected": false, - "id": "1bea47ed-f6a9-463b-b423-14b9cca9ad27", - "file": "/v2/images/1bea47ed-f6a9-463b-b423-14b9cca9ad27/file", - "checksum": "64d7c1cd2b6f60c92c14662941cb7913", - "owner": "5ef70662f8b34079a6eddb8da9d75fe8", - "size": 13167616, - "min_ram": 0, - "schema": "/v2/schemas/image", - "virtual_size": null - }, - { - "status": "active", - "name": "F17-x86_64-cfntools", - "tags": [], - "container_format": "bare", - "created_at": "2014-10-30T08:23:39Z", - "disk_format": "qcow2", - "updated_at": "2014-11-03T16:40:10Z", - "visibility": "public", - "self": "/v2/images/781b3762-9469-4cec-b58d-3349e5de4e9c", - "min_disk": 0, - "protected": false, - "id": "781b3762-9469-4cec-b58d-3349e5de4e9c", - "file": "/v2/images/781b3762-9469-4cec-b58d-3349e5de4e9c/file", - "checksum": "afab0f79bac770d61d24b4d0560b5f70", - "owner": "5ef70662f8b34079a6eddb8da9d75fe8", - "size": 476704768, - "min_ram": 0, - "schema": "/v2/schemas/image", - "virtual_size": null + "status": "ACTIVE", + "updated": "2016-02-08T10:09:57Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/18c88af8-492b-4bc0-bd0c-e99c9764b2ee", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/18c88af8-492b-4bc0-bd0c-e99c9764b2ee", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/18c88af8-492b-4bc0-bd0c-e99c9764b2ee", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "18c88af8-492b-4bc0-bd0c-e99c9764b2ee", + "OS-EXT-IMG-SIZE:size": 1242497024, + "name": "plredvmimg", + "created": "2016-02-08T10:09:14Z", + "minDisk": 20, + "server": { + "id": "d2312e41-67bb-43ac-8434-27e67f05dcf8", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/servers/d2312e41-67bb-43ac-8434-27e67f05dcf8", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/servers/d2312e41-67bb-43ac-8434-27e67f05dcf8", + "rel": "bookmark" + } + ] + }, + "progress": 100, + "minRam": 0, + "metadata": { + "org.dasein.platform": "RHEL", + "instance_uuid": "d2312e41-67bb-43ac-8434-27e67f05dcf8", + "image_state": "available", + "user_id": "e3ea2e865bcd43f59b97dfc76acd0e81", + "image_location": "snapshot", + "image_type": "snapshot", + "org.dasein.description": "plredvmimg", + "ramdisk_id": null, + "kernel_id": null, + "network_allocated": "True", + "base_image_ref": "4fe549b5-7a94-4e6d-8712-4ca8462050c0", + "owner_id": "94b7d98054db4d4eb5734e4a370805c7" + } + }, + { + "status": "ACTIVE", + "updated": "2016-02-08T07:11:42Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/11cdc38b-7d87-4ab9-86bd-19cf33056b81", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/11cdc38b-7d87-4ab9-86bd-19cf33056b81", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/11cdc38b-7d87-4ab9-86bd-19cf33056b81", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "11cdc38b-7d87-4ab9-86bd-19cf33056b81", + "OS-EXT-IMG-SIZE:size": 1653997568, + "name": "kstestubu1", + "created": "2016-02-08T07:11:03Z", + "minDisk": 20, + "server": { + "id": "405e9abf-82aa-46d2-8c94-6f14d78d0a26", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/servers/405e9abf-82aa-46d2-8c94-6f14d78d0a26", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/servers/405e9abf-82aa-46d2-8c94-6f14d78d0a26", + "rel": "bookmark" + } + ] + }, + "progress": 100, + "minRam": 0, + "metadata": { + "org.dasein.platform": "UBUNTU", + "instance_uuid": "405e9abf-82aa-46d2-8c94-6f14d78d0a26", + "image_state": "available", + "user_id": "e3ea2e865bcd43f59b97dfc76acd0e81", + "image_location": "snapshot", + "image_type": "snapshot", + "org.dasein.description": "kstestubu1", + "ramdisk_id": null, + "kernel_id": null, + "network_allocated": "True", + "base_image_ref": "be75c519-a938-41e1-88bb-2af6d9e9c962", + "owner_id": "94b7d98054db4d4eb5734e4a370805c7" + } + }, + { + "status": "ACTIVE", + "updated": "2015-11-12T12:28:08Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/43c1fff5-e520-410f-bdb1-076adb8cc8c0", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/43c1fff5-e520-410f-bdb1-076adb8cc8c0", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/43c1fff5-e520-410f-bdb1-076adb8cc8c0", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "43c1fff5-e520-410f-bdb1-076adb8cc8c0", + "OS-EXT-IMG-SIZE:size": 851509248, + "name": "image-857377", + "created": "2015-11-12T12:27:46Z", + "minDisk": 20, + "server": { + "id": "a62e0a21-c96a-495a-a0bb-e05d439acf7b", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/servers/a62e0a21-c96a-495a-a0bb-e05d439acf7b", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/servers/a62e0a21-c96a-495a-a0bb-e05d439acf7b", + "rel": "bookmark" + } + ] + }, + "progress": 100, + "minRam": 0, + "metadata": { + "org.dasein.platform": "UBUNTU", + "instance_uuid": "a62e0a21-c96a-495a-a0bb-e05d439acf7b", + "image_state": "available", + "user_id": "e3ea2e865bcd43f59b97dfc76acd0e81", + "image_location": "snapshot", + "image_type": "snapshot", + "org.dasein.description": "image-857377", + "ramdisk_id": null, + "kernel_id": null, + "network_allocated": "True", + "base_image_ref": "be75c519-a938-41e1-88bb-2af6d9e9c962", + "owner_id": "94b7d98054db4d4eb5734e4a370805c7" + } + }, + { + "status": "ACTIVE", + "updated": "2015-11-03T15:00:09Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/44f93d94-782b-4327-a779-6fcb422f0ec4", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/44f93d94-782b-4327-a779-6fcb422f0ec4", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/44f93d94-782b-4327-a779-6fcb422f0ec4", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "44f93d94-782b-4327-a779-6fcb422f0ec4", + "OS-EXT-IMG-SIZE:size": 851509248, + "name": "image-866288", + "created": "2015-11-03T14:59:51Z", + "minDisk": 20, + "server": { + "id": "3f5c8984-4047-421d-965a-caa25b341f03", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/servers/3f5c8984-4047-421d-965a-caa25b341f03", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/servers/3f5c8984-4047-421d-965a-caa25b341f03", + "rel": "bookmark" + } + ] + }, + "progress": 100, + "minRam": 0, + "metadata": { + "org.dasein.platform": "UBUNTU", + "instance_uuid": "3f5c8984-4047-421d-965a-caa25b341f03", + "image_state": "available", + "user_id": "e3ea2e865bcd43f59b97dfc76acd0e81", + "image_location": "snapshot", + "image_type": "snapshot", + "org.dasein.description": "image-866288", + "ramdisk_id": null, + "kernel_id": null, + "network_allocated": "True", + "base_image_ref": "be75c519-a938-41e1-88bb-2af6d9e9c962", + "owner_id": "94b7d98054db4d4eb5734e4a370805c7" + } + }, + { + "status": "ACTIVE", + "updated": "2015-10-26T13:16:27Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/89977c3a-13be-4146-b306-fe94f8571068", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/89977c3a-13be-4146-b306-fe94f8571068", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/89977c3a-13be-4146-b306-fe94f8571068", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "89977c3a-13be-4146-b306-fe94f8571068", + "OS-EXT-IMG-SIZE:size": 851509248, + "name": "image-459676", + "created": "2015-10-26T13:16:09Z", + "minDisk": 20, + "server": { + "id": "9c427c19-7438-49e3-be5f-ed06089eedb8", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/servers/9c427c19-7438-49e3-be5f-ed06089eedb8", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/servers/9c427c19-7438-49e3-be5f-ed06089eedb8", + "rel": "bookmark" + } + ] + }, + "progress": 100, + "minRam": 0, + "metadata": { + "org.dasein.platform": "UBUNTU", + "instance_uuid": "9c427c19-7438-49e3-be5f-ed06089eedb8", + "image_state": "available", + "user_id": "e3ea2e865bcd43f59b97dfc76acd0e81", + "image_location": "snapshot", + "image_type": "snapshot", + "org.dasein.description": "image-459676", + "ramdisk_id": null, + "kernel_id": null, + "network_allocated": "True", + "base_image_ref": "be75c519-a938-41e1-88bb-2af6d9e9c962", + "owner_id": "94b7d98054db4d4eb5734e4a370805c7" + } + }, + { + "status": "SAVING", + "updated": "2015-09-08T03:56:50Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/fafb5504-411c-4b16-a4f0-352435052adf", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/fafb5504-411c-4b16-a4f0-352435052adf", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/fafb5504-411c-4b16-a4f0-352435052adf", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "fafb5504-411c-4b16-a4f0-352435052adf", + "OS-EXT-IMG-SIZE:size": 17182752768, + "name": "Windows-2012R2-Standard-64", + "created": "2015-09-08T03:56:49Z", + "minDisk": 0, + "progress": 50, + "minRam": 0, + "metadata": {} + }, + { + "status": "ACTIVE", + "updated": "2015-09-08T03:57:04Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/4fe549b5-7a94-4e6d-8712-4ca8462050c0", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/4fe549b5-7a94-4e6d-8712-4ca8462050c0", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/4fe549b5-7a94-4e6d-8712-4ca8462050c0", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "4fe549b5-7a94-4e6d-8712-4ca8462050c0", + "OS-EXT-IMG-SIZE:size": 337641472, + "name": "RHEL-6.5-x86_64", + "created": "2015-09-08T03:56:47Z", + "minDisk": 0, + "progress": 100, + "minRam": 0, + "metadata": {} + }, + { + "status": "ACTIVE", + "updated": "2015-09-08T03:56:54Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/8f5cd69c-721f-496a-b419-0c3b343ca7ca", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/8f5cd69c-721f-496a-b419-0c3b343ca7ca", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/8f5cd69c-721f-496a-b419-0c3b343ca7ca", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "8f5cd69c-721f-496a-b419-0c3b343ca7ca", + "OS-EXT-IMG-SIZE:size": 344457216, + "name": "CentOS-6.5-x86_64", + "created": "2015-09-08T03:56:45Z", + "minDisk": 0, + "progress": 100, + "minRam": 0, + "metadata": {} + }, + { + "status": "ACTIVE", + "updated": "2015-09-08T03:56:51Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/bba418d0-21b4-45db-a646-12a8ddc265f1", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/bba418d0-21b4-45db-a646-12a8ddc265f1", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/bba418d0-21b4-45db-a646-12a8ddc265f1", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "bba418d0-21b4-45db-a646-12a8ddc265f1", + "OS-EXT-IMG-SIZE:size": 256180736, + "name": "Ubuntu-14.04-amd64", + "created": "2015-09-08T03:56:44Z", + "minDisk": 0, + "progress": 100, + "minRam": 0, + "metadata": {} + }, + { + "status": "ACTIVE", + "updated": "2015-09-08T03:56:47Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/be75c519-a938-41e1-88bb-2af6d9e9c962", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/be75c519-a938-41e1-88bb-2af6d9e9c962", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/be75c519-a938-41e1-88bb-2af6d9e9c962", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "be75c519-a938-41e1-88bb-2af6d9e9c962", + "OS-EXT-IMG-SIZE:size": 255197184, + "name": "Ubuntu-12.04-amd64", + "created": "2015-09-08T03:56:42Z", + "minDisk": 0, + "progress": 100, + "minRam": 0, + "metadata": {} + }, + { + "status": "ACTIVE", + "updated": "2015-09-08T03:53:01Z", + "links": [ + { + "href": "http://nova-osp7/v2/94b7d98054db4d4eb5734e4a370805c7/images/24a1cc8f-7c58-404d-99a2-13931b59024c", + "rel": "self" + }, + { + "href": "http://nova-osp7/94b7d98054db4d4eb5734e4a370805c7/images/24a1cc8f-7c58-404d-99a2-13931b59024c", + "rel": "bookmark" + }, + { + "href": "http://148.9.210.226:9292/images/24a1cc8f-7c58-404d-99a2-13931b59024c", + "type": "application/vnd.openstack.image", + "rel": "alternate" + } + ], + "id": "24a1cc8f-7c58-404d-99a2-13931b59024c", + "OS-EXT-IMG-SIZE:size": 13200896, + "name": "cirros", + "created": "2015-09-08T03:52:58Z", + "minDisk": 0, + "progress": 100, + "minRam": 0, + "metadata": {} } - ], - "schema": "/v2/schemas/images", - "first": "/v2/images" + ] } \ No newline at end of file From aa7c8534ddc456d1a386a0141f5292da5012e1fa Mon Sep 17 00:00:00 2001 From: mariapavlova Date: Tue, 16 Feb 2016 16:17:44 +0000 Subject: [PATCH 6/7] Exceptions --- .../nova/os/compute/CinderVolume.java | 6 +++--- .../openstack/nova/os/compute/NovaServer.java | 18 +++++++++--------- .../rackspace/lb/RackspaceLoadBalancers.java | 12 ++++++------ .../os/network/LoadBalancerSupportImpl.java | 2 +- .../nova/os/network/NovaFloatingIP.java | 4 ++-- .../nova/os/network/NovaSecurityGroup.java | 4 ++-- .../openstack/nova/os/network/Quantum.java | 4 ++-- .../nova/os/storage/SwiftBlobStore.java | 6 +++--- 8 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java index 353f822..b9f2507 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java @@ -153,7 +153,7 @@ else if( getMaximumVolumeSize() != null && size.intValue() > getMaximumVolumeSiz } } logger.error("create(): No volume was created by the create attempt, and no error was returned"); - throw new ResourceNotFoundException("No volume was created"); + throw new ResourceNotFoundException("volume", options.getVolumeProductId()); } finally { @@ -168,10 +168,10 @@ public void detach(@Nonnull String volumeId, boolean force) throws InternalExcep Volume volume = getVolume(volumeId); if( volume == null ) { - throw new ResourceNotFoundException("No such volume: " + volumeId); + throw new ResourceNotFoundException("volume", volumeId); } if( volume.getProviderVirtualMachineId() == null ) { - throw new ResourceNotFoundException("Volume " + volumeId + " is not attached"); + throw new ResourceNotFoundException("Volume ", volumeId + " is not attached"); } NovaMethod method = new NovaMethod(getProvider()); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java index 5345f48..4df10c7 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/NovaServer.java @@ -159,7 +159,7 @@ protected Platform getPlatform(String vmName, String vmDescription, String image VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new ResourceNotFoundException("No such virtual machine: " + vmId); + throw new ResourceNotFoundException("vm", vmId); } Map json = new HashMap<>(); @@ -386,7 +386,7 @@ protected void prepareVlanForLaunch(VMLaunchOptions options, Map try { MachineImage targetImage = getImage(options.getMachineImageId()); if( targetImage == null ) { - throw new ResourceNotFoundException("No such machine image: " + options.getMachineImageId()); + throw new ResourceNotFoundException("machine image: ", options.getMachineImageId()); } //Additional LPAR Call boolean isBareMetal = isBareMetal(options.getMachineImageId()); @@ -616,7 +616,7 @@ else if( name.equals(fw.getName()) ) { return listFirewalls(vmId, server); } - throw new ResourceNotFoundException("No such server found for " + vmId); + throw new ResourceNotFoundException("server", vmId); } catch( JSONException e ) { logger.error("listFirewalls(): Unable to identify expected values in JSON: " + e.getMessage()); @@ -845,7 +845,7 @@ public void pause(@Nonnull String vmId) throws InternalException, CloudException VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new ResourceNotFoundException("No such virtual machine found for " + vmId); + throw new ResourceNotFoundException("vm", vmId); } if( !getCapabilities().supportsPause() ) { throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName()); @@ -868,7 +868,7 @@ public void resume(@Nonnull String vmId) throws InternalException, CloudExceptio VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new ResourceNotFoundException("No such virtual machine found for " + vmId); + throw new ResourceNotFoundException("vm", vmId); } if( !getCapabilities().supportsResume() ) { throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName()); @@ -891,7 +891,7 @@ public void start(@Nonnull String vmId) throws InternalException, CloudException VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new ResourceNotFoundException("No such virtual machine found for " + vmId); + throw new ResourceNotFoundException("vm", vmId); } if( !getCapabilities().supportsStart() ) { throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName()); @@ -914,7 +914,7 @@ public void stop(@Nonnull String vmId, boolean force) throws InternalException, VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new ResourceNotFoundException("No such virtual machine found for " + vmId); + throw new ResourceNotFoundException("vm", vmId); } if( !getCapabilities().supportsStop() ) { throw new OperationNotSupportedException("Start/stop is not supported in " + getProvider().getCloudName()); @@ -937,7 +937,7 @@ public void suspend(@Nonnull String vmId) throws InternalException, CloudExcepti VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new ResourceNotFoundException("No such virtual machine found for " + vmId); + throw new ResourceNotFoundException("vm", vmId); } if( !getCapabilities().supportsSuspend() ) { throw new OperationNotSupportedException("Suspend/resume is not supported in " + getProvider().getCloudName()); @@ -960,7 +960,7 @@ public void unpause(@Nonnull String vmId) throws InternalException, CloudExcepti VirtualMachine vm = getVirtualMachine(vmId); if( vm == null ) { - throw new ResourceNotFoundException("No such virtual machine found for " + vmId); + throw new ResourceNotFoundException("vm", vmId); } if( !getCapabilities().supportsUnPause() ) { throw new OperationNotSupportedException("Pause/unpause is not supported in " + getProvider().getCloudName()); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLoadBalancers.java b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLoadBalancers.java index f598031..dbd9141 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLoadBalancers.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/ext/rackspace/lb/RackspaceLoadBalancers.java @@ -200,7 +200,7 @@ public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String... serv if( vm == null ) { logger.error("addServers(): Failed to add " + id + " because it does not exist"); - throw new ResourceNotFoundException("No such server: " + id); + throw new ResourceNotFoundException("server", id); } String address = null; @@ -216,7 +216,7 @@ public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String... serv } if( address == null ) { logger.error("addServers(): No address exists for mapping the load balancer to this server"); - throw new ResourceNotFoundException("The virtual machine " + id + " has no mappable addresses"); + throw new ResourceNotFoundException("The virtual machine ", id + " has no mappable addresses"); } if( logger.isDebugEnabled() ) { logger.debug("addServers(): Mapping IP is: " + address); @@ -875,14 +875,14 @@ public void removeIPEndpoints(@Nonnull String fromLoadBalancerId, @Nonnull Strin LoadBalancer lb = getLoadBalancer(fromLoadBalancerId); if( lb == null || LoadBalancerState.TERMINATED.equals(lb.getCurrentState()) ) { - throw new ResourceNotFoundException("No such load balancer: " + fromLoadBalancerId); + throw new ResourceNotFoundException("load balancer", fromLoadBalancerId); } while( LoadBalancerState.PENDING.equals(lb.getCurrentState()) ) { try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } lb = getLoadBalancer(fromLoadBalancerId); if( lb == null || LoadBalancerState.TERMINATED.equals(lb.getCurrentState()) ) { - throw new ResourceNotFoundException("No such load balancer: " + fromLoadBalancerId); + throw new ResourceNotFoundException("load balancer", fromLoadBalancerId); } } @@ -916,14 +916,14 @@ public void removeServers(@Nonnull String fromLoadBalancerId, @Nonnull String... LoadBalancer lb = getLoadBalancer(fromLoadBalancerId); if( lb == null || LoadBalancerState.TERMINATED.equals(lb.getCurrentState()) ) { - throw new ResourceNotFoundException("No such load balancer: " + fromLoadBalancerId); + throw new ResourceNotFoundException("load balancer", fromLoadBalancerId); } while( LoadBalancerState.PENDING.equals(lb.getCurrentState()) ) { try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } lb = getLoadBalancer(fromLoadBalancerId); if( lb == null || LoadBalancerState.TERMINATED.equals(lb.getCurrentState()) ) { - throw new ResourceNotFoundException("No such load balancer: " + fromLoadBalancerId); + throw new ResourceNotFoundException("load balancer", fromLoadBalancerId); } } diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java index 1c26ef2..815b312 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/LoadBalancerSupportImpl.java @@ -156,7 +156,7 @@ public boolean isSubscribed() throws CloudException, InternalException { } } logger.error("create(): Method executed successfully, but no load balancer was found in JSON"); - throw new ResourceNotFoundException("Method executed successfully, but no load balancer was found in JSON"); + throw new GeneralCloudException("Method executed successfully, but no load balancer was found in JSON", CloudErrorType.GENERAL); } catch( JSONException e ) { logger.error("create(): Failed to identify a load balancer ID in the cloud response: " + e.getMessage()); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaFloatingIP.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaFloatingIP.java index ef7f84d..bcdfb22 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaFloatingIP.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaFloatingIP.java @@ -87,7 +87,7 @@ public void assign(@Nonnull String addressId, @Nonnull String serverId) throws I IpAddress addr = getIpAddress(addressId); if( addr == null ) { - throw new ResourceNotFoundException("No such IP address: " + addressId); + throw new ResourceNotFoundException("IP", addressId); } //action.put("server", serverId); action.put("address",addr.getRawAddress().getIpAddress()); @@ -420,7 +420,7 @@ public void releaseFromServer(@Nonnull String addressId) throws InternalExceptio IpAddress addr = getIpAddress(addressId); if( addr == null ) { - throw new ResourceNotFoundException("No such IP address: " + addressId); + throw new ResourceNotFoundException("IP", addressId); } String serverId = addr.getServerId(); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java index 64cba79..53ffe04 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java @@ -100,7 +100,7 @@ public class NovaSecurityGroup extends AbstractFirewallSupport { Firewall targetGroup = getFirewall(sourceEndpoint.getProviderFirewallId()); if( targetGroup == null ) { - throw new ResourceNotFoundException("No such source endpoint firewall: " + sourceEndpoint.getProviderFirewallId()); + throw new ResourceNotFoundException("firewall", sourceEndpoint.getProviderFirewallId()); } json.put("group_id", targetGroup.getProviderFirewallId()); @@ -605,7 +605,7 @@ else if( t.getRuleTargetType().equals(RuleTargetType.GLOBAL) && source.equals(t. } } if( targetRule == null ) { - throw new ResourceNotFoundException("No such firewall rule"); + throw new ResourceNotFoundException("firewall rule", targetRule.getFirewallId()); } revoke(targetRule.getProviderRuleId()); } diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/Quantum.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/Quantum.java index 2efc98c..b815d48 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/Quantum.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/Quantum.java @@ -167,7 +167,7 @@ public QuantumType getNetworkType() throws CloudException, InternalException { if (vlan != null) { throw new InternalException("Cannot launch into the network without a subnet"); } - throw new ResourceNotFoundException("Invalid id no network or subnet found for " + subnetId); + throw new ResourceNotFoundException("subnet", subnetId); } Map wrapper = new HashMap(); Map json = new HashMap(); @@ -342,7 +342,7 @@ public QuantumType getNetworkType() throws CloudException, InternalException { VLAN vlan = getVlan(options.getProviderVlanId()); if( vlan == null ) { - throw new ResourceNotFoundException("No such VLAN: " + options.getProviderVlanId()); + throw new ResourceNotFoundException("VLAN: ", options.getProviderVlanId()); } Map wrapper = new HashMap(); diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java b/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java index 95ba7c0..73b3db9 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java @@ -215,7 +215,7 @@ public String getSignedObjectUrl(@Nonnull String bucket, @Nonnull String object, APITrace.begin(getProvider(), "Blob.getObjectSize"); try { if( bucket == null ) { - throw new ResourceNotFoundException("No such object: " + bucket ); + throw new ResourceNotFoundException("No such object: ", bucket ); } if( object == null ) { return null; @@ -288,7 +288,7 @@ protected void get(@Nullable String bucket, @Nonnull String location, @Nonnull F APITrace.begin(getProvider(), "Blob.get"); try { if( bucket == null ) { - throw new ResourceNotFoundException("No such object: " + bucket + "/" + location); + throw new ResourceNotFoundException("No such object: ", bucket + "/" + location); } if( toFile.exists() ) { if( !toFile.delete() ) { @@ -300,7 +300,7 @@ protected void get(@Nullable String bucket, @Nonnull String location, @Nonnull F input = method.get(bucket, location); if( input == null ) { - throw new ResourceNotFoundException("No such object: " + bucket + "/" + location); + throw new ResourceNotFoundException("No such object: ", bucket + "/" + location); } try { copy(input, new FileOutputStream(toFile), transfer); From fcedb56ee77c1d109c030088d4c170535896e2ba Mon Sep 17 00:00:00 2001 From: mariapavlova Date: Wed, 4 May 2016 11:10:53 +0100 Subject: [PATCH 7/7] Tests --- pom.xml | 22 +- .../nova/os/compute/CinderSnapshot.java | 6 +- .../nova/os/compute/CinderVolume.java | 36 +- .../nova/os/identity/NovaKeypair.java | 2 +- .../nova/os/storage/SwiftBlobStore.java | 6 +- .../nova/os/compute/CinderSnapshotTest.java | 326 +++++++++++++++ .../nova/os/compute/CinderVolumeTest.java | 375 ++++++++++++++++++ .../nova/os/compute/NovaImageTest.java | 1 + .../nova/os/identity/NovaKeypairTest.java | 194 +++++++++ .../nova/os/storage/SwiftBlobStoreTest.java | 260 ++++++++++++ .../nova/fixtures/compute/create_keypair.json | 8 + .../fixtures/compute/create_snapshot.json | 11 + .../nova/fixtures/compute/create_volume.json | 27 ++ .../nova/fixtures/compute/get_keypair.json | 13 + .../nova/fixtures/compute/get_snapshot.json | 11 + .../nova/fixtures/compute/get_volume.json | 27 ++ .../nova/fixtures/compute/list_keypairs.json | 11 + .../nova/fixtures/compute/list_snapshot.json | 26 ++ .../fixtures/compute/list_volume_types.json | 16 + .../nova/fixtures/compute/list_volumes.json | 41 ++ 20 files changed, 1396 insertions(+), 23 deletions(-) create mode 100644 src/test/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshotTest.java create mode 100644 src/test/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolumeTest.java create mode 100644 src/test/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypairTest.java create mode 100644 src/test/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStoreTest.java create mode 100644 src/test/resources/nova/fixtures/compute/create_keypair.json create mode 100644 src/test/resources/nova/fixtures/compute/create_snapshot.json create mode 100644 src/test/resources/nova/fixtures/compute/create_volume.json create mode 100644 src/test/resources/nova/fixtures/compute/get_keypair.json create mode 100644 src/test/resources/nova/fixtures/compute/get_snapshot.json create mode 100644 src/test/resources/nova/fixtures/compute/get_volume.json create mode 100644 src/test/resources/nova/fixtures/compute/list_keypairs.json create mode 100644 src/test/resources/nova/fixtures/compute/list_snapshot.json create mode 100644 src/test/resources/nova/fixtures/compute/list_volume_types.json create mode 100644 src/test/resources/nova/fixtures/compute/list_volumes.json diff --git a/pom.xml b/pom.xml index 7edf6d1..a4f8db4 100644 --- a/pom.xml +++ b/pom.xml @@ -110,13 +110,31 @@ org.powermock powermock-module-junit4 - 1.5.6 + 1.5.5 test org.powermock powermock-api-mockito - 1.5.6 + 1.5.5 + test + + + com.hazelcast + hazelcast + 3.4 + test + + + com.hazelcast + hazelcast + 3.4 + test + + + com.hazelcast + hazelcast + 3.4 test diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshot.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshot.java index f67d270..0659d91 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshot.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshot.java @@ -104,7 +104,7 @@ public CinderSnapshot(NovaOpenStack provider) { } } logger.error("snapshot(): No snapshot was created by the create attempt, and no error was returned"); - throw new GeneralCloudException("No listener was created", CloudErrorType.GENERAL); + throw new GeneralCloudException("No snapshot was created", CloudErrorType.GENERAL); } finally { @@ -315,7 +315,7 @@ public void remove(@Nonnull String snapshotId) throws InternalException, CloudEx return new String[0]; } - private @Nullable Snapshot toSnapshot(@Nullable JSONObject json) throws CloudException, InternalException { + @Nullable Snapshot toSnapshot( @Nullable JSONObject json ) throws CloudException, InternalException { if( json == null ) { return null; } @@ -394,7 +394,7 @@ else if( status.equalsIgnoreCase("creating") ) { } } - private @Nullable ResourceStatus toStatus(@Nullable JSONObject json) throws CloudException, InternalException { + protected @Nullable ResourceStatus toStatus(@Nullable JSONObject json) throws CloudException, InternalException { if( json == null ) { return null; } diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java index b9f2507..a6bef9e 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolume.java @@ -62,7 +62,7 @@ public CinderVolume(@Nonnull NovaOpenStack provider) { super(provider); } - private @Nonnull String getAttachmentsResource() { + @Nonnull String getAttachmentsResource() { return "os-volume_attachments"; } @@ -72,7 +72,7 @@ public CinderVolume(@Nonnull NovaOpenStack provider) { // return ((getProvider()).isHP() ? "/os-volumes" : "/volumes"); } - private @Nonnull String getTypesResource() { + @Nonnull String getTypesResource() { return "/types"; } @@ -117,11 +117,11 @@ public void attach(@Nonnull String volumeId, @Nonnull String toServer, @Nonnull Storage size = options.getVolumeSize(); - if( size == null || (size.intValue() < getMinimumVolumeSize().intValue()) ) { - size = getMinimumVolumeSize(); + if( size == null || (size.intValue() < getCapabilities().getMinimumVolumeSize().intValue()) ) { + size = getCapabilities().getMinimumVolumeSize(); } - else if( getMaximumVolumeSize() != null && size.intValue() > getMaximumVolumeSize().intValue() ) { - size = getMaximumVolumeSize(); + else if( getCapabilities().getMaximumVolumeSize() != null && size.intValue() > getCapabilities().getMaximumVolumeSize().intValue() ) { + size = getCapabilities().getMaximumVolumeSize(); } json.put("size", size.intValue()); if( options.getSnapshotId() != null ) { @@ -218,15 +218,23 @@ public VolumeCapabilities getCapabilities() throws CloudException, InternalExcep } } + private Iterable getCachedProducts() throws InternalException { + Cache cache = Cache.getInstance(getProvider(), "volumeProducts", VolumeProduct.class, CacheLevel.REGION_ACCOUNT); + return cache.get(getContext()); + } + + private void saveProductsToCache(Iterable products) throws InternalException { + Cache cache = Cache.getInstance(getProvider(), "volumeProducts", VolumeProduct.class, CacheLevel.REGION_ACCOUNT); + cache.put(getContext(), products); + } + @Override public @Nonnull Iterable listVolumeProducts() throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.listVolumeProducts"); try { - Cache cache = Cache.getInstance(getProvider(), "volumeProducts", VolumeProduct.class, CacheLevel.REGION_ACCOUNT); - Iterable current = cache.get(getContext()); - - if( current != null ) { - return current; + Iterable cached = getCachedProducts(); + if( cached != null ) { + return cached; } NovaMethod method = new NovaMethod(getProvider()); List products = new ArrayList<>(); @@ -273,7 +281,7 @@ public VolumeCapabilities getCapabilities() throws CloudException, InternalExcep throw new CommunicationException("Unable to understand listVolumes response: " + e.getMessage(), e); } } - cache.put(getContext(), Collections.unmodifiableList(products)); + saveProductsToCache(products); return products; } finally { @@ -409,7 +417,7 @@ public void remove(@Nonnull String volumeId) throws InternalException, CloudExce } } - private @Nullable ResourceStatus toStatus(@Nullable JSONObject json) throws CloudException, InternalException { + protected @Nullable ResourceStatus toStatus(@Nullable JSONObject json) throws CloudException, InternalException { if( json == null ) { return null; } @@ -454,7 +462,7 @@ else if( status.equals("attaching") ) { } } - private @Nullable Volume toVolume(@Nullable JSONObject json, @Nonnull Iterable types) throws CloudException, InternalException { + protected @Nullable Volume toVolume(@Nullable JSONObject json, @Nonnull Iterable types) throws CloudException, InternalException { if( json == null ) { return null; } diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypair.java b/src/main/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypair.java index d594fa3..b838c8c 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypair.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypair.java @@ -306,7 +306,7 @@ public boolean isSubscribed() throws InternalException, CloudException { return new String[0]; } - private @Nullable SSHKeypair toKeypair(@Nullable JSONObject json) throws InternalException, CloudException { + protected @Nullable SSHKeypair toKeypair(@Nullable JSONObject json) throws InternalException, CloudException { if( json == null ) { return null; } diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java b/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java index 73b3db9..664451b 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStore.java @@ -125,7 +125,7 @@ public BlobStoreCapabilities getCapabilities() throws CloudException, InternalEx } } - private void createBucket(@Nonnull String name) throws InternalException, CloudException { + protected void createBucket(@Nonnull String name) throws InternalException, CloudException { APITrace.begin(getProvider(), "Blob.createBucket"); try { try { @@ -239,7 +239,7 @@ public String getSignedObjectUrl(@Nonnull String bucket, @Nonnull String object, } } - private @Nonnull String findFreeName(@Nonnull String bucket) throws InternalException, CloudException { + protected @Nonnull String findFreeName(@Nonnull String bucket) throws InternalException, CloudException { int idx = bucket.lastIndexOf("."); String prefix, rawName; @@ -314,7 +314,7 @@ protected void get(@Nullable String bucket, @Nonnull String location, @Nonnull F } } - private long getMetaDataLength(@Nonnull Map meta) { + protected long getMetaDataLength(@Nonnull Map meta) { return getMetaDataLong("Content-Length", meta); } diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshotTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshotTest.java new file mode 100644 index 0000000..98f6222 --- /dev/null +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/CinderSnapshotTest.java @@ -0,0 +1,326 @@ +package org.dasein.cloud.openstack.nova.os.compute; + +import org.dasein.cloud.*; +import org.dasein.cloud.compute.*; +import org.dasein.cloud.openstack.nova.os.NovaMethod; +import org.dasein.cloud.openstack.nova.os.NovaOpenStack; +import org.dasein.cloud.openstack.nova.os.OpenStackProvider; +import org.dasein.cloud.openstack.nova.os.OpenStackTest; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.Iterator; +import java.util.List; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.when; +import static org.powermock.api.mockito.PowerMockito.whenNew; + +/** + * Created by mariapavlova on 06/04/2016. + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(CinderSnapshot.class) +public class CinderSnapshotTest extends OpenStackTest { + private NovaMethod method; + private Snapshot snapshot; + private NovaServer vmSupport; + private CinderSnapshot snapshotSupport; + private NovaComputeServices computeServices; + private NovaOpenStack provider; + + private String testRegionId = "testRegionId"; + private String testOwnerId = "5ef70662f8b34079a6eddb8da9d75fe8"; + private String testSnapshotId = "3fbbcccf-d058-4502-8844-6feeffdf4cb5"; + private String testName = "snap-001"; + private String testDescription = "Daily backup"; + private String testVolumeId = "testVolumeId"; + + @Before + public void setUp() throws Exception { + provider = PowerMockito.mock(NovaOpenStack.class); + try { + PowerMockito.when(provider.isPostCactus()).thenReturn(true); + PowerMockito.when(provider.getCloudProvider()).thenReturn(OpenStackProvider.OTHER); + } + catch( CloudException | InternalException e ) { + e.printStackTrace(); + fail(); + } + ProviderContext context = PowerMockito.mock(ProviderContext.class); + PowerMockito.when(context.getRegionId()).thenReturn(testRegionId); + PowerMockito.when(context.getAccountNumber()).thenReturn(testOwnerId); + + snapshotSupport = PowerMockito.mock(CinderSnapshot.class); + + try { + PowerMockito.doReturn(provider).when(snapshotSupport, "getProvider"); + PowerMockito.doReturn(context).when(snapshotSupport, "getContext"); + } + catch( Exception e ) { + e.printStackTrace(); + fail("Exception occurred " + e.getMessage()); + } + + vmSupport = PowerMockito.mock(NovaServer.class); + method = PowerMockito.mock(NovaMethod.class); + snapshot = PowerMockito.mock(Snapshot.class); + try { + whenNew(NovaMethod.class).withAnyArguments().thenReturn(method); + } + catch( Exception e ) { + e.printStackTrace(); + fail("Couldn't create a mock for NovaMethod construction"); + } + } + + + @Test public void testCreateSnapshot() throws Exception { + JSONObject json = readJson("nova/fixtures/compute/create_snapshot.json"); + when(snapshotSupport.createSnapshot(any(SnapshotCreateOptions.class))).thenCallRealMethod(); + when(method.postString(anyString(), anyString(), anyString(), any(JSONObject.class), anyBoolean())) + .thenReturn(json); + when(snapshotSupport.toSnapshot(any(JSONObject.class))).thenCallRealMethod(); + SnapshotCreateOptions options = SnapshotCreateOptions.getInstanceForCreate(testVolumeId, testName, testDescription); + String snapshotId = snapshotSupport.createSnapshot(options); + assertEquals("Returned snapshot id is not as expected", testSnapshotId, snapshotId); + } + + @Test public void testGetCapabilities() throws Exception { + when(snapshotSupport.getCapabilities()).thenCallRealMethod(); + assertNotNull("Capabilities cannot be null", snapshotSupport.getCapabilities()); + } + + @Test public void testGetSnapshot() throws Exception { + JSONObject json = readJson("nova/fixtures/compute/get_snapshot.json"); + when(snapshotSupport.getSnapshot(anyString())).thenCallRealMethod(); + when(method.getResource(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(json); + when(snapshotSupport.toSnapshot(any(JSONObject.class))).thenCallRealMethod(); + Snapshot snapshot = snapshotSupport.getSnapshot(testSnapshotId); + assertNotNull("Returned snapshot cannot be null", snapshot); + assertEquals("Returned snapshot id is not as expected", testSnapshotId, snapshot.getProviderSnapshotId()); + assertEquals("Returned snapshot name is not as expected", testName, snapshot.getName()); + assertEquals("Returned snapshot description is not as expected", testDescription, snapshot.getDescription()); + } + + @Test public void testListSnapshotStatus() throws Exception { + JSONObject json = readJson("nova/fixtures/compute/list_snapshot.json"); + when(method.getResource(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(json); + when(snapshotSupport.listSnapshotStatus()).thenCallRealMethod(); + ResourceStatus dummy = new ResourceStatus("dummy", MachineImageState.ACTIVE); + when(snapshotSupport.toStatus(any(JSONObject.class))).thenReturn(dummy); + //when(snapshotSupport.toSnapshot(any(JSONObject.class))).thenCallRealMethod(); + + Iterator resourceStatuses = snapshotSupport.listSnapshotStatus().iterator(); + verify(snapshotSupport, times(2)).toStatus(any(JSONObject.class)); + int count = 0; + while( resourceStatuses.hasNext() ) { + count++; + resourceStatuses.next(); + } + assertEquals("The number of returned objects is incorrect", 2, count); + + } + + @Test public void testIsPublic() throws Exception { + when(snapshotSupport.isPublic(anyString())).thenCallRealMethod(); + assertFalse("All snapshots are private in Openstack", snapshotSupport.isPublic(testSnapshotId)); + } + + @Test public void testIsSubscribed() throws Exception { + + } + + @Test public void testListSnapshots() throws Exception { + JSONObject json = readJson("nova/fixtures/compute/list_snapshot.json"); + when(method.getResource(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(json); + when(snapshotSupport.listSnapshots()).thenCallRealMethod(); + Snapshot dummy = new Snapshot(); + when(snapshotSupport.toSnapshot(any(JSONObject.class))).thenReturn(dummy); + + Iterator snapshotIterator = snapshotSupport.listSnapshots().iterator(); + verify(snapshotSupport, times(2)).toSnapshot(any(JSONObject.class)); + int count = 0; + while( snapshotIterator.hasNext() ) { + count++; + snapshotIterator.next(); + } + assertEquals("The number of returned objects is incorrect", 2, count); + + + } + + @Test public void testRemove() throws Exception { + Snapshot snapshot = new Snapshot(); + Snapshot deletedSnapshot = new Snapshot(); + snapshot.setCurrentState(SnapshotState.AVAILABLE); + deletedSnapshot.setCurrentState(SnapshotState.DELETED); + snapshot.setProviderSnapshotId("testSnapshotId"); + + Mockito.doCallRealMethod().when(snapshotSupport).remove(anyString()); + when(snapshotSupport.getSnapshot(anyString())).thenReturn(snapshot, deletedSnapshot); + Mockito.doNothing().when(method).deleteResource(anyString(), anyString(), anyString(), anyString()); + + snapshotSupport.remove(testSnapshotId); + + ArgumentCaptor snapshotIdArg = ArgumentCaptor.forClass(String.class); + verify(method).deleteResource(anyString(), anyString(), snapshotIdArg.capture(), anyString()); + assertEquals("Snapshot Id passed to the method is not as expected", testSnapshotId, snapshotIdArg.getValue()); + // assertEquals("Current state is incorrect", MachineImageState.ACTIVE, image.getCurrentState()); + + } + + @Test public void testSearchSnapshots() throws Exception { + JSONObject json = readJson("nova/fixtures/compute/list_snapshot.json"); + when(method.getResource(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(json); + when(snapshotSupport.searchSnapshots(any(SnapshotFilterOptions.class))).thenCallRealMethod(); + Snapshot dummy = new Snapshot(); + when(snapshotSupport.toSnapshot(any(JSONObject.class))).thenReturn(dummy); + + Iterator snapshotIterator = snapshotSupport.searchSnapshots(SnapshotFilterOptions.getInstance()).iterator(); + verify(snapshotSupport, times(2)).toSnapshot(any(JSONObject.class)); + int count = 0; + while( snapshotIterator.hasNext() ) { + count++; + snapshotIterator.next(); + } + assertEquals("The number of returned objects is incorrect", 2, count); + } + + @Test + public void testSetTags() throws Exception { + // prepare + Mockito.doCallRealMethod().when(snapshotSupport).setTags(anyString(), any(Tag.class), any(Tag.class)); + Tag[] tags = { new Tag("a", "aa"), new Tag("b", "bb") } ; + + // run + snapshotSupport.setTags(testSnapshotId, tags); + + // verify + ArgumentCaptor serviceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + ArgumentCaptor tag2Capt = ArgumentCaptor.forClass(Tag.class); + verify(provider).createTags(serviceIdCapt.capture(), resourceCapt.capture(), resourceIdCapt.capture(), tag1Capt.capture(), tag2Capt.capture()); + assertEquals("Service id is incorrect", CinderSnapshot.SERVICE, serviceIdCapt.getValue()); + assertEquals("Resource is incorrect", "/snapshots", resourceCapt.getValue()); + assertEquals("Resource id is incorrect", testSnapshotId, resourceIdCapt.getValue()); + assertArrayEquals("Tags are incorrect", tags, new Tag[] { tag1Capt.getValue(), tag2Capt.getValue() } ); + } + + @Test + public void testSetTags1() throws Exception { + // prepare + Mockito.doCallRealMethod().when(snapshotSupport).setTags(any(String[].class), any(Tag.class)); + Tag tag = new Tag("a", "aa"); + String anotherSnapshotId = "anotherTestId"; + + // run + snapshotSupport.setTags(new String[] {testSnapshotId, anotherSnapshotId}, tag); + + // verify + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + verify(snapshotSupport, times(2)).setTags(resourceIdCapt.capture(), tag1Capt.capture()); + List idValues = resourceIdCapt.getAllValues(); + assertArrayEquals("Resource ids were not correct", new String[]{testSnapshotId, anotherSnapshotId}, + idValues.toArray(new String[idValues.size()])); + assertEquals("Tag was not correct", tag, tag1Capt.getValue()); + } + + @Test + public void testUpdateTags() throws Exception { + // prepare + Mockito.doCallRealMethod().when(snapshotSupport).updateTags(anyString(), any(Tag.class), any(Tag.class)); + Tag[] tags = { new Tag("a", "aa"), new Tag("b", "bb") } ; + + // run + snapshotSupport.updateTags(testSnapshotId, tags); + + // verify + ArgumentCaptor serviceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + ArgumentCaptor tag2Capt = ArgumentCaptor.forClass(Tag.class); + verify(provider).updateTags(serviceIdCapt.capture(), resourceCapt.capture(), resourceIdCapt.capture(), tag1Capt.capture(), tag2Capt.capture()); + assertEquals("Service id is incorrect", CinderSnapshot.SERVICE, serviceIdCapt.getValue()); + assertEquals("Resource is incorrect", "/snapshots", resourceCapt.getValue()); + assertEquals("Resource id is incorrect", testSnapshotId, resourceIdCapt.getValue()); + assertArrayEquals("Tags are incorrect", tags, new Tag[] { tag1Capt.getValue(), tag2Capt.getValue() } ); + } + + @Test public void testUpdateTags1() throws Exception { + // prepare + Mockito.doCallRealMethod().when(snapshotSupport).updateTags(any(String[].class), any(Tag.class)); + Tag tag = new Tag("a", "aa"); + String anotherId = "anotherTestId"; + + // run + snapshotSupport.updateTags(new String[] {testSnapshotId, anotherId}, tag); + + // verify + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + verify(snapshotSupport, times(2)).updateTags(resourceIdCapt.capture(), tag1Capt.capture()); + List imageIdValues = resourceIdCapt.getAllValues(); + assertArrayEquals("Resource ids were not correct", new String[]{testSnapshotId, anotherId}, + imageIdValues.toArray(new String[imageIdValues.size()])); + assertEquals("Tag was not correct", tag, tag1Capt.getValue()); + } + + @Test + public void testRemoveTags() throws Exception { + // prepare + Mockito.doCallRealMethod().when(snapshotSupport).removeTags(anyString(), any(Tag.class), any(Tag.class)); + Tag[] tags = { new Tag("a", "aa"), new Tag("b", "bb") } ; + + // run + snapshotSupport.removeTags(testSnapshotId, tags); + + // verify + ArgumentCaptor serviceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + ArgumentCaptor tag2Capt = ArgumentCaptor.forClass(Tag.class); + verify(provider).removeTags(serviceIdCapt.capture(), resourceCapt.capture(), resourceIdCapt.capture(), tag1Capt.capture(), tag2Capt.capture()); + assertEquals("Service id is incorrect", CinderSnapshot.SERVICE, serviceIdCapt.getValue()); + assertEquals("Resource is incorrect", "/snapshots", resourceCapt.getValue()); + assertEquals("Resource id is incorrect", testSnapshotId, resourceIdCapt.getValue()); + assertArrayEquals("Tags are incorrect", tags, new Tag[] { tag1Capt.getValue(), tag2Capt.getValue() } ); + + } + + @Test + public void testRemoveTags1() throws Exception { + // prepare + Mockito.doCallRealMethod().when(snapshotSupport).removeTags(any(String[].class), any(Tag.class)); + Tag tag = new Tag("a", "aa"); + String anotherId = "anotherTestId"; + + // run + snapshotSupport.removeTags(new String[] {testSnapshotId, anotherId}, tag); + + // verify + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + verify(snapshotSupport, times(2)).removeTags(resourceIdCapt.capture(), tag1Capt.capture()); + List idValues = resourceIdCapt.getAllValues(); + assertArrayEquals("Resource ids were not correct", new String[]{testSnapshotId, anotherId}, + idValues.toArray(new String[idValues.size()])); + assertEquals("Tag was not correct", tag, tag1Capt.getValue()); + }} \ No newline at end of file diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolumeTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolumeTest.java new file mode 100644 index 0000000..775ecf0 --- /dev/null +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/CinderVolumeTest.java @@ -0,0 +1,375 @@ +package org.dasein.cloud.openstack.nova.os.compute; + +import org.dasein.cloud.*; +import org.dasein.cloud.compute.*; +import org.dasein.cloud.openstack.nova.os.*; +import org.dasein.cloud.util.Cache; +import org.dasein.cloud.util.CacheLevel; +import org.dasein.util.uom.storage.Gigabyte; +import org.dasein.util.uom.storage.Storage; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.when; +import static org.powermock.api.mockito.PowerMockito.whenNew; + +/** + * Created by mariapavlova on 12/04/2016. + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest( { CinderVolume.class, Cache.class } ) +public class CinderVolumeTest extends OpenStackTest { + private NovaMethod method; + private CinderVolume volumeSupport; + private NovaOpenStack provider; + private AuthenticationContext authenticationContext; + + private static final String testRegionId = "testRegionId"; + private static final String testOwnerId = "5ef70662f8b34079a6eddb8da9d75fe8"; + private static final String testName = "vol-001"; + private static final String testDescription = "Another volume."; + private static final String testVolumeId = "521752a6-acf6-4b2d-bc7a-119f9148cd8c"; + private static final String testVmId = "testVmId"; + private static final VolumeProduct fakeProduct = VolumeProduct.getInstance(testVolumeId, testName, testDescription, VolumeType.HDD); + + @Before + public void setUp() throws Exception { + provider = PowerMockito.mock(NovaOpenStack.class); + try { + PowerMockito.when(provider.isPostCactus()).thenReturn(true); + PowerMockito.when(provider.getCloudProvider()).thenReturn(OpenStackProvider.OTHER); + /*Class cls = NovaOpenStack.class; + PowerMockito.when(provider.getClass()).thenReturn(cls);*/ + } + catch( CloudException | InternalException e ) { + e.printStackTrace(); + fail(); + } + ProviderContext context = PowerMockito.mock(ProviderContext.class); + PowerMockito.when(context.getRegionId()).thenReturn(testRegionId); + PowerMockito.when(context.getAccountNumber()).thenReturn(testOwnerId); + volumeSupport = PowerMockito.mock(CinderVolume.class); + + try { + PowerMockito.doReturn(provider).when(volumeSupport, "getProvider"); + PowerMockito.doReturn(context).when(volumeSupport, "getContext"); + } + catch( Exception e ) { + e.printStackTrace(); + fail("Exception occurred " + e.getMessage()); + } + + /*Cache noCache = PowerMockito.mock(Cache.class); + PowerMockito.when(Cache.getInstance(any(CloudProvider.class), anyString(), any(Class.class), any(CacheLevel.class))).thenReturn(noCache); + when(noCache.get(any(ProviderContext.class))).thenReturn(null);*/ + + method = PowerMockito.mock(NovaMethod.class); + try { + whenNew(NovaMethod.class).withAnyArguments().thenReturn(method); + } + catch( Exception e ) { + e.printStackTrace(); + fail("Couldn't create a mock for NovaMethod construction"); + } + } + + + + @Test public void testAttach() throws Exception { + + } + + @Test public void testCreateVolume() throws Exception { + JSONObject json = readJson("nova/fixtures/compute/create_volume.json"); + when(volumeSupport.createVolume(any(VolumeCreateOptions.class))).thenCallRealMethod(); + when(method.postString(anyString(), anyString(), anyString(), any(JSONObject.class), anyBoolean())) + .thenReturn(json); + when(volumeSupport.listVolumeProducts()).thenReturn(Arrays.asList(fakeProduct)); + when(volumeSupport.toVolume(any(JSONObject.class), any(Iterable.class))).thenCallRealMethod(); + when(volumeSupport.getCapabilities()).thenCallRealMethod(); + VolumeCreateOptions options = VolumeCreateOptions.getInstance(new Storage<>(30, Storage.GIGABYTE), testName, testDescription); + //run + String volumeId = volumeSupport.createVolume(options); + assertEquals("Returned volume id is not as expected", testVolumeId, volumeId); + } + + @Test public void testDetach() throws Exception { + // prepare + Volume fakeVolume = mock(Volume.class); + when(fakeVolume.getProviderVirtualMachineId()).thenReturn(testVmId); + when(volumeSupport.getVolume(anyString())).thenReturn(fakeVolume); + Mockito.doCallRealMethod().when(volumeSupport).detach(anyString(), anyBoolean()); + when(volumeSupport.getAttachmentsResource()).thenCallRealMethod(); + + // run + volumeSupport.detach(testVolumeId, false); + + // verify + ArgumentCaptor serviceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor suffixCapt = ArgumentCaptor.forClass(String.class); + verify(method).deleteResource(serviceIdCapt.capture(), resourceCapt.capture(), resourceIdCapt.capture(), suffixCapt.capture()); + assertEquals("Service id is incorrect", NovaServer.SERVICE, serviceIdCapt.getValue()); + assertEquals("Resource is incorrect", "/servers", resourceCapt.getValue()); + assertEquals("Resource id is incorrect", testVmId, resourceIdCapt.getValue()); + assertEquals("Suffix is incorrect", volumeSupport.getAttachmentsResource() + "/" + testVolumeId, suffixCapt.getValue() ); + } + + @Test public void testGetCapabilities() throws Exception { + when(volumeSupport.getCapabilities()).thenCallRealMethod(); + assertNotNull("Capabilities object cannot be null", volumeSupport.getCapabilities()); + } + + @Test public void testGetVolume() throws Exception { + // prepare + JSONObject json = readJson("nova/fixtures/compute/get_volume.json"); + when(method.getResource(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(json); + when(volumeSupport.getVolume(anyString())).thenCallRealMethod(); + when(volumeSupport.toVolume(any(JSONObject.class), any(Iterable.class))).thenCallRealMethod(); + when(volumeSupport.listVolumeProducts()).thenReturn(Arrays.asList(fakeProduct)); + + // run + Volume result = volumeSupport.getVolume(testVolumeId); + + // verify + assertNotNull("Returned object is not expected to be null", result); + assertEquals("Return object id is not as expected", "521752a6-acf6-4b2d-bc7a-119f9148cd8c", result.getProviderVolumeId()); + } + + @Test public void testListVolumeProducts() throws Exception { + // prepare + JSONObject json = readJson("nova/fixtures/compute/list_volume_types.json"); + when(method.getResource(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(json); + when(volumeSupport.listVolumeProducts()).thenCallRealMethod(); + when(volumeSupport.getTypesResource()).thenCallRealMethod(); + // run + Iterable result = volumeSupport.listVolumeProducts(); + + // verify + assertNotNull("Returned collection cannot be null", result); + int count = 0; + for( VolumeProduct product : result ) { + count ++; + } + assertEquals("Returned number of objects is not as expected", 2, count); + } + + @Test public void testListVolumeStatus() throws Exception { + + // prepare + JSONObject json = readJson("nova/fixtures/compute/list_volumes.json"); + when(method.getResource(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(json); + when(volumeSupport.listVolumeStatus()).thenCallRealMethod(); + when(volumeSupport.toStatus(any(JSONObject.class))).thenCallRealMethod(); + // run + Iterable result = volumeSupport.listVolumeStatus(); + + // verify + assertNotNull("Returned collection cannot be null", result); + int count = 0; + for( ResourceStatus product : result ) { + count ++; + } + assertEquals("Returned number of objects is not as expected", 2, count); + + } + + @Test public void testListVolumes() throws Exception { + + // prepare + JSONObject json = readJson("nova/fixtures/compute/list_volumes.json"); + when(method.getResource(anyString(), anyString(), anyString(), anyBoolean())).thenReturn(json); + when(volumeSupport.listVolumeProducts()).thenReturn(Arrays.asList(fakeProduct)); + when(volumeSupport.listVolumes()).thenCallRealMethod(); + when(volumeSupport.toVolume(any(JSONObject.class), any(Iterable.class))).thenCallRealMethod(); + + // run + Iterable result = volumeSupport.listVolumes(); + + // verify + assertNotNull("Returned collection cannot be null", result); + int count = 0; + for( Volume product : result ) { + count ++; + } + assertEquals("Returned number of objects is not as expected", 2, count); + + } + + @Test + public void testIsSubscribed() throws Exception { + AuthenticationContext context = mock(AuthenticationContext.class); + final String testServiceUrl = "testServiceUrl"; + + Mockito.when(provider.getAuthenticationContext()).thenReturn(context); + Mockito.when(context.getServiceUrl(anyString())).thenReturn(testServiceUrl); + when(volumeSupport.isSubscribed()).thenCallRealMethod(); + boolean test = volumeSupport.isSubscribed(); + assertTrue("Return value is incorrect", test); + + } + + @Test public void testRemove() throws Exception { + // prepare + Volume volume = new Volume(); + Volume deletedVolume = new Volume(); + volume.setCurrentState(VolumeState.PENDING); + deletedVolume.setCurrentState(VolumeState.DELETED); + volume.setProviderVolumeId("testVolumeId"); + + Mockito.doCallRealMethod().when(volumeSupport).remove(anyString()); + when(volumeSupport.getVolume(anyString())).thenReturn(volume, deletedVolume); + Mockito.doNothing().when(method).deleteResource(anyString(), anyString(), anyString(), anyString()); + // run + volumeSupport.remove(testVolumeId); + // verify + ArgumentCaptor volumeIdArg = ArgumentCaptor.forClass(String.class); + verify(method).deleteResource(anyString(), anyString(), volumeIdArg.capture(), anyString()); + assertEquals("Volume Id passed to the method is not as expected", testVolumeId, volumeIdArg.getValue()); + + } + + @Test + public void testSetTags() throws Exception { + // prepare + Mockito.doCallRealMethod().when(volumeSupport).setTags(anyString(), any(Tag.class), any(Tag.class)); + Tag[] tags = { new Tag("a", "aa"), new Tag("b", "bb") } ; + + // run + volumeSupport.setTags(testVolumeId, tags); + + // verify + ArgumentCaptor serviceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + ArgumentCaptor tag2Capt = ArgumentCaptor.forClass(Tag.class); + verify(provider).createTags(serviceIdCapt.capture(), resourceCapt.capture(), resourceIdCapt.capture(), tag1Capt.capture(), tag2Capt.capture()); + assertEquals("Service id is incorrect", CinderVolume.SERVICE, serviceIdCapt.getValue()); + assertEquals("Resource is incorrect", "/volumes", resourceCapt.getValue()); + assertEquals("Resource id is incorrect", testVolumeId, resourceIdCapt.getValue()); + assertArrayEquals("Tags are incorrect", tags, new Tag[] { tag1Capt.getValue(), tag2Capt.getValue() } ); + } + + @Test + public void testSetTags1() throws Exception { + // prepare + Mockito.doCallRealMethod().when(volumeSupport).setTags(any(String[].class), any(Tag.class)); + Tag tag = new Tag("a", "aa"); + String anotherSnapshotId = "anotherTestId"; + + // run + volumeSupport.setTags(new String[] {testVolumeId, anotherSnapshotId}, tag); + + // verify + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + verify(volumeSupport, times(2)).setTags(resourceIdCapt.capture(), tag1Capt.capture()); + List idValues = resourceIdCapt.getAllValues(); + assertArrayEquals("Resource ids were not correct", new String[]{testVolumeId, anotherSnapshotId}, + idValues.toArray(new String[idValues.size()])); + assertEquals("Tag was not correct", tag, tag1Capt.getValue()); + } + + @Test + public void testUpdateTags() throws Exception { + // prepare + Mockito.doCallRealMethod().when(volumeSupport).updateTags(anyString(), any(Tag.class), any(Tag.class)); + Tag[] tags = { new Tag("a", "aa"), new Tag("b", "bb") } ; + + // run + volumeSupport.updateTags(testVolumeId, tags); + + // verify + ArgumentCaptor serviceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + ArgumentCaptor tag2Capt = ArgumentCaptor.forClass(Tag.class); + verify(provider).updateTags(serviceIdCapt.capture(), resourceCapt.capture(), resourceIdCapt.capture(), tag1Capt.capture(), tag2Capt.capture()); + assertEquals("Service id is incorrect", CinderVolume.SERVICE, serviceIdCapt.getValue()); + assertEquals("Resource is incorrect", "/volumes", resourceCapt.getValue()); + assertEquals("Resource id is incorrect", testVolumeId, resourceIdCapt.getValue()); + assertArrayEquals("Tags are incorrect", tags, new Tag[] { tag1Capt.getValue(), tag2Capt.getValue() } ); + } + + @Test public void testUpdateTags1() throws Exception { + // prepare + Mockito.doCallRealMethod().when(volumeSupport).updateTags(any(String[].class), any(Tag.class)); + Tag tag = new Tag("a", "aa"); + String anotherId = "anotherTestId"; + + // run + volumeSupport.updateTags(new String[] {testVolumeId, anotherId}, tag); + + // verify + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + verify(volumeSupport, times(2)).updateTags(resourceIdCapt.capture(), tag1Capt.capture()); + List imageIdValues = resourceIdCapt.getAllValues(); + assertArrayEquals("Resource ids were not correct", new String[]{testVolumeId, anotherId}, + imageIdValues.toArray(new String[imageIdValues.size()])); + assertEquals("Tag was not correct", tag, tag1Capt.getValue()); + } + + @Test + public void testRemoveTags() throws Exception { + // prepare + Mockito.doCallRealMethod().when(volumeSupport).removeTags(anyString(), any(Tag.class), any(Tag.class)); + Tag[] tags = { new Tag("a", "aa"), new Tag("b", "bb") } ; + + // run + volumeSupport.removeTags(testVolumeId, tags); + + // verify + ArgumentCaptor serviceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + ArgumentCaptor tag2Capt = ArgumentCaptor.forClass(Tag.class); + verify(provider).removeTags(serviceIdCapt.capture(), resourceCapt.capture(), resourceIdCapt.capture(), tag1Capt.capture(), tag2Capt.capture()); + assertEquals("Service id is incorrect", CinderVolume.SERVICE, serviceIdCapt.getValue()); + assertEquals("Resource is incorrect", "/volumes", resourceCapt.getValue()); + assertEquals("Resource id is incorrect", testVolumeId, resourceIdCapt.getValue()); + assertArrayEquals("Tags are incorrect", tags, new Tag[] { tag1Capt.getValue(), tag2Capt.getValue() } ); + + } + + @Test + public void testRemoveTags1() throws Exception { + // prepare + Mockito.doCallRealMethod().when(volumeSupport).removeTags(any(String[].class), any(Tag.class)); + Tag tag = new Tag("a", "aa"); + String anotherId = "anotherTestId"; + + // run + volumeSupport.removeTags(new String[] {testVolumeId, anotherId}, tag); + + // verify + ArgumentCaptor resourceIdCapt = ArgumentCaptor.forClass(String.class); + ArgumentCaptor tag1Capt = ArgumentCaptor.forClass(Tag.class); + verify(volumeSupport, times(2)).removeTags(resourceIdCapt.capture(), tag1Capt.capture()); + List idValues = resourceIdCapt.getAllValues(); + assertArrayEquals("Resource ids were not correct", new String[]{testVolumeId, anotherId}, + idValues.toArray(new String[idValues.size()])); + assertEquals("Tag was not correct", tag, tag1Capt.getValue()); + } +} \ No newline at end of file diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java index e8cd3be..e1815c9 100644 --- a/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/compute/NovaImageTest.java @@ -25,6 +25,7 @@ import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; /** diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypairTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypairTest.java new file mode 100644 index 0000000..34f1a5a --- /dev/null +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/identity/NovaKeypairTest.java @@ -0,0 +1,194 @@ +package org.dasein.cloud.openstack.nova.os.identity; + +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.ProviderContext; +import org.dasein.cloud.identity.SSHKeypair; +import org.dasein.cloud.openstack.nova.os.NovaMethod; +import org.dasein.cloud.openstack.nova.os.NovaOpenStack; +import org.dasein.cloud.openstack.nova.os.OpenStackProvider; +import org.dasein.cloud.openstack.nova.os.OpenStackTest; +import org.dasein.cloud.openstack.nova.os.compute.NovaComputeServices; +import org.dasein.cloud.openstack.nova.os.compute.NovaServer; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.Collection; +import java.util.Map; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.whenNew; + +/** + * Created by mariapavlova on 02/03/2016. + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest(NovaKeypair.class) +public class NovaKeypairTest extends OpenStackTest { + private NovaMethod method; + private NovaKeypair keypairSupport; + + private NovaOpenStack provider; + + private String testKeypairId = "keypair-50ca852e-273f-4cdc-8949-45feba200837"; + private String testRegionId = "testRegionId"; + private String testOwnerId = "5ef70662f8b34079a6eddb8da9d75fe8"; + private String testKeypairName = "testKeypairName"; + private String testPublicKey = "testPublicKey"; + + @Before + public void setup() { + provider = PowerMockito.mock(NovaOpenStack.class); + try { + PowerMockito.when(provider.isPostCactus()).thenReturn(true); + PowerMockito.when(provider.getCloudProvider()).thenReturn(OpenStackProvider.OTHER); + } + catch( CloudException | InternalException e ) { + e.printStackTrace(); + fail(); + } + ProviderContext context = PowerMockito.mock(ProviderContext.class); + PowerMockito.when(context.getRegionId()).thenReturn(testRegionId); + PowerMockito.when(context.getAccountNumber()).thenReturn(testOwnerId); + + keypairSupport = PowerMockito.mock(NovaKeypair.class); + + try { + PowerMockito.doReturn(provider).when(keypairSupport, "getProvider"); + PowerMockito.doReturn(context).when(keypairSupport, "getContext"); + } + catch( Exception e ) { + e.printStackTrace(); + fail("Exception occurred " + e.getMessage()); + } + + method = PowerMockito.mock(NovaMethod.class); + try { + whenNew(NovaMethod.class).withAnyArguments().thenReturn(method); + } + catch( Exception e ) { + e.printStackTrace(); + fail("Couldn't create a mock for NovaMethod construction"); + } + } + + @Test + public void testCreateKeypair() throws Exception { + JSONObject json = readJson("nova/fixtures/compute/create_keypair.json"); + SSHKeypair keypair = new SSHKeypair(); + keypair.setProviderKeypairId(testKeypairId); + + when(keypairSupport.toKeypair(any(JSONObject.class))).thenReturn(keypair); + when(method.postServers(anyString(), anyString(), any(JSONObject.class), anyBoolean())).thenReturn(json); + when(keypairSupport.createKeypair(anyString())).thenCallRealMethod(); + + SSHKeypair res = keypairSupport.createKeypair("testKeypairName"); + + assertNotNull("Returned keipair name cannot be null", res); + assertEquals("Returned keipair name is not as expected", keypair, res); + + } + + @Test + public void testDeleteKeypair() throws Exception { + Mockito.doNothing().when(method).deleteServers(anyString(), anyString()); + Mockito.doCallRealMethod().when(keypairSupport).deleteKeypair(anyString()); + + keypairSupport.deleteKeypair(testKeypairId); + + ArgumentCaptor keypairIdArg = ArgumentCaptor.forClass(String.class); + verify(method).deleteServers(anyString(), keypairIdArg.capture()); + assertEquals("Keypair ID passed to the method is not as expected", testKeypairId, keypairIdArg.getValue()); + + } + + @Test + public void testGetFingerprint() throws Exception { + SSHKeypair keypair = new SSHKeypair(); + keypair.setFingerprint("fingerprint"); + + when(keypairSupport.getKeypair(anyString())).thenReturn(keypair); + when(keypairSupport.getFingerprint(anyString())).thenCallRealMethod(); + + String res = keypairSupport.getFingerprint(testKeypairId); + + assertNotNull("Returned fingerprint id cannot be null", res); + assertEquals("Fingerprint is not as expected", "fingerprint", res); + } + + @Test + public void testGetKeypair() throws Exception { + JSONObject json = readJson("nova/fixtures/compute/list_keypairs.json"); + when(method.getServers(anyString(), anyString(), anyBoolean())).thenReturn(json); + when(keypairSupport.toKeypair(any(JSONObject.class))).thenCallRealMethod(); + Mockito.doCallRealMethod().when(keypairSupport).getKeypair(anyString()); + + SSHKeypair res = keypairSupport.getKeypair(testKeypairId); + + assertNotNull("Returned keypair id cannot be null", res); + assertEquals("Returned keipair fingerprint is not as expected", + "7e:eb:ab:24:ba:d1:e1:88:ae:9a:fb:66:53:df:d3:bd", + res.getFingerprint()); + + } + + @Test + public void testGetCapabilities() throws Exception { + + } + + @Test + public void testImportKeypair() throws Exception { + SSHKeypair keypair = new SSHKeypair(); + + JSONObject json = readJson("nova/fixtures/compute/create_keypair.json"); + when(method.postServers(anyString(), anyString(), any(JSONObject.class), anyBoolean())).thenReturn(json); + + when(keypairSupport.toKeypair(any(JSONObject.class))).thenCallRealMethod(); + when(keypairSupport.importKeypair(anyString(), anyString())).thenCallRealMethod(); + + SSHKeypair res = keypairSupport.importKeypair(testKeypairName, testPublicKey); + assertNotNull("Returned keypair id cannot be null", res); + + ArgumentCaptor jsonArg = ArgumentCaptor.forClass(JSONObject.class); + + verify(method).postServers(anyString(), anyString(), jsonArg.capture(), anyBoolean()); + Map keypairParam = ( Map ) jsonArg.getValue().get("keypair"); + assertNotNull("Argument is incorrect", keypairParam); + assertEquals("Argument value 'name' is incorrect", testKeypairName, keypairParam.get("name")); + assertEquals("Argument value 'public_key' is incorrect", testPublicKey, keypairParam.get("public_key")); + } + + @Test + public void testIsSubscribed() throws Exception { + + } + + @Test + public void testList() throws Exception { + JSONObject json = readJson("nova/fixtures/compute/list_keypairs.json"); + when(method.getServers(anyString(), anyString(), anyBoolean())).thenReturn(json); + when(keypairSupport.toKeypair(any(JSONObject.class))).thenCallRealMethod(); + when(keypairSupport.list()).thenCallRealMethod(); + + Collection res = keypairSupport.list(); + int count = 0; + for( SSHKeypair key : res ) { + count++; + } + assertNotNull("Returned list cannot be null", res); + assertEquals("Returned number of keypairs is not as expected", 1, count); + } + +} \ No newline at end of file diff --git a/src/test/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStoreTest.java b/src/test/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStoreTest.java new file mode 100644 index 0000000..615bc44 --- /dev/null +++ b/src/test/java/org/dasein/cloud/openstack/nova/os/storage/SwiftBlobStoreTest.java @@ -0,0 +1,260 @@ +package org.dasein.cloud.openstack.nova.os.storage; + +import org.dasein.cloud.CloudException; +import org.dasein.cloud.InternalException; +import org.dasein.cloud.ProviderContext; +import org.dasein.cloud.openstack.nova.os.*; +import org.dasein.cloud.storage.Blob; +import org.dasein.cloud.storage.FileTransfer; +import org.dasein.util.uom.storage.Byte; +import org.dasein.util.uom.storage.Storage; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.mockito.Mockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.*; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.*; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.when; +import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; + +/** + * Created by mariapavlova on 19/04/2016. + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest( { SwiftBlobStore.class } ) +/* + + + */ +public class SwiftBlobStoreTest extends OpenStackTest { + private SwiftMethod method; + private SwiftBlobStore swiftBlobSupport; + private NovaOpenStack provider; + private Blob blobMock; + private AuthenticationContext authenticationContext; + + private static final String testRegionId = "testRegionId"; + private static final String testOwnerId = "5ef70662f8b34079a6eddb8da9d75fe8"; + private static final String testBucketName = "testBucketName"; + private static final String testBucketLocation = "testBucketLocation"; + private static final String testObjectName = "testObjectName"; + private static final String testStorageUrl = "testStorageUrl"; + + @Before + public void setUp() throws Exception { + provider = mock(NovaOpenStack.class); + try { + PowerMockito.when(provider.isPostCactus()).thenReturn(true); + PowerMockito.when(provider.getCloudProvider()).thenReturn(OpenStackProvider.OTHER); + } + catch( CloudException | InternalException e ) { + e.printStackTrace(); + fail(); + } + ProviderContext context = mock(ProviderContext.class); + PowerMockito.when(context.getRegionId()).thenReturn(testRegionId); + PowerMockito.when(context.getAccountNumber()).thenReturn(testOwnerId); + swiftBlobSupport = mock(SwiftBlobStore.class); + + try { + PowerMockito.doReturn(provider).when(swiftBlobSupport, "getProvider"); + PowerMockito.doReturn(context).when(swiftBlobSupport, "getContext"); + } + catch( Exception e ) { + e.printStackTrace(); + fail("Exception occurred " + e.getMessage()); + } + // auth context + authenticationContext = Mockito.mock(AuthenticationContext.class); + Mockito.when(provider.getAuthenticationContext()).thenReturn(authenticationContext); + Mockito.when(authenticationContext.getStorageUrl()).thenReturn(testStorageUrl); + + /*Cache noCache = PowerMockito.mock(Cache.class); + PowerMockito.when(Cache.getInstance(any(CloudProvider.class), anyString(), any(Class.class), any(CacheLevel.class))).thenReturn(noCache); + when(noCache.get(any(ProviderContext.class))).thenReturn(null);*/ + + method = mock(SwiftMethod.class); + try { + whenNew(SwiftMethod.class).withAnyArguments().thenReturn(method); + } + catch( Exception e ) { + e.printStackTrace(); + fail("Couldn't create a mock for NovaMethod construction"); + } + } + + + @Test public void testGetCapabilities() throws Exception { + + } + + @Test public void testCreateBucket() throws Exception { + // prepare + Blob blobMock = mock(Blob.class); + when(swiftBlobSupport.getBucket(anyString())).thenReturn(blobMock); + when(swiftBlobSupport.exists(anyString())).thenReturn(true); + when(swiftBlobSupport.findFreeName(anyString())).thenReturn(testBucketName); + Mockito.doNothing().when(swiftBlobSupport).createBucket(anyString()); + when(swiftBlobSupport.createBucket(anyString(), any(Boolean.class))).thenCallRealMethod(); + // run + Blob bucket = swiftBlobSupport.createBucket(testBucketName, true); + // verify + assertEquals("Returned bucket name is not as expected", blobMock, bucket); + + } + + @Test public void testExists() throws Exception { + + } + + @Test public void testGetBucket() throws Exception { + // prepare + Blob blobMock = mock(Blob.class); + when(swiftBlobSupport.getBucket(anyString())).thenCallRealMethod(); + when(blobMock.isContainer()).thenReturn(true); + when(swiftBlobSupport.list(anyString())).thenReturn(Arrays.asList(blobMock)); + when(blobMock.getBucketName()).thenReturn(testBucketName); + // run + Blob bucket = swiftBlobSupport.getBucket(testBucketName); + //verify + assertEquals("Returned bucket name is not as expected ", blobMock, bucket); + } + + @Test public void testGetObject() throws Exception { + // prepare + Blob blobMock = mock(Blob.class); + when(swiftBlobSupport.list(anyString())).thenReturn(Arrays.asList(blobMock)); + when(blobMock.getObjectName()).thenReturn(testObjectName); + when(swiftBlobSupport.getObject(anyString(), anyString())).thenCallRealMethod(); + // run + Blob bucket = swiftBlobSupport.getObject(testBucketName, testObjectName); + //verify + assertEquals("Returned Object is not as expected", blobMock, bucket); + } + + @Test public void testGetSignedObjectUrl() throws Exception { + + } + + @Test public void testGetObjectSize() throws Exception { + // prepare + Blob blobMock = mock(Blob.class); + + Map map = new HashMap<>(); + map.put(testBucketName, testObjectName); + when(method.head(anyString(), anyString())).thenReturn(map); + when(swiftBlobSupport.getMetaDataLength(any(Map.class))).thenReturn(100L); +// when(method, "getContext").thenReturn(context); + when(swiftBlobSupport.getObjectSize(anyString(), anyString())).thenCallRealMethod(); + //run + Storage res = swiftBlobSupport.getObjectSize(testBucketName, testObjectName); + //verify + assertEquals("Returned object size is not as expected", 100L, res.longValue()); + + } + + @Test public void testGet() throws Exception { + // prepare + File tempFile = File.createTempFile("dasein", "blob-get"); + tempFile.deleteOnExit(); + FileTransfer fileTransferMock = mock(FileTransfer.class); + final String testContent = "testContent"; + InputStream stream = new ByteArrayInputStream(testContent.getBytes()); + + when(swiftBlobSupport.exists(anyString())).thenReturn(false); + when(method.get(anyString(), anyString())).thenReturn(stream); + Mockito.doCallRealMethod().when(swiftBlobSupport).get(anyString(), anyString(), any(File.class), any(FileTransfer.class)); + PowerMockito.doCallRealMethod().when(swiftBlobSupport, "copy", any(InputStream.class), any(OutputStream.class), any(FileTransfer.class)); + + //run + swiftBlobSupport.get(testBucketName, testBucketLocation, tempFile, fileTransferMock); + + //verify + String resultContent = new String(Files.readAllBytes(tempFile.toPath())); + assertEquals("Resulting copied file content is not as expected", testContent, resultContent); + } + + @Test public void testIsPublic() throws Exception { + + } + + @Test public void testIsSubscribed() throws Exception { + + } + + @Test public void testList() throws Exception { + + } + + @Test public void testMakePublic() throws Exception { + + } + + @Test public void testMakePublic1() throws Exception { + + } + + @Test public void testMapServiceAction() throws Exception { + + } + + @Test public void testMove() throws Exception { + + } + + @Test public void testPut() throws Exception { + + } + + @Test public void testPut1() throws Exception { + + } + + @Test public void testRemoveBucket() throws Exception { + + } + + @Test public void testRemoveObject() throws Exception { + + } + + @Test public void testRenameBucket() throws Exception { + + } + + @Test public void testRenameObject() throws Exception { + + } + + @Test public void testUpload() throws Exception { + + } + + @Test public void testUpdateTags() throws Exception { + + } + + @Test public void testUpdateTags1() throws Exception { + + } + + @Test public void testRemoveTags() throws Exception { + + } + + @Test public void testRemoveTags1() throws Exception { + + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/compute/create_keypair.json b/src/test/resources/nova/fixtures/compute/create_keypair.json new file mode 100644 index 0000000..ffd59f7 --- /dev/null +++ b/src/test/resources/nova/fixtures/compute/create_keypair.json @@ -0,0 +1,8 @@ +{ + "keypair": { + "fingerprint": "1e:2c:9b:56:79:4b:45:77:f9:ca:7a:98:2c:b0:d5:3c", + "name": "keypair-803a1926-af78-4b05-902a-1d6f7a8d9d3e", + "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDx8nkQv/zgGgB4rMYmIf+6A4l6Rr+o/6lHBQdW5aYd44bd8JttDCE/F/pNRr0lRE+PiqSPO8nDPHw0010JeMH9gYgnnFlyY3/OcJ02RhIPyyxYpv9FhY+2YiUkpwFOcLImyrxEsYXpD/0d3ac30bNH6Sw9JD9UZHYcpSxsIbECHw== Generated-by-Nova", + "user_id": "fake" + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/compute/create_snapshot.json b/src/test/resources/nova/fixtures/compute/create_snapshot.json new file mode 100644 index 0000000..75b1dd7 --- /dev/null +++ b/src/test/resources/nova/fixtures/compute/create_snapshot.json @@ -0,0 +1,11 @@ +{ + "snapshot": { + "id": "3fbbcccf-d058-4502-8844-6feeffdf4cb5", + "display_name": "snap-001", + "display_description": "Daily backup", + "volume_id": "521752a6-acf6-4b2d-bc7a-119f9148cd8c", + "status": "available", + "size": 30, + "created_at": "2012-02-29T03:50:07Z" + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/compute/create_volume.json b/src/test/resources/nova/fixtures/compute/create_volume.json new file mode 100644 index 0000000..deda50e --- /dev/null +++ b/src/test/resources/nova/fixtures/compute/create_volume.json @@ -0,0 +1,27 @@ +{ + "volume": { + "id": "521752a6-acf6-4b2d-bc7a-119f9148cd8c", + "display_name": "vol-001", + "display_description": "Another volume.", + "status": "active", + "size": 30, + "volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164", + "metadata": { + "contents": "junk" + }, + "availability_zone": "us-east1", + "bootable": "false", + "snapshot_id": null, + "attachments": [ + { + "attachment_id": "03987cd1-0ad5-40d1-9b2a-7cc48295d4fa", + "id": "47e9ecc5-4045-4ee3-9a4b-d859d546a0cf", + "volume_id": "6c80f8ac-e3e2-480c-8e6e-f1db92fe4bfe", + "server_id": "d1c4788b-9435-42e2-9b81-29f3be1cd01f", + "host_name": "mitaka", + "device": "/" + } + ], + "created_at": "2012-02-14T20:53:07Z" + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/compute/get_keypair.json b/src/test/resources/nova/fixtures/compute/get_keypair.json new file mode 100644 index 0000000..b88902f --- /dev/null +++ b/src/test/resources/nova/fixtures/compute/get_keypair.json @@ -0,0 +1,13 @@ +{ + "keypair": { + "fingerprint": "44:fe:29:6e:23:14:b9:53:5b:65:82:58:1c:fe:5a:c3", + "name": "keypair-6638abdb-c4e8-407c-ba88-c8dd7cc3c4f1", + "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC1HTrHCbb9NawNLSV8N6tSa8i637+EC2dA+lsdHHfQlT54t+N0nHhJPlKWDLhc579j87vp6RDFriFJ/smsTnDnf64O12z0kBaJpJPH2zXrBkZFK6q2rmxydURzX/z0yLSCP77SFJ0fdXWH2hMsAusflGyryHGX20n+mZK6mDrxVzGxEz228dwQ5G7Az5OoZDWygH2pqPvKjkifRw0jwUKf3BbkP0QvANACOk26cv16mNFpFJfI1N3OC5lUsZQtKGR01ptJoWijYKccqhkAKuo902tg/qup58J5kflNm7I61sy1mJon6SGqNUSfoQagqtBH6vd/tU1jnlwZ03uUroAL Generated-by-Nova\n", + "user_id": "fake", + "deleted": false, + "created_at": "2014-05-07T12:06:13.681238", + "updated_at": null, + "deleted_at": null, + "id": 1 + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/compute/get_snapshot.json b/src/test/resources/nova/fixtures/compute/get_snapshot.json new file mode 100644 index 0000000..75b1dd7 --- /dev/null +++ b/src/test/resources/nova/fixtures/compute/get_snapshot.json @@ -0,0 +1,11 @@ +{ + "snapshot": { + "id": "3fbbcccf-d058-4502-8844-6feeffdf4cb5", + "display_name": "snap-001", + "display_description": "Daily backup", + "volume_id": "521752a6-acf6-4b2d-bc7a-119f9148cd8c", + "status": "available", + "size": 30, + "created_at": "2012-02-29T03:50:07Z" + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/compute/get_volume.json b/src/test/resources/nova/fixtures/compute/get_volume.json new file mode 100644 index 0000000..deda50e --- /dev/null +++ b/src/test/resources/nova/fixtures/compute/get_volume.json @@ -0,0 +1,27 @@ +{ + "volume": { + "id": "521752a6-acf6-4b2d-bc7a-119f9148cd8c", + "display_name": "vol-001", + "display_description": "Another volume.", + "status": "active", + "size": 30, + "volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164", + "metadata": { + "contents": "junk" + }, + "availability_zone": "us-east1", + "bootable": "false", + "snapshot_id": null, + "attachments": [ + { + "attachment_id": "03987cd1-0ad5-40d1-9b2a-7cc48295d4fa", + "id": "47e9ecc5-4045-4ee3-9a4b-d859d546a0cf", + "volume_id": "6c80f8ac-e3e2-480c-8e6e-f1db92fe4bfe", + "server_id": "d1c4788b-9435-42e2-9b81-29f3be1cd01f", + "host_name": "mitaka", + "device": "/" + } + ], + "created_at": "2012-02-14T20:53:07Z" + } +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/compute/list_keypairs.json b/src/test/resources/nova/fixtures/compute/list_keypairs.json new file mode 100644 index 0000000..4962581 --- /dev/null +++ b/src/test/resources/nova/fixtures/compute/list_keypairs.json @@ -0,0 +1,11 @@ +{ + "keypairs": [ + { + "keypair": { + "fingerprint": "7e:eb:ab:24:ba:d1:e1:88:ae:9a:fb:66:53:df:d3:bd", + "name": "keypair-50ca852e-273f-4cdc-8949-45feba200837", + "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCkF3MX59OrlBs3dH5CU7lNmvpbrgZxSpyGjlnE8Flkirnc/Up22lpjznoxqeoTAwTW034k7Dz6aYIrZGmQwe2TkE084yqvlj45Dkyoj95fW/sZacm0cZNuL69EObEGHdprfGJQajrpz22NQoCD8TFB8Wv+8om9NH9Le6s+WPe98WC77KLw8qgfQsbIey+JawPWl4O67ZdL5xrypuRjfIPWjgy/VH85IXg/Z/GONZ2nxHgSShMkwqSFECAC5L3PHB+0+/12M/iikdatFSVGjpuHvkLOs3oe7m6HlOfluSJ85BzLWBbvva93qkGmLg4ZAc8rPh2O+YIsBUHNLLMM/oQp Generated-by-Nova\n" + } + } + ] +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/compute/list_snapshot.json b/src/test/resources/nova/fixtures/compute/list_snapshot.json new file mode 100644 index 0000000..7b4f813 --- /dev/null +++ b/src/test/resources/nova/fixtures/compute/list_snapshot.json @@ -0,0 +1,26 @@ +{ + "snapshots": [ + { + "id": "3fbbcccf-d058-4502-8844-6feeffdf4cb5", + "display_name": "snap-001", + "display_description": "Daily backup", + "volume_id": "521752a6-acf6-4b2d-bc7a-119f9148cd8c", + "status": "available", + "size": 30, + "created_at": "2012-02-29T03:50:07Z", + "metadata": { + "contents": "junk" + } + }, + { + "id": "e479997c-650b-40a4-9dfe-77655818b0d2", + "display_name": "snap-002", + "display_description": "Weekly backup", + "volume_id": "76b8950a-8594-4e5b-8dce-0dfa9c696358", + "status": "available", + "size": 25, + "created_at": "2012-03-19T01:52:47Z", + "metadata": {} + } + ] +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/compute/list_volume_types.json b/src/test/resources/nova/fixtures/compute/list_volume_types.json new file mode 100644 index 0000000..1627b98 --- /dev/null +++ b/src/test/resources/nova/fixtures/compute/list_volume_types.json @@ -0,0 +1,16 @@ +{ + "volume_types": [ + { + "id": "289da7f8-6440-407c-9fb4-7db01ec49164", + "name": "vol-type-001", + "extra_specs": { + "capabilities": "gpu" + } + }, + { + "id": "96c3bda7-c82a-4f50-be73-ca7621794835", + "name": "vol-type-002", + "extra_specs": {} + } + ] +} \ No newline at end of file diff --git a/src/test/resources/nova/fixtures/compute/list_volumes.json b/src/test/resources/nova/fixtures/compute/list_volumes.json new file mode 100644 index 0000000..b22fa31 --- /dev/null +++ b/src/test/resources/nova/fixtures/compute/list_volumes.json @@ -0,0 +1,41 @@ +{ + "volumes": [ + { + "id": "521752a6-acf6-4b2d-bc7a-119f9148cd8c", + "display_name": "vol-001", + "display_description": "Another volume.", + "status": "active", + "size": 30, + "volume_type": "289da7f8-6440-407c-9fb4-7db01ec49164", + "metadata": { + "contents": "junk" + }, + "availability_zone": "us-east1", + "snapshot_id": null, + "attachments": [ + { + "attachment_id": "03987cd1-0ad5-40d1-9b2a-7cc48295d4fa", + "id": "47e9ecc5-4045-4ee3-9a4b-d859d546a0cf", + "volume_id": "6c80f8ac-e3e2-480c-8e6e-f1db92fe4bfe", + "server_id": "d1c4788b-9435-42e2-9b81-29f3be1cd01f", + "host_name": "mitaka", + "device": "/" + } + ], + "created_at": "2012-02-14T20:53:07Z" + }, + { + "id": "76b8950a-8594-4e5b-8dce-0dfa9c696358", + "display_name": "vol-002", + "display_description": "Yet another volume.", + "status": "active", + "size": 25, + "volume_type": "96c3bda7-c82a-4f50-be73-ca7621794835", + "metadata": {}, + "availability_zone": "us-east2", + "snapshot_id": null, + "attachments": [], + "created_at": "2012-03-15T19:10:03Z" + } + ] +} \ No newline at end of file