Nvp and rest refactoring and more tests

Signed-off-by: Hugo Trippaers <htrippaers@schubergphilis.com>
This commit is contained in:
Antonio Fornie 2014-02-05 10:01:06 +01:00 committed by Hugo Trippaers
parent dda47dbd67
commit 510972abde
26 changed files with 2211 additions and 1388 deletions

View File

@ -19,32 +19,12 @@
package com.cloud.network.nicira; package com.cloud.network.nicira;
import java.io.Serializable;
import java.util.List; import java.util.List;
import org.apache.commons.lang.builder.EqualsBuilder; public abstract class AccessConfiguration<T extends AccessRule> extends BaseNiciraNamedEntity {
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
@SuppressWarnings("serial")
public abstract class AccessConfiguration<T extends AccessRule> implements Serializable {
protected String displayName;
protected List<T> logicalPortEgressRules; protected List<T> logicalPortEgressRules;
protected List<T> logicalPortIngressRules; protected List<T> logicalPortIngressRules;
protected List<NiciraNvpTag> tags;
protected String uuid;
protected String href;
protected String schema;
public String getDisplayName() {
return displayName;
}
public void setDisplayName(final String displayName) {
this.displayName = displayName;
}
public List<T> getLogicalPortEgressRules() { public List<T> getLogicalPortEgressRules() {
return logicalPortEgressRules; return logicalPortEgressRules;
@ -61,72 +41,4 @@ public abstract class AccessConfiguration<T extends AccessRule> implements Seria
public void setLogicalPortIngressRules(final List<T> logicalPortIngressRules) { public void setLogicalPortIngressRules(final List<T> logicalPortIngressRules) {
this.logicalPortIngressRules = logicalPortIngressRules; this.logicalPortIngressRules = logicalPortIngressRules;
} }
public String getUuid() {
return uuid;
}
public void setUuid(final String uuid) {
this.uuid = uuid;
}
public String getHref() {
return href;
}
public void setHref(final String href) {
this.href = href;
}
public String getSchema() {
return schema;
}
public void setSchema(final String schema) {
this.schema = schema;
}
public List<NiciraNvpTag> getTags() {
return tags;
}
public void setTags(final List<NiciraNvpTag> tags) {
this.tags = tags;
}
@Override
public String toString() {
return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false);
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31)
.append(displayName).append(logicalPortEgressRules)
.append(logicalPortIngressRules).append(tags)
.append(uuid).append(href).append(schema)
.toHashCode();
}
@Override
@SuppressWarnings("unchecked")
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(this.getClass().isInstance(obj))) {
return false;
}
final AccessConfiguration<? extends AccessRule> another =
(AccessConfiguration<? extends AccessRule>) obj;
return new EqualsBuilder()
.append(displayName, another.displayName)
.append(uuid, another.uuid)
.append(href, another.href)
.append(schema, another.schema)
.isEquals();
}
} }

View File

@ -19,6 +19,5 @@
package com.cloud.network.nicira; package com.cloud.network.nicira;
@SuppressWarnings("serial")
public class Acl extends AccessConfiguration<AclRule> { public class Acl extends AccessConfiguration<AclRule> {
} }

View File

@ -0,0 +1,85 @@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.network.nicira;
import java.io.Serializable;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
public abstract class BaseNiciraEntity implements Serializable {
protected String href;
protected String schema;
protected String uuid;
public String getUuid() {
return uuid;
}
public void setUuid(final String uuid) {
this.uuid = uuid;
}
public String getHref() {
return href;
}
public void setHref(final String href) {
this.href = href;
}
public String getSchema() {
return schema;
}
public void setSchema(final String schema) {
this.schema = schema;
}
@Override
public String toString() {
return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false);
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31)
.append(this.getClass())
.append(uuid)
.toHashCode();
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(this.getClass().isInstance(obj))) {
return false;
}
final BaseNiciraEntity another = (BaseNiciraEntity) obj;
return new EqualsBuilder().append(uuid, another.uuid).isEquals();
}
}

View File

@ -21,45 +21,24 @@ package com.cloud.network.nicira;
import java.util.List; import java.util.List;
/** public abstract class BaseNiciraNamedEntity extends BaseNiciraEntity {
*
*/
public class LogicalRouterConfig {
private String displayName;
private RoutingConfig routingConfig;
private final String type = "LogicalRouterConfig";
private String uuid;
private List<NiciraNvpTag> tags;
public RoutingConfig getRoutingConfig() { protected String displayName;
return routingConfig; protected List<NiciraNvpTag> tags;
}
public void setRoutingConfig(RoutingConfig routingConfig) {
this.routingConfig = routingConfig;
}
public String getDisplayName() { public String getDisplayName() {
return displayName; return displayName;
} }
public void setDisplayName(String displayName) { public void setDisplayName(final String displayName) {
this.displayName = displayName; this.displayName = displayName;
} }
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public List<NiciraNvpTag> getTags() { public List<NiciraNvpTag> getTags() {
return tags; return tags;
} }
public void setTags(List<NiciraNvpTag> tags) { public void setTags(final List<NiciraNvpTag> tags) {
this.tags = tags; this.tags = tags;
} }
} }

View File

@ -0,0 +1,71 @@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.network.nicira;
/**
*
*/
public class LogicalRouter extends BaseNiciraNamedEntity {
public static final String REPLICATION_MODE_SERVICE = "service";
public static final String REPLICATION_MODE_SOURCE = "source";
private final String type = "LogicalRouterConfig";
private RoutingConfig routingConfig;
private boolean distributed;
private boolean natSynchronizationEnabled;
private String replicationMode;
public String getType() {
return type;
}
public RoutingConfig getRoutingConfig() {
return routingConfig;
}
public void setRoutingConfig(final RoutingConfig routingConfig) {
this.routingConfig = routingConfig;
}
public boolean isDistributed() {
return distributed;
}
public void setDistributed(final boolean distributed) {
this.distributed = distributed;
}
public boolean isNatSynchronizationEnabled() {
return natSynchronizationEnabled;
}
public void setNatSynchronizationEnabled(final boolean natSynchronizationEnabled) {
this.natSynchronizationEnabled = natSynchronizationEnabled;
}
public String getReplicationMode() {
return replicationMode;
}
public void setReplicationMode(final String replicationMode) {
this.replicationMode = replicationMode;
}
}

View File

@ -21,24 +21,18 @@ package com.cloud.network.nicira;
import java.util.List; import java.util.List;
/** public class LogicalRouterPort extends BaseNiciraNamedEntity {
*
*/
public class LogicalRouterPort {
private String displayName;
private List<NiciraNvpTag> tags;
private Integer portno; private Integer portno;
private boolean adminStatusEnabled; private boolean adminStatusEnabled;
private List<String> ipAddresses; private List<String> ipAddresses;
private String macAddress; private String macAddress;
private final String type = "LogicalRouterPortConfig"; private final String type = "LogicalRouterPortConfig";
private String uuid;
public int getPortno() { public int getPortno() {
return portno; return portno;
} }
public void setPortno(int portno) { public void setPortno(final int portno) {
this.portno = portno; this.portno = portno;
} }
@ -46,7 +40,7 @@ public class LogicalRouterPort {
return adminStatusEnabled; return adminStatusEnabled;
} }
public void setAdminStatusEnabled(boolean adminStatusEnabled) { public void setAdminStatusEnabled(final boolean adminStatusEnabled) {
this.adminStatusEnabled = adminStatusEnabled; this.adminStatusEnabled = adminStatusEnabled;
} }
@ -54,7 +48,7 @@ public class LogicalRouterPort {
return ipAddresses; return ipAddresses;
} }
public void setIpAddresses(List<String> ipAddresses) { public void setIpAddresses(final List<String> ipAddresses) {
this.ipAddresses = ipAddresses; this.ipAddresses = ipAddresses;
} }
@ -62,32 +56,7 @@ public class LogicalRouterPort {
return macAddress; return macAddress;
} }
public void setMacAddress(String macAddress) { public void setMacAddress(final String macAddress) {
this.macAddress = macAddress; this.macAddress = macAddress;
} }
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public List<NiciraNvpTag> getTags() {
return tags;
}
public void setTags(List<NiciraNvpTag> tags) {
this.tags = tags;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
} }

View File

@ -21,29 +21,20 @@ package com.cloud.network.nicira;
import java.util.List; import java.util.List;
public class LogicalSwitch { public class LogicalSwitch extends BaseNiciraNamedEntity {
private String displayName; public static final String REPLICATION_MODE_SERVICE = "service";
public static final String REPLICATION_MODE_SOURCE = "source";
private final String type = "LogicalSwitchConfig";
private boolean portIsolationEnabled; private boolean portIsolationEnabled;
private List<NiciraNvpTag> tags;
private List<TransportZoneBinding> transportZones; private List<TransportZoneBinding> transportZones;
private String type; private String replicationMode;
private String uuid;
private String href;
private String schema;
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public boolean isPortIsolationEnabled() { public boolean isPortIsolationEnabled() {
return portIsolationEnabled; return portIsolationEnabled;
} }
public void setPortIsolationEnabled(boolean portIsolationEnabled) { public void setPortIsolationEnabled(final boolean portIsolationEnabled) {
this.portIsolationEnabled = portIsolationEnabled; this.portIsolationEnabled = portIsolationEnabled;
} }
@ -51,48 +42,19 @@ public class LogicalSwitch {
return type; return type;
} }
public void setType(String type) {
this.type = type;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public List<NiciraNvpTag> getTags() {
return tags;
}
public void setTags(List<NiciraNvpTag> tags) {
this.tags = tags;
}
public List<TransportZoneBinding> getTransportZones() { public List<TransportZoneBinding> getTransportZones() {
return transportZones; return transportZones;
} }
public void setTransportZones(List<TransportZoneBinding> transportZones) { public void setTransportZones(final List<TransportZoneBinding> transportZones) {
this.transportZones = transportZones; this.transportZones = transportZones;
} }
public String getReplicationMode() {
return replicationMode;
}
public void setReplicationMode(final String replicationMode) {
this.replicationMode = replicationMode;
}
} }

View File

@ -21,16 +21,13 @@ package com.cloud.network.nicira;
import java.util.List; import java.util.List;
public class LogicalSwitchPort { public class LogicalSwitchPort extends BaseNiciraNamedEntity {
private String displayName;
private List<NiciraNvpTag> tags;
private Integer portno; private Integer portno;
private boolean adminStatusEnabled; private boolean adminStatusEnabled;
private String queueUuid; private String queueUuid;
private List<String> securityProfiles; private List<String> securityProfiles;
private List<String> mirrorTargets; private List<String> mirrorTargets;
private String type; private final String type = "LogicalSwitchPortConfig";
private String uuid;
public LogicalSwitchPort() { public LogicalSwitchPort() {
super(); super();
@ -43,27 +40,11 @@ public class LogicalSwitchPort {
this.adminStatusEnabled = adminStatusEnabled; this.adminStatusEnabled = adminStatusEnabled;
} }
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public List<NiciraNvpTag> getTags() {
return tags;
}
public void setTags(List<NiciraNvpTag> tags) {
this.tags = tags;
}
public Integer getPortno() { public Integer getPortno() {
return portno; return portno;
} }
public void setPortno(Integer portno) { public void setPortno(final Integer portno) {
this.portno = portno; this.portno = portno;
} }
@ -71,7 +52,7 @@ public class LogicalSwitchPort {
return adminStatusEnabled; return adminStatusEnabled;
} }
public void setAdminStatusEnabled(boolean adminStatusEnabled) { public void setAdminStatusEnabled(final boolean adminStatusEnabled) {
this.adminStatusEnabled = adminStatusEnabled; this.adminStatusEnabled = adminStatusEnabled;
} }
@ -79,7 +60,7 @@ public class LogicalSwitchPort {
return queueUuid; return queueUuid;
} }
public void setQueueUuid(String queueUuid) { public void setQueueUuid(final String queueUuid) {
this.queueUuid = queueUuid; this.queueUuid = queueUuid;
} }
@ -87,7 +68,7 @@ public class LogicalSwitchPort {
return securityProfiles; return securityProfiles;
} }
public void setSecurityProfiles(List<String> securityProfiles) { public void setSecurityProfiles(final List<String> securityProfiles) {
this.securityProfiles = securityProfiles; this.securityProfiles = securityProfiles;
} }
@ -95,24 +76,7 @@ public class LogicalSwitchPort {
return mirrorTargets; return mirrorTargets;
} }
public void setMirrorTargets(List<String> mirrorTargets) { public void setMirrorTargets(final List<String> mirrorTargets) {
this.mirrorTargets = mirrorTargets; this.mirrorTargets = mirrorTargets;
} }
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
} }

View File

@ -18,55 +18,14 @@
// //
package com.cloud.network.nicira; package com.cloud.network.nicira;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID; import java.util.UUID;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
import org.apache.log4j.Logger;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer; import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
@ -74,33 +33,24 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.cloud.utils.rest.CloudstackRESTException;
import com.cloud.utils.rest.RESTServiceConnector;
import com.cloud.utils.rest.RESTValidationStrategy;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class NiciraNvpApi { public class NiciraNvpApi {
protected static final String GET_METHOD_TYPE = "get"; protected static final String GET_METHOD_TYPE = "get";
protected static final String DELETE_METHOD_TYPE = "delete"; protected static final String DELETE_METHOD_TYPE = "delete";
protected static final String PUT_METHOD_TYPE = "put"; protected static final String PUT_METHOD_TYPE = "put";
protected static final String POST_METHOD_TYPE = "post"; protected static final String POST_METHOD_TYPE = "post";
private static final String TEXT_HTML_CONTENT_TYPE = "text/html";
private static final String JSON_CONTENT_TYPE = "application/json";
private static final String CONTENT_TYPE = "Content-Type";
private static final int BODY_RESP_MAX_LEN = 1024;
protected static final String SEC_PROFILE_URI_PREFIX = "/ws.v1/security-profile"; protected static final String SEC_PROFILE_URI_PREFIX = "/ws.v1/security-profile";
protected static final String ACL_URI_PREFIX = "/ws.v1/acl"; protected static final String ACL_URI_PREFIX = "/ws.v1/acl";
private static final String SWITCH_URI_PREFIX = "/ws.v1/lswitch"; private static final String SWITCH_URI_PREFIX = "/ws.v1/lswitch";
private static final String ROUTER_URI_PREFIX = "/ws.v1/lrouter"; private static final String ROUTER_URI_PREFIX = "/ws.v1/lrouter";
private static final int HTTPS_PORT = 443; private static final String LOGIN_URL = "/ws.v1/login";
private static final Logger s_logger = Logger.getLogger(NiciraNvpApi.class);
private final static String protocol = "https";
private final static MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager();
private String host; protected RESTServiceConnector restConnector;
private String adminuser;
private String adminpass;
private final HttpClient client;
private String nvpVersion;
private final Gson gson;
protected final static Map<Class, String> prefixMap; protected final static Map<Class, String> prefixMap;
@ -112,115 +62,174 @@ public class NiciraNvpApi {
prefixMap = new HashMap<Class, String>(); prefixMap = new HashMap<Class, String>();
prefixMap.put(SecurityProfile.class, SEC_PROFILE_URI_PREFIX); prefixMap.put(SecurityProfile.class, SEC_PROFILE_URI_PREFIX);
prefixMap.put(Acl.class, ACL_URI_PREFIX); prefixMap.put(Acl.class, ACL_URI_PREFIX);
prefixMap.put(LogicalSwitch.class, SWITCH_URI_PREFIX);
prefixMap.put(LogicalRouter.class, ROUTER_URI_PREFIX);
listTypeMap = new HashMap<Class, Type>(); listTypeMap = new HashMap<Class, Type>();
listTypeMap.put(SecurityProfile.class, new TypeToken<NiciraNvpList<SecurityProfile>>() { listTypeMap.put(SecurityProfile.class, new TypeToken<NiciraNvpList<SecurityProfile>>() {
}.getType()); }.getType());
listTypeMap.put(Acl.class, new TypeToken<NiciraNvpList<Acl>>() { listTypeMap.put(Acl.class, new TypeToken<NiciraNvpList<Acl>>() {
}.getType()); }.getType());
listTypeMap.put(LogicalSwitch.class, new TypeToken<NiciraNvpList<LogicalSwitch>>() {
}.getType());
listTypeMap.put(LogicalRouter.class, new TypeToken<NiciraNvpList<LogicalRouter>>() {
}.getType());
defaultListParams = new HashMap<String, String>(); defaultListParams = new HashMap<String, String>();
defaultListParams.put("fields", "*"); defaultListParams.put("fields", "*");
} }
/* This factory method is protected so we can extend this
* in the unittests.
*/
protected HttpClient createHttpClient() {
return new HttpClient(s_httpClientManager);
}
protected HttpMethod createMethod(final String type, final String uri) throws NiciraNvpApiException {
String url;
try {
url = new URL(protocol, host, uri).toString();
} catch (final MalformedURLException e) {
s_logger.error("Unable to build Nicira API URL", e);
throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
}
if (POST_METHOD_TYPE.equalsIgnoreCase(type)) {
return new PostMethod(url);
} else if (GET_METHOD_TYPE.equalsIgnoreCase(type)) {
return new GetMethod(url);
} else if (DELETE_METHOD_TYPE.equalsIgnoreCase(type)) {
return new DeleteMethod(url);
} else if (PUT_METHOD_TYPE.equalsIgnoreCase(type)) {
return new PutMethod(url);
} else {
throw new NiciraNvpApiException("Requesting unknown method type");
}
}
public NiciraNvpApi() { public NiciraNvpApi() {
client = createHttpClient(); final List<Class<?>> classList = new ArrayList<Class<?>>();
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); classList.add(NatRule.class);
classList.add(RoutingConfig.class);
final List<JsonDeserializer<?>> deserializerList = new ArrayList<JsonDeserializer<?>>();
deserializerList.add(new NatRuleAdapter());
deserializerList.add(new RoutingConfigAdapter());
try { restConnector = new RESTServiceConnector(new RESTValidationStrategy(LOGIN_URL), classList, deserializerList);
// Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter
Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory)new TrustingProtocolSocketFactory(), HTTPS_PORT));
} catch (final IOException e) {
s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
} }
gson = new GsonBuilder().registerTypeAdapter(NatRule.class, new NatRuleAdapter()).setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); public NiciraNvpApi(final String address, final String username, final String password) {
this();
restConnector.setControllerAddress(address);
restConnector.setAdminCredentials(username, password);
} }
public void setControllerAddress(final String address) { public void setControllerAddress(final String address) {
host = address; restConnector.setControllerAddress(address);
} }
public void setAdminCredentials(final String username, final String password) { public void setAdminCredentials(final String username, final String password) {
adminuser = username; restConnector.setAdminCredentials(username, password);
adminpass = password;
} }
/** /**
* Logs into the Nicira API. The cookie is stored in the <code>_authcookie<code> variable. * POST
* <p>
* The method returns false if the login failed or the connection could not be made.
* *
* @param entity
* @return
* @throws NiciraNvpApiException
*/ */
protected void login() throws NiciraNvpApiException { protected <T> T create(final T entity) throws NiciraNvpApiException {
String url; final String uri = prefixMap.get(entity.getClass());
return createWithUri(entity, uri);
if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) {
throw new NiciraNvpApiException("Hostname/credentials are null or empty");
} }
/**
* POST
*
* @param entity
* @return
* @throws NiciraNvpApiException
*/
protected <T> T createWithUri(final T entity, final String uri) throws NiciraNvpApiException {
T createdEntity;
try { try {
url = new URL(protocol, host, "/ws.v1/login").toString(); createdEntity = restConnector.executeCreateObject(entity, new TypeToken<T>() {
} catch (final MalformedURLException e) { }.getType(), uri, Collections.<String, String> emptyMap());
s_logger.error("Unable to build Nicira API URL", e); } catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException("Unable to build Nicira API URL", e); throw new NiciraNvpApiException(e);
} }
final PostMethod pm = new PostMethod(url); return createdEntity;
pm.addParameter("username", adminuser); }
pm.addParameter("password", adminpass);
/**
* GET list of items
*
* @return
* @throws NiciraNvpApiException
*/
protected <T> NiciraNvpList<T> find(final Class<T> clazz) throws NiciraNvpApiException {
return find(null, clazz);
}
/**
* GET list of items
*
* @param uuid
* @return
* @throws NiciraNvpApiException
*/
public <T> NiciraNvpList<T> find(final String uuid, final Class<T> clazz) throws NiciraNvpApiException {
final String uri = prefixMap.get(clazz);
Map<String, String> params = defaultListParams;
if (uuid != null) {
params = new HashMap<String, String>(defaultListParams);
params.put("uuid", uuid);
}
NiciraNvpList<T> entities;
try { try {
client.executeMethod(pm); entities = restConnector.executeRetrieveObject(listTypeMap.get(clazz), uri, params);
} catch (final HttpException e) { } catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException("Nicira NVP API login failed ", e); throw new NiciraNvpApiException(e);
} catch (final IOException e) {
throw new NiciraNvpApiException("Nicira NVP API login failed ", e);
} finally {
pm.releaseConnection();
} }
if (pm.getStatusCode() != HttpStatus.SC_OK) { if (entities == null) {
s_logger.error("Nicira NVP API login failed : " + pm.getStatusText()); throw new NiciraNvpApiException("Unexpected response from API");
throw new NiciraNvpApiException("Nicira NVP API login failed " + pm.getStatusText());
} }
// Extract the version for later use return entities;
if (pm.getResponseHeader("Server") != null) {
nvpVersion = pm.getResponseHeader("Server").getValue();
s_logger.debug("NVP Controller reports version " + nvpVersion);
} }
// Success; the cookie required for login is kept in _client /**
* PUT item given a UUID as key and an item object
* with the new data
*
* @param item
* @param uuid
* @throws NiciraNvpApiException
*/
public <T> void update(final T item, final String uuid)
throws NiciraNvpApiException {
final String uri = prefixMap.get(item.getClass()) + "/" + uuid;
updateWithUri(item, uri);
}
/**
* PUT item given a UUID as key and an item object
* with the new data
*
* @param item
* @param uuid
* @throws NiciraNvpApiException
*/
public <T> void updateWithUri(final T item, final String uri)
throws NiciraNvpApiException {
try {
restConnector.executeUpdateObject(item, uri, Collections.<String, String> emptyMap());
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
}
/**
* DELETE Security Profile given a UUID as key
*
* @param securityProfileUuid
* @throws NiciraNvpApiException
*/
public <T> void delete(final String uuid, final Class<T> clazz)
throws NiciraNvpApiException {
final String uri = prefixMap.get(clazz) + "/" + uuid;
deleteWithUri(uri);
}
/**
* DELETE Security Profile given a UUID as key
*
* @param securityProfileUuid
* @throws NiciraNvpApiException
*/
public <T> void deleteWithUri(final String uri)
throws NiciraNvpApiException {
try {
restConnector.executeDeleteObject(uri);
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
} }
/** /**
@ -341,111 +350,68 @@ public class NiciraNvpApi {
delete(aclUuid, Acl.class); delete(aclUuid, Acl.class);
} }
/** public LogicalSwitch createLogicalSwitch(final LogicalSwitch logicalSwitch) throws NiciraNvpApiException {
* POST return create(logicalSwitch);
*
* @param entity
* @return
* @throws NiciraNvpApiException
*/
protected <T> T create(final T entity) throws NiciraNvpApiException {
final String uri = prefixMap.get(entity.getClass());
final T createdEntity = executeCreateObject(entity, new TypeToken<T>() {
}.getType(), uri, Collections.<String, String> emptyMap());
return createdEntity;
} }
/** /**
* GET list of items * GET list of {@link LogicalSwitch}
* *
* @return * @return
* @throws NiciraNvpApiException * @throws NiciraNvpApiException
*/ */
protected <T> NiciraNvpList<T> find(final Class<T> clazz) throws NiciraNvpApiException { public NiciraNvpList<LogicalSwitch> findLogicalSwitch() throws NiciraNvpApiException {
return find(null, clazz); return findLogicalSwitch(null);
} }
/** /**
* GET list of items * GET list of {@link LogicalSwitch} filtered by UUID
* *
* @param uuid * @param uuid
* @return * @return
* @throws NiciraNvpApiException * @throws NiciraNvpApiException
*/ */
public <T> NiciraNvpList<T> find(final String uuid, final Class<T> clazz) throws NiciraNvpApiException { public NiciraNvpList<LogicalSwitch> findLogicalSwitch(final String uuid) throws NiciraNvpApiException {
final String uri = prefixMap.get(clazz); return find(uuid, LogicalSwitch.class);
Map<String, String> params = defaultListParams;
if (uuid != null) {
params = new HashMap<String, String>(defaultListParams);
params.put("uuid", uuid);
}
final NiciraNvpList<T> entities = executeRetrieveObject(listTypeMap.get(clazz), uri, params);
if (entities == null) {
throw new NiciraNvpApiException("Unexpected response from API");
}
return entities;
} }
/** /**
* PUT item given a UUID as key and an item object * PUT {@link LogicalSwitch} given a UUID as key and a {@link LogicalSwitch}
* with the new data * with the new data
* *
* @param item * @param logicalSwitch
* @param uuid * @param logicalSwitchUuid
* @throws NiciraNvpApiException * @throws NiciraNvpApiException
*/ */
public <T> void update(final T item, public void updateLogicalSwitch(final LogicalSwitch logicalSwitch,
final String uuid) final String logicalSwitchUuid)
throws NiciraNvpApiException { throws NiciraNvpApiException {
final String uri = prefixMap.get(item.getClass()) + "/" + uuid; update(logicalSwitch, logicalSwitchUuid);
executeUpdateObject(item, uri, Collections.<String, String> emptyMap());
}
/**
* DELETE Security Profile given a UUID as key
*
* @param securityProfileUuid
* @throws NiciraNvpApiException
*/
public <T> void delete(final String uuid, final Class<T> clazz)
throws NiciraNvpApiException {
final String uri = prefixMap.get(clazz) + "/" + uuid;
executeDeleteObject(uri);
}
public LogicalSwitch createLogicalSwitch(final LogicalSwitch logicalSwitch) throws NiciraNvpApiException {
final String uri = SWITCH_URI_PREFIX;
final LogicalSwitch createdLogicalSwitch = executeCreateObject(logicalSwitch, new TypeToken<LogicalSwitch>() {
}.getType(), uri, Collections.<String, String> emptyMap());
return createdLogicalSwitch;
} }
public void deleteLogicalSwitch(final String uuid) throws NiciraNvpApiException { public void deleteLogicalSwitch(final String uuid) throws NiciraNvpApiException {
final String uri = SWITCH_URI_PREFIX + "/" + uuid; delete(uuid, LogicalSwitch.class);
executeDeleteObject(uri);
} }
public LogicalSwitchPort createLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException { public LogicalSwitchPort createLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException {
final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport"; final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport";
final LogicalSwitchPort createdLogicalSwitchPort = executeCreateObject(logicalSwitchPort, new TypeToken<LogicalSwitchPort>() { return createWithUri(logicalSwitchPort, uri);
}.getType(), uri, Collections.<String, String> emptyMap());
return createdLogicalSwitchPort;
} }
public void modifyLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid, final Attachment attachment) throws NiciraNvpApiException { public void updateLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException {
final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPort.getUuid();
updateWithUri(logicalSwitchPort, uri);
}
public void updateLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid,
final Attachment attachment) throws NiciraNvpApiException {
final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid + "/attachment"; final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid + "/attachment";
executeUpdateObject(attachment, uri, Collections.<String, String> emptyMap()); updateWithUri(attachment, uri);
} }
public void deleteLogicalSwitchPort(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException { public void deleteLogicalSwitchPort(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException {
final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid; final String uri = SWITCH_URI_PREFIX + "/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid;
executeDeleteObject(uri); deleteWithUri(uri);
} }
public String findLogicalSwitchPortUuidByVifAttachmentUuid(final String logicalSwitchUuid, final String vifAttachmentUuid) throws NiciraNvpApiException { public String findLogicalSwitchPortUuidByVifAttachmentUuid(final String logicalSwitchUuid, final String vifAttachmentUuid) throws NiciraNvpApiException {
@ -454,8 +420,13 @@ public class NiciraNvpApi {
params.put("attachment_vif_uuid", vifAttachmentUuid); params.put("attachment_vif_uuid", vifAttachmentUuid);
params.put("fields", "uuid"); params.put("fields", "uuid");
final NiciraNvpList<LogicalSwitchPort> lspl = executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalSwitchPort>>() { NiciraNvpList<LogicalSwitchPort> lspl;
try {
lspl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalSwitchPort>>() {
}.getType(), uri, params); }.getType(), uri, params);
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
if (lspl == null || lspl.getResultCount() != 1) { if (lspl == null || lspl.getResultCount() != 1) {
throw new NiciraNvpApiException("Unexpected response from API"); throw new NiciraNvpApiException("Unexpected response from API");
@ -467,8 +438,13 @@ public class NiciraNvpApi {
public ControlClusterStatus getControlClusterStatus() throws NiciraNvpApiException { public ControlClusterStatus getControlClusterStatus() throws NiciraNvpApiException {
final String uri = "/ws.v1/control-cluster/status"; final String uri = "/ws.v1/control-cluster/status";
final ControlClusterStatus ccs = executeRetrieveObject(new TypeToken<ControlClusterStatus>() { ControlClusterStatus ccs;
try {
ccs = restConnector.executeRetrieveObject(new TypeToken<ControlClusterStatus>() {
}.getType(), uri, null); }.getType(), uri, null);
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
return ccs; return ccs;
} }
@ -479,8 +455,13 @@ public class NiciraNvpApi {
params.put("uuid", logicalSwitchPortUuid); params.put("uuid", logicalSwitchPortUuid);
params.put("fields", "uuid"); params.put("fields", "uuid");
final NiciraNvpList<LogicalSwitchPort> lspl = executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalSwitchPort>>() { NiciraNvpList<LogicalSwitchPort> lspl;
try {
lspl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalSwitchPort>>() {
}.getType(), uri, params); }.getType(), uri, params);
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
if (lspl == null) { if (lspl == null) {
throw new NiciraNvpApiException("Unexpected response from API"); throw new NiciraNvpApiException("Unexpected response from API");
@ -489,64 +470,101 @@ public class NiciraNvpApi {
return lspl; return lspl;
} }
public LogicalRouterConfig createLogicalRouter(final LogicalRouterConfig logicalRouterConfig) throws NiciraNvpApiException { public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortsByUuid(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX; final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
final Map<String, String> params = new HashMap<String, String>();
params.put("uuid", logicalRouterPortUuid);
params.put("fields", "uuid");
final LogicalRouterConfig lrc = executeCreateObject(logicalRouterConfig, new TypeToken<LogicalRouterConfig>() { NiciraNvpList<LogicalRouterPort> lrpl;
}.getType(), uri, Collections.<String, String> emptyMap()); try {
lrpl = restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
}.getType(), uri, params);
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
return lrc; if (lrpl == null) {
throw new NiciraNvpApiException("Unexpected response from API");
}
return lrpl;
}
public LogicalRouter createLogicalRouter(final LogicalRouter logicalRouter) throws NiciraNvpApiException {
return create(logicalRouter);
}
/**
* GET list of {@link LogicalRouter}
*
* @return
* @throws NiciraNvpApiException
*/
public NiciraNvpList<LogicalRouter> findLogicalRouter() throws NiciraNvpApiException {
return findLogicalRouter(null);
}
/**
* GET list of {@link LogicalRouter} filtered by UUID
*
* @param uuid
* @return
* @throws NiciraNvpApiException
*/
public NiciraNvpList<LogicalRouter> findLogicalRouter(final String uuid) throws NiciraNvpApiException {
return find(uuid, LogicalRouter.class);
}
public LogicalRouter findOneLogicalRouterByUuid(final String logicalRouterUuid) throws NiciraNvpApiException {
return findLogicalRouter(logicalRouterUuid).getResults().get(0);
}
public void updateLogicalRouter(final LogicalRouter logicalRouter,
final String logicalRouterUuid)
throws NiciraNvpApiException {
update(logicalRouter, logicalRouterUuid);
} }
public void deleteLogicalRouter(final String logicalRouterUuid) throws NiciraNvpApiException { public void deleteLogicalRouter(final String logicalRouterUuid) throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid; final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid;
deleteWithUri(uri);
executeDeleteObject(uri);
} }
public LogicalRouterPort createLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { public LogicalRouterPort createLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport"; final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport";
return createWithUri(logicalRouterPort, uri);
final LogicalRouterPort lrp = executeCreateObject(logicalRouterPort, new TypeToken<LogicalRouterPort>() {
}.getType(), uri, Collections.<String, String> emptyMap());
return lrp;
} }
public void deleteLogicalRouterPort(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException { public void deleteLogicalRouterPort(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid; final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid;
deleteWithUri(uri);
executeDeleteObject(uri);
} }
public void modifyLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { public void updateLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid(); final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid();
updateWithUri(logicalRouterPort, uri);
executeUpdateObject(logicalRouterPort, uri, Collections.<String, String> emptyMap());
} }
public void modifyLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment) public void updateLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment)
throws NiciraNvpApiException { throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment"; final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment";
executeUpdateObject(attachment, uri, Collections.<String, String> emptyMap()); updateWithUri(attachment, uri);
} }
public NatRule createLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { public NatRule createLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat"; final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat";
return createWithUri(natRule, uri);
return executeCreateObject(natRule, new TypeToken<NatRule>() {
}.getType(), uri, Collections.<String, String> emptyMap());
} }
public void modifyLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { public void updateLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRule.getUuid(); final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRule.getUuid();
updateWithUri(natRule, uri);
executeUpdateObject(natRule, uri, Collections.<String, String> emptyMap());
} }
public void deleteLogicalRouterNatRule(final String logicalRouterUuid, final UUID natRuleUuid) throws NiciraNvpApiException { public void deleteLogicalRouterNatRule(final String logicalRouterUuid, final UUID natRuleUuid) throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRuleUuid.toString(); final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/nat/" + natRuleUuid.toString();
deleteWithUri(uri);
executeDeleteObject(uri);
} }
public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid, public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid,
@ -557,21 +575,12 @@ public class NiciraNvpApi {
params.put("attachment_vlan", "0"); params.put("attachment_vlan", "0");
params.put("fields", "*"); params.put("fields", "*");
return executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() { try {
return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
}.getType(), uri, params); }.getType(), uri, params);
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
} }
public LogicalRouterConfig findOneLogicalRouterByUuid(final String logicalRouterUuid) throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid;
return executeRetrieveObject(new TypeToken<LogicalRouterConfig>() {
}.getType(), uri, Collections.<String, String> emptyMap());
}
public void updateLogicalRouterPortConfig(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException {
final String uri = ROUTER_URI_PREFIX + "/" + logicalRouterUuid + "/lport" + logicalRouterPort.getUuid();
executeUpdateObject(logicalRouterPort, uri, Collections.<String, String> emptyMap());
} }
public NiciraNvpList<NatRule> findNatRulesByLogicalRouterUuid(final String logicalRouterUuid) throws NiciraNvpApiException { public NiciraNvpList<NatRule> findNatRulesByLogicalRouterUuid(final String logicalRouterUuid) throws NiciraNvpApiException {
@ -579,8 +588,12 @@ public class NiciraNvpApi {
final Map<String, String> params = new HashMap<String, String>(); final Map<String, String> params = new HashMap<String, String>();
params.put("fields", "*"); params.put("fields", "*");
return executeRetrieveObject(new TypeToken<NiciraNvpList<NatRule>>() { try {
return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<NatRule>>() {
}.getType(), uri, params); }.getType(), uri, params);
} catch (final CloudstackRESTException e) {
throw new NiciraNvpApiException(e);
}
} }
public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceUuid(final String logicalRouterUuid, final String l3GatewayServiceUuid) public NiciraNvpList<LogicalRouterPort> findLogicalRouterPortByGatewayServiceUuid(final String logicalRouterUuid, final String l3GatewayServiceUuid)
@ -590,231 +603,11 @@ public class NiciraNvpApi {
params.put("fields", "*"); params.put("fields", "*");
params.put("attachment_gwsvc_uuid", l3GatewayServiceUuid); params.put("attachment_gwsvc_uuid", l3GatewayServiceUuid);
return executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() { try {
return restConnector.executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalRouterPort>>() {
}.getType(), uri, params); }.getType(), uri, params);
} } catch (final CloudstackRESTException e) {
protected <T> void executeUpdateObject(final T newObject, final String uri, final Map<String, String> parameters) throws NiciraNvpApiException {
if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) {
throw new NiciraNvpApiException("Hostname/credentials are null or empty");
}
final PutMethod pm = (PutMethod)createMethod(PUT_METHOD_TYPE, uri);
pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
try {
pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
} catch (final UnsupportedEncodingException e) {
throw new NiciraNvpApiException("Failed to encode json request body", e);
}
executeMethod(pm);
if (pm.getStatusCode() != HttpStatus.SC_OK) {
final String errorMessage = responseToErrorMessage(pm);
pm.releaseConnection();
s_logger.error("Failed to update object : " + errorMessage);
throw new NiciraNvpApiException("Failed to update object : " + errorMessage);
}
pm.releaseConnection();
}
@SuppressWarnings("unchecked")
protected <T> T executeCreateObject(final T newObject, final Type returnObjectType, final String uri, final Map<String, String> parameters)
throws NiciraNvpApiException {
if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) {
throw new NiciraNvpApiException("Hostname/credentials are null or empty");
}
final PostMethod pm = (PostMethod)createMethod(POST_METHOD_TYPE, uri);
pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
try {
pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
} catch (final UnsupportedEncodingException e) {
throw new NiciraNvpApiException("Failed to encode json request body", e);
}
executeMethod(pm);
if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
final String errorMessage = responseToErrorMessage(pm);
pm.releaseConnection();
s_logger.error("Failed to create object : " + errorMessage);
throw new NiciraNvpApiException("Failed to create object : " + errorMessage);
}
T result;
try {
result = (T)gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
} catch (final IOException e) {
throw new NiciraNvpApiException("Failed to decode json response body", e);
} finally {
pm.releaseConnection();
}
return result;
}
protected void executeDeleteObject(final String uri) throws NiciraNvpApiException {
if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) {
throw new NiciraNvpApiException("Hostname/credentials are null or empty");
}
final DeleteMethod dm = (DeleteMethod)createMethod(DELETE_METHOD_TYPE, uri);
dm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
executeMethod(dm);
if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
final String errorMessage = responseToErrorMessage(dm);
dm.releaseConnection();
s_logger.error("Failed to delete object : " + errorMessage);
throw new NiciraNvpApiException("Failed to delete object : " + errorMessage);
}
dm.releaseConnection();
}
@SuppressWarnings("unchecked")
protected <T> T executeRetrieveObject(final Type returnObjectType, final String uri, final Map<String, String> parameters) throws NiciraNvpApiException {
if (host == null || host.isEmpty() || adminuser == null || adminuser.isEmpty() || adminpass == null || adminpass.isEmpty()) {
throw new NiciraNvpApiException("Hostname/credentials are null or empty");
}
final GetMethod gm = (GetMethod)createMethod(GET_METHOD_TYPE, uri);
gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
if (parameters != null && !parameters.isEmpty()) {
final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
for (final Entry<String, String> e : parameters.entrySet()) {
nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue()));
}
gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
}
executeMethod(gm);
if (gm.getStatusCode() != HttpStatus.SC_OK) {
final String errorMessage = responseToErrorMessage(gm);
gm.releaseConnection();
s_logger.error("Failed to retrieve object : " + errorMessage);
throw new NiciraNvpApiException("Failed to retrieve object : " + errorMessage);
}
T returnValue;
try {
returnValue = (T)gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
} catch (final IOException e) {
s_logger.error("IOException while retrieving response body", e);
throw new NiciraNvpApiException(e); throw new NiciraNvpApiException(e);
} finally {
gm.releaseConnection();
}
return returnValue;
}
protected void executeMethod(final HttpMethodBase method) throws NiciraNvpApiException {
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
method.releaseConnection();
// login and try again
login();
client.executeMethod(method);
}
} catch (final HttpException e) {
s_logger.error("HttpException caught while trying to connect to the Nicira NVP Controller", e);
method.releaseConnection();
throw new NiciraNvpApiException("API call to Nicira NVP Controller Failed", e);
} catch (final IOException e) {
s_logger.error("IOException caught while trying to connect to the Nicira NVP Controller", e);
method.releaseConnection();
throw new NiciraNvpApiException("API call to Nicira NVP Controller Failed", e);
}
}
private String responseToErrorMessage(final HttpMethodBase method) {
assert method.isRequestSent() : "no use getting an error message unless the request is sent";
if (TEXT_HTML_CONTENT_TYPE.equals(method.getResponseHeader(CONTENT_TYPE).getValue())) {
// The error message is the response content
// Safety margin of 1024 characters, anything longer is probably useless
// and will clutter the logs
try {
return method.getResponseBodyAsString(BODY_RESP_MAX_LEN);
} catch (final IOException e) {
s_logger.debug("Error while loading response body", e);
}
}
// The default
return method.getStatusText();
}
/* The Nicira controller uses a self-signed certificate. The
* TrustingProtocolSocketFactory will accept any provided
* certificate when making an SSL connection to the SDN
* Manager
*/
private class TrustingProtocolSocketFactory implements SecureProtocolSocketFactory {
private SSLSocketFactory ssf;
public TrustingProtocolSocketFactory() throws IOException {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
// Trust always
}
@Override
public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
// Trust always
}
}};
try {
// Install the all-trusting trust manager
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
ssf = sc.getSocketFactory();
} catch (final KeyManagementException e) {
throw new IOException(e);
} catch (final NoSuchAlgorithmException e) {
throw new IOException(e);
}
}
@Override
public Socket createSocket(final String host, final int port) throws IOException {
return ssf.createSocket(host, port);
}
@Override
public Socket createSocket(final String address, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException {
return ssf.createSocket(address, port, localAddress, localPort);
}
@Override
public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
return ssf.createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
final int timeout = params.getConnectionTimeout();
if (timeout == 0) {
return createSocket(host, port, localAddress, localPort);
} else {
final Socket s = ssf.createSocket();
s.bind(new InetSocketAddress(localAddress, localPort));
s.connect(new InetSocketAddress(host, port), timeout);
return s;
}
} }
} }
@ -837,6 +630,24 @@ public class NiciraNvpApi {
throw new JsonParseException("Failed to deserialize type \"" + natRuleType + "\""); throw new JsonParseException("Failed to deserialize type \"" + natRuleType + "\"");
} }
}
public static class RoutingConfigAdapter implements JsonDeserializer<RoutingConfig> {
@Override
public RoutingConfig deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = jsonElement.getAsJsonObject();
if (!jsonObject.has("type")) {
throw new JsonParseException("Deserializing as a RoutingConfig, but no type present in the json object");
}
final String routingConfigType = jsonObject.get("type").getAsString();
if ("SingleDefaultRouteImplicitRoutingConfig".equals(routingConfigType)) {
return context.deserialize(jsonElement, SingleDefaultRouteImplicitRoutingConfig.class);
}
throw new JsonParseException("Failed to deserialize type \"" + routingConfigType + "\"");
}
} }
} }

View File

@ -22,11 +22,11 @@ package com.cloud.network.nicira;
/** /**
* *
*/ */
public class SingleDefaultRouteImplictRoutingConfig extends RoutingConfig { public class SingleDefaultRouteImplicitRoutingConfig extends RoutingConfig {
public RouterNextHop defaultRouteNextHop; public RouterNextHop defaultRouteNextHop;
public final String type = "SingleDefaultRouteImplicitRoutingConfig"; public final String type = "SingleDefaultRouteImplicitRoutingConfig";
public SingleDefaultRouteImplictRoutingConfig(RouterNextHop routerNextHop) { public SingleDefaultRouteImplicitRoutingConfig(final RouterNextHop routerNextHop) {
defaultRouteNextHop = routerNextHop; defaultRouteNextHop = routerNextHop;
} }
@ -34,7 +34,7 @@ public class SingleDefaultRouteImplictRoutingConfig extends RoutingConfig {
return defaultRouteNextHop; return defaultRouteNextHop;
} }
public void setDefaultRouteNextHop(RouterNextHop defaultRouteNextHop) { public void setDefaultRouteNextHop(final RouterNextHop defaultRouteNextHop) {
this.defaultRouteNextHop = defaultRouteNextHop; this.defaultRouteNextHop = defaultRouteNextHop;
} }
} }

View File

@ -19,6 +19,11 @@
package com.cloud.network.nicira; package com.cloud.network.nicira;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
public class VifAttachment extends Attachment { public class VifAttachment extends Attachment {
private final String type = "VifAttachment"; private final String type = "VifAttachment";
private String vifUuid; private String vifUuid;
@ -34,7 +39,7 @@ public class VifAttachment extends Attachment {
return vifUuid; return vifUuid;
} }
public void setVifUuid(String vifUuid) { public void setVifUuid(final String vifUuid) {
this.vifUuid = vifUuid; this.vifUuid = vifUuid;
} }
@ -42,4 +47,32 @@ public class VifAttachment extends Attachment {
return type; return type;
} }
@Override
public String toString() {
return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false);
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31)
.append(this.getClass())
.append(vifUuid)
.toHashCode();
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(this.getClass().isInstance(obj))) {
return false;
}
final VifAttachment another = (VifAttachment) obj;
return new EqualsBuilder().append(vifUuid, another.vifUuid).isEquals();
}
} }

View File

@ -66,7 +66,7 @@ import com.cloud.host.Host.Type;
import com.cloud.network.nicira.ControlClusterStatus; import com.cloud.network.nicira.ControlClusterStatus;
import com.cloud.network.nicira.DestinationNatRule; import com.cloud.network.nicira.DestinationNatRule;
import com.cloud.network.nicira.L3GatewayAttachment; import com.cloud.network.nicira.L3GatewayAttachment;
import com.cloud.network.nicira.LogicalRouterConfig; import com.cloud.network.nicira.LogicalRouter;
import com.cloud.network.nicira.LogicalRouterPort; import com.cloud.network.nicira.LogicalRouterPort;
import com.cloud.network.nicira.LogicalSwitch; import com.cloud.network.nicira.LogicalSwitch;
import com.cloud.network.nicira.LogicalSwitchPort; import com.cloud.network.nicira.LogicalSwitchPort;
@ -78,7 +78,7 @@ import com.cloud.network.nicira.NiciraNvpList;
import com.cloud.network.nicira.NiciraNvpTag; import com.cloud.network.nicira.NiciraNvpTag;
import com.cloud.network.nicira.PatchAttachment; import com.cloud.network.nicira.PatchAttachment;
import com.cloud.network.nicira.RouterNextHop; import com.cloud.network.nicira.RouterNextHop;
import com.cloud.network.nicira.SingleDefaultRouteImplictRoutingConfig; import com.cloud.network.nicira.SingleDefaultRouteImplicitRoutingConfig;
import com.cloud.network.nicira.SourceNatRule; import com.cloud.network.nicira.SourceNatRule;
import com.cloud.network.nicira.TransportZoneBinding; import com.cloud.network.nicira.TransportZoneBinding;
import com.cloud.network.nicira.VifAttachment; import com.cloud.network.nicira.VifAttachment;
@ -294,7 +294,7 @@ public class NiciraNvpResource implements ServerResource {
LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true); LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true);
LogicalSwitchPort newPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort); LogicalSwitchPort newPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort);
try { try {
niciraNvpApi.modifyLogicalSwitchPortAttachment(cmd.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid)); niciraNvpApi.updateLogicalSwitchPortAttachment(cmd.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid));
} catch (NiciraNvpApiException ex) { } catch (NiciraNvpApiException ex) {
s_logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport"); s_logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport");
niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), newPort.getUuid()); niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), newPort.getUuid());
@ -334,7 +334,7 @@ public class NiciraNvpResource implements ServerResource {
List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>(); List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
tags.add(new NiciraNvpTag("cs_account", cmd.getOwnerName())); tags.add(new NiciraNvpTag("cs_account", cmd.getOwnerName()));
niciraNvpApi.modifyLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, new VifAttachment(attachmentUuid)); niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, new VifAttachment(attachmentUuid));
return new UpdateLogicalSwitchPortAnswer(cmd, true, "Attachment for " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid); return new UpdateLogicalSwitchPortAnswer(cmd, true, "Attachment for " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid);
} catch (NiciraNvpApiException e) { } catch (NiciraNvpApiException e) {
if (numRetries > 0) { if (numRetries > 0) {
@ -383,10 +383,10 @@ public class NiciraNvpResource implements ServerResource {
try { try {
// Create the Router // Create the Router
LogicalRouterConfig lrc = new LogicalRouterConfig(); LogicalRouter lrc = new LogicalRouter();
lrc.setDisplayName(truncate(routerName, NAME_MAX_LEN)); lrc.setDisplayName(truncate(routerName, NAME_MAX_LEN));
lrc.setTags(tags); lrc.setTags(tags);
lrc.setRoutingConfig(new SingleDefaultRouteImplictRoutingConfig(new RouterNextHop(publicNetworkNextHopIp))); lrc.setRoutingConfig(new SingleDefaultRouteImplicitRoutingConfig(new RouterNextHop(publicNetworkNextHopIp)));
lrc = niciraNvpApi.createLogicalRouter(lrc); lrc = niciraNvpApi.createLogicalRouter(lrc);
// store the switchport for rollback // store the switchport for rollback
@ -408,7 +408,7 @@ public class NiciraNvpResource implements ServerResource {
if (cmd.getVlanId() != 0) { if (cmd.getVlanId() != 0) {
attachment.setVlanId(cmd.getVlanId()); attachment.setVlanId(cmd.getVlanId());
} }
niciraNvpApi.modifyLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment); niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment);
// Create the inside port for the router // Create the inside port for the router
LogicalRouterPort lrpi = new LogicalRouterPort(); LogicalRouterPort lrpi = new LogicalRouterPort();
@ -425,10 +425,10 @@ public class NiciraNvpResource implements ServerResource {
lsp = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lsp); lsp = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lsp);
// Attach the inside router port to the lswitch port with a PatchAttachment // Attach the inside router port to the lswitch port with a PatchAttachment
niciraNvpApi.modifyLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), new PatchAttachment(lsp.getUuid())); niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), new PatchAttachment(lsp.getUuid()));
// Attach the inside lswitch port to the router with a PatchAttachment // Attach the inside lswitch port to the router with a PatchAttachment
niciraNvpApi.modifyLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), new PatchAttachment(lrpi.getUuid())); niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), new PatchAttachment(lrpi.getUuid()));
// Setup the source nat rule // Setup the source nat rule
SourceNatRule snr = new SourceNatRule(); SourceNatRule snr = new SourceNatRule();
@ -484,7 +484,7 @@ public class NiciraNvpResource implements ServerResource {
} }
LogicalRouterPort lrp = ports.getResults().get(0); LogicalRouterPort lrp = ports.getResults().get(0);
lrp.setIpAddresses(cmd.getPublicCidrs()); lrp.setIpAddresses(cmd.getPublicCidrs());
niciraNvpApi.modifyLogicalRouterPort(cmd.getLogicalRouterUuid(), lrp); niciraNvpApi.updateLogicalRouterPort(cmd.getLogicalRouterUuid(), lrp);
return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, true, "Configured " + cmd.getPublicCidrs().size() + " ip addresses on logical router uuid " + return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, true, "Configured " + cmd.getPublicCidrs().size() + " ip addresses on logical router uuid " +
cmd.getLogicalRouterUuid()); cmd.getLogicalRouterUuid());

View File

@ -104,7 +104,7 @@ public class NiciraNvpElementTest {
@Test @Test
public void canHandleTest() { public void canHandleTest() {
Network net = mock(Network.class); final Network net = mock(Network.class);
when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
when(net.getId()).thenReturn(NETWORK_ID); when(net.getId()).thenReturn(NETWORK_ID);
@ -134,43 +134,43 @@ public class NiciraNvpElementTest {
@Test @Test
public void implementTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { public void implementTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
Network network = mock(Network.class); final Network network = mock(Network.class);
when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
when(network.getId()).thenReturn(NETWORK_ID); when(network.getId()).thenReturn(NETWORK_ID);
NetworkOffering offering = mock(NetworkOffering.class); final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated); when(offering.getGuestType()).thenReturn(GuestType.Isolated);
mock(DeployDestination.class); mock(DeployDestination.class);
Domain dom = mock(Domain.class); final Domain dom = mock(Domain.class);
when(dom.getName()).thenReturn("domain"); when(dom.getName()).thenReturn("domain");
Account acc = mock(Account.class); final Account acc = mock(Account.class);
when(acc.getAccountName()).thenReturn("accountname"); when(acc.getAccountName()).thenReturn("accountname");
ReservationContext context = mock(ReservationContext.class); final ReservationContext context = mock(ReservationContext.class);
when(context.getDomain()).thenReturn(dom); when(context.getDomain()).thenReturn(dom);
when(context.getAccount()).thenReturn(acc); when(context.getAccount()).thenReturn(acc);
} }
@Test @Test
public void applyIpTest() throws ResourceUnavailableException { public void applyIpTest() throws ResourceUnavailableException {
Network network = mock(Network.class); final Network network = mock(Network.class);
when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
when(network.getId()).thenReturn(NETWORK_ID); when(network.getId()).thenReturn(NETWORK_ID);
when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
NetworkOffering offering = mock(NetworkOffering.class); final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated); when(offering.getGuestType()).thenReturn(GuestType.Isolated);
List<PublicIpAddress> ipAddresses = new ArrayList<PublicIpAddress>(); final List<PublicIpAddress> ipAddresses = new ArrayList<PublicIpAddress>();
PublicIpAddress pipReleased = mock(PublicIpAddress.class); final PublicIpAddress pipReleased = mock(PublicIpAddress.class);
PublicIpAddress pipAllocated = mock(PublicIpAddress.class); final PublicIpAddress pipAllocated = mock(PublicIpAddress.class);
Ip ipReleased = new Ip("42.10.10.10"); final Ip ipReleased = new Ip("42.10.10.10");
Ip ipAllocated = new Ip("10.10.10.10"); final Ip ipAllocated = new Ip("10.10.10.10");
when(pipAllocated.getState()).thenReturn(IpAddress.State.Allocated); when(pipAllocated.getState()).thenReturn(IpAddress.State.Allocated);
when(pipAllocated.getAddress()).thenReturn(ipAllocated); when(pipAllocated.getAddress()).thenReturn(ipAllocated);
when(pipAllocated.getNetmask()).thenReturn("255.255.255.0"); when(pipAllocated.getNetmask()).thenReturn("255.255.255.0");
@ -180,25 +180,25 @@ public class NiciraNvpElementTest {
ipAddresses.add(pipAllocated); ipAddresses.add(pipAllocated);
ipAddresses.add(pipReleased); ipAddresses.add(pipReleased);
Set<Service> services = new HashSet<Service>(); final Set<Service> services = new HashSet<Service>();
services.add(Service.SourceNat); services.add(Service.SourceNat);
services.add(Service.StaticNat); services.add(Service.StaticNat);
services.add(Service.PortForwarding); services.add(Service.PortForwarding);
List<NiciraNvpDeviceVO> deviceList = new ArrayList<NiciraNvpDeviceVO>(); final List<NiciraNvpDeviceVO> deviceList = new ArrayList<NiciraNvpDeviceVO>();
NiciraNvpDeviceVO nndVO = mock(NiciraNvpDeviceVO.class); final NiciraNvpDeviceVO nndVO = mock(NiciraNvpDeviceVO.class);
NiciraNvpRouterMappingVO nnrmVO = mock(NiciraNvpRouterMappingVO.class); final NiciraNvpRouterMappingVO nnrmVO = mock(NiciraNvpRouterMappingVO.class);
when(niciraNvpRouterMappingDao.findByNetworkId(NETWORK_ID)).thenReturn(nnrmVO); when(niciraNvpRouterMappingDao.findByNetworkId(NETWORK_ID)).thenReturn(nnrmVO);
when(nnrmVO.getLogicalRouterUuid()).thenReturn("abcde"); when(nnrmVO.getLogicalRouterUuid()).thenReturn("abcde");
when(nndVO.getHostId()).thenReturn(NETWORK_ID); when(nndVO.getHostId()).thenReturn(NETWORK_ID);
HostVO hvo = mock(HostVO.class); final HostVO hvo = mock(HostVO.class);
when(hvo.getId()).thenReturn(NETWORK_ID); when(hvo.getId()).thenReturn(NETWORK_ID);
when(hvo.getDetail("l3gatewayserviceuuid")).thenReturn("abcde"); when(hvo.getDetail("l3gatewayserviceuuid")).thenReturn("abcde");
when(hostDao.findById(NETWORK_ID)).thenReturn(hvo); when(hostDao.findById(NETWORK_ID)).thenReturn(hvo);
deviceList.add(nndVO); deviceList.add(nndVO);
when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(deviceList); when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(deviceList);
ConfigurePublicIpsOnLogicalRouterAnswer answer = mock(ConfigurePublicIpsOnLogicalRouterAnswer.class); final ConfigurePublicIpsOnLogicalRouterAnswer answer = mock(ConfigurePublicIpsOnLogicalRouterAnswer.class);
when(answer.getResult()).thenReturn(true); when(answer.getResult()).thenReturn(true);
when(agentManager.easySend(eq(NETWORK_ID), any(ConfigurePublicIpsOnLogicalRouterCommand.class))).thenReturn(answer); when(agentManager.easySend(eq(NETWORK_ID), any(ConfigurePublicIpsOnLogicalRouterCommand.class))).thenReturn(answer);
@ -206,8 +206,8 @@ public class NiciraNvpElementTest {
verify(agentManager, atLeast(1)).easySend(eq(NETWORK_ID), argThat(new ArgumentMatcher<ConfigurePublicIpsOnLogicalRouterCommand>() { verify(agentManager, atLeast(1)).easySend(eq(NETWORK_ID), argThat(new ArgumentMatcher<ConfigurePublicIpsOnLogicalRouterCommand>() {
@Override @Override
public boolean matches(Object argument) { public boolean matches(final Object argument) {
ConfigurePublicIpsOnLogicalRouterCommand command = (ConfigurePublicIpsOnLogicalRouterCommand)argument; final ConfigurePublicIpsOnLogicalRouterCommand command = (ConfigurePublicIpsOnLogicalRouterCommand)argument;
if (command.getPublicCidrs().size() == 1) if (command.getPublicCidrs().size() == 1)
return true; return true;
return false; return false;

View File

@ -99,7 +99,7 @@ public class NiciraNvpGuestNetworkGuruTest {
guru.agentMgr = agentmgr; guru.agentMgr = agentmgr;
guru.networkDao = netdao; guru.networkDao = netdao;
DataCenterVO dc = mock(DataCenterVO.class); final DataCenterVO dc = mock(DataCenterVO.class);
when(dc.getNetworkType()).thenReturn(NetworkType.Advanced); when(dc.getNetworkType()).thenReturn(NetworkType.Advanced);
when(dc.getGuestNetworkCidr()).thenReturn("10.1.1.1/24"); when(dc.getGuestNetworkCidr()).thenReturn("10.1.1.1/24");
@ -108,12 +108,12 @@ public class NiciraNvpGuestNetworkGuruTest {
@Test @Test
public void testCanHandle() { public void testCanHandle() {
NetworkOffering offering = mock(NetworkOffering.class); final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated); when(offering.getGuestType()).thenReturn(GuestType.Isolated);
PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
when(physnet.getId()).thenReturn(NETWORK_ID); when(physnet.getId()).thenReturn(NETWORK_ID);
@ -142,34 +142,34 @@ public class NiciraNvpGuestNetworkGuruTest {
@Test @Test
public void testDesign() { public void testDesign() {
PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnetdao.findById((Long)any())).thenReturn(physnet); when(physnetdao.findById((Long)any())).thenReturn(physnet);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
when(physnet.getId()).thenReturn(NETWORK_ID); when(physnet.getId()).thenReturn(NETWORK_ID);
NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
when(device.getId()).thenReturn(1L); when(device.getId()).thenReturn(1L);
NetworkOffering offering = mock(NetworkOffering.class); final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated); when(offering.getGuestType()).thenReturn(GuestType.Isolated);
when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true); when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true);
DeploymentPlan plan = mock(DeploymentPlan.class); final DeploymentPlan plan = mock(DeploymentPlan.class);
Network network = mock(Network.class); final Network network = mock(Network.class);
Account account = mock(Account.class); final Account account = mock(Account.class);
Network designednetwork = guru.design(offering, plan, network, account); final Network designednetwork = guru.design(offering, plan, network, account);
assertTrue(designednetwork != null); assertTrue(designednetwork != null);
assertTrue(designednetwork.getBroadcastDomainType() == BroadcastDomainType.Lswitch); assertTrue(designednetwork.getBroadcastDomainType() == BroadcastDomainType.Lswitch);
} }
@Test @Test
public void testDesignNoElementOnPhysicalNetwork() { public void testDesignNoElementOnPhysicalNetwork() {
PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnetdao.findById((Long)any())).thenReturn(physnet); when(physnetdao.findById((Long)any())).thenReturn(physnet);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
when(physnet.getId()).thenReturn(NETWORK_ID); when(physnet.getId()).thenReturn(NETWORK_ID);
@ -177,22 +177,22 @@ public class NiciraNvpGuestNetworkGuruTest {
mock(NiciraNvpDeviceVO.class); mock(NiciraNvpDeviceVO.class);
when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections.<NiciraNvpDeviceVO> emptyList()); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections.<NiciraNvpDeviceVO> emptyList());
NetworkOffering offering = mock(NetworkOffering.class); final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated); when(offering.getGuestType()).thenReturn(GuestType.Isolated);
DeploymentPlan plan = mock(DeploymentPlan.class); final DeploymentPlan plan = mock(DeploymentPlan.class);
Network network = mock(Network.class); final Network network = mock(Network.class);
Account account = mock(Account.class); final Account account = mock(Account.class);
Network designednetwork = guru.design(offering, plan, network, account); final Network designednetwork = guru.design(offering, plan, network, account);
assertTrue(designednetwork == null); assertTrue(designednetwork == null);
} }
@Test @Test
public void testDesignNoIsolationMethodSTT() { public void testDesignNoIsolationMethodSTT() {
PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnetdao.findById((Long)any())).thenReturn(physnet); when(physnetdao.findById((Long)any())).thenReturn(physnet);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"})); when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"}));
when(physnet.getId()).thenReturn(NETWORK_ID); when(physnet.getId()).thenReturn(NETWORK_ID);
@ -200,57 +200,57 @@ public class NiciraNvpGuestNetworkGuruTest {
mock(NiciraNvpDeviceVO.class); mock(NiciraNvpDeviceVO.class);
when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections.<NiciraNvpDeviceVO> emptyList()); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections.<NiciraNvpDeviceVO> emptyList());
NetworkOffering offering = mock(NetworkOffering.class); final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated); when(offering.getGuestType()).thenReturn(GuestType.Isolated);
DeploymentPlan plan = mock(DeploymentPlan.class); final DeploymentPlan plan = mock(DeploymentPlan.class);
Network network = mock(Network.class); final Network network = mock(Network.class);
Account account = mock(Account.class); final Account account = mock(Account.class);
Network designednetwork = guru.design(offering, plan, network, account); final Network designednetwork = guru.design(offering, plan, network, account);
assertTrue(designednetwork == null); assertTrue(designednetwork == null);
} }
@Test @Test
public void testDesignNoConnectivityInOffering() { public void testDesignNoConnectivityInOffering() {
PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnetdao.findById((Long)any())).thenReturn(physnet); when(physnetdao.findById((Long)any())).thenReturn(physnet);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
when(physnet.getId()).thenReturn(NETWORK_ID); when(physnet.getId()).thenReturn(NETWORK_ID);
NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
when(device.getId()).thenReturn(1L); when(device.getId()).thenReturn(1L);
NetworkOffering offering = mock(NetworkOffering.class); final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated); when(offering.getGuestType()).thenReturn(GuestType.Isolated);
when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
DeploymentPlan plan = mock(DeploymentPlan.class); final DeploymentPlan plan = mock(DeploymentPlan.class);
Network network = mock(Network.class); final Network network = mock(Network.class);
Account account = mock(Account.class); final Account account = mock(Account.class);
Network designednetwork = guru.design(offering, plan, network, account); final Network designednetwork = guru.design(offering, plan, network, account);
assertTrue(designednetwork == null); assertTrue(designednetwork == null);
} }
@Test @Test
public void testImplement() throws InsufficientVirtualNetworkCapcityException { public void testImplement() throws InsufficientVirtualNetworkCapcityException {
PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnetdao.findById((Long)any())).thenReturn(physnet); when(physnetdao.findById((Long)any())).thenReturn(physnet);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
when(physnet.getId()).thenReturn(NETWORK_ID); when(physnet.getId()).thenReturn(NETWORK_ID);
NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
when(device.getId()).thenReturn(1L); when(device.getId()).thenReturn(1L);
NetworkOffering offering = mock(NetworkOffering.class); final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated); when(offering.getGuestType()).thenReturn(GuestType.Isolated);
@ -259,53 +259,53 @@ public class NiciraNvpGuestNetworkGuruTest {
mock(DeploymentPlan.class); mock(DeploymentPlan.class);
NetworkVO network = mock(NetworkVO.class); final NetworkVO network = mock(NetworkVO.class);
when(network.getName()).thenReturn("testnetwork"); when(network.getName()).thenReturn("testnetwork");
when(network.getState()).thenReturn(State.Implementing); when(network.getState()).thenReturn(State.Implementing);
when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
DeployDestination dest = mock(DeployDestination.class); final DeployDestination dest = mock(DeployDestination.class);
DataCenter dc = mock(DataCenter.class); final DataCenter dc = mock(DataCenter.class);
when(dest.getDataCenter()).thenReturn(dc); when(dest.getDataCenter()).thenReturn(dc);
HostVO niciraHost = mock(HostVO.class); final HostVO niciraHost = mock(HostVO.class);
when(hostdao.findById(anyLong())).thenReturn(niciraHost); when(hostdao.findById(anyLong())).thenReturn(niciraHost);
when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
when(niciraHost.getId()).thenReturn(NETWORK_ID); when(niciraHost.getId()).thenReturn(NETWORK_ID);
when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
Domain dom = mock(Domain.class); final Domain dom = mock(Domain.class);
when(dom.getName()).thenReturn("domain"); when(dom.getName()).thenReturn("domain");
Account acc = mock(Account.class); final Account acc = mock(Account.class);
when(acc.getAccountName()).thenReturn("accountname"); when(acc.getAccountName()).thenReturn("accountname");
ReservationContext res = mock(ReservationContext.class); final ReservationContext res = mock(ReservationContext.class);
when(res.getDomain()).thenReturn(dom); when(res.getDomain()).thenReturn(dom);
when(res.getAccount()).thenReturn(acc); when(res.getAccount()).thenReturn(acc);
CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class);
when(answer.getResult()).thenReturn(true); when(answer.getResult()).thenReturn(true);
when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa");
when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
Network implementednetwork = guru.implement(network, offering, dest, res); final Network implementednetwork = guru.implement(network, offering, dest, res);
assertTrue(implementednetwork != null); assertTrue(implementednetwork != null);
verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any());
} }
@Test @Test
public void testImplementWithCidr() throws InsufficientVirtualNetworkCapcityException { public void testImplementWithCidr() throws InsufficientVirtualNetworkCapcityException {
PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnetdao.findById((Long)any())).thenReturn(physnet); when(physnetdao.findById((Long)any())).thenReturn(physnet);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
when(physnet.getId()).thenReturn(NETWORK_ID); when(physnet.getId()).thenReturn(NETWORK_ID);
NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
when(device.getId()).thenReturn(1L); when(device.getId()).thenReturn(1L);
NetworkOffering offering = mock(NetworkOffering.class); final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated); when(offering.getGuestType()).thenReturn(GuestType.Isolated);
@ -314,39 +314,39 @@ public class NiciraNvpGuestNetworkGuruTest {
mock(DeploymentPlan.class); mock(DeploymentPlan.class);
NetworkVO network = mock(NetworkVO.class); final NetworkVO network = mock(NetworkVO.class);
when(network.getName()).thenReturn("testnetwork"); when(network.getName()).thenReturn("testnetwork");
when(network.getState()).thenReturn(State.Implementing); when(network.getState()).thenReturn(State.Implementing);
when(network.getGateway()).thenReturn("10.1.1.1"); when(network.getGateway()).thenReturn("10.1.1.1");
when(network.getCidr()).thenReturn("10.1.1.0/24"); when(network.getCidr()).thenReturn("10.1.1.0/24");
when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
DeployDestination dest = mock(DeployDestination.class); final DeployDestination dest = mock(DeployDestination.class);
DataCenter dc = mock(DataCenter.class); final DataCenter dc = mock(DataCenter.class);
when(dest.getDataCenter()).thenReturn(dc); when(dest.getDataCenter()).thenReturn(dc);
HostVO niciraHost = mock(HostVO.class); final HostVO niciraHost = mock(HostVO.class);
when(hostdao.findById(anyLong())).thenReturn(niciraHost); when(hostdao.findById(anyLong())).thenReturn(niciraHost);
when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
when(niciraHost.getId()).thenReturn(NETWORK_ID); when(niciraHost.getId()).thenReturn(NETWORK_ID);
when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
Domain dom = mock(Domain.class); final Domain dom = mock(Domain.class);
when(dom.getName()).thenReturn("domain"); when(dom.getName()).thenReturn("domain");
Account acc = mock(Account.class); final Account acc = mock(Account.class);
when(acc.getAccountName()).thenReturn("accountname"); when(acc.getAccountName()).thenReturn("accountname");
ReservationContext res = mock(ReservationContext.class); final ReservationContext res = mock(ReservationContext.class);
when(res.getDomain()).thenReturn(dom); when(res.getDomain()).thenReturn(dom);
when(res.getAccount()).thenReturn(acc); when(res.getAccount()).thenReturn(acc);
CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class);
when(answer.getResult()).thenReturn(true); when(answer.getResult()).thenReturn(true);
when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa");
when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
Network implementednetwork = guru.implement(network, offering, dest, res); final Network implementednetwork = guru.implement(network, offering, dest, res);
assertTrue(implementednetwork != null); assertTrue(implementednetwork != null);
assertTrue(implementednetwork.getCidr().equals("10.1.1.0/24")); assertTrue(implementednetwork.getCidr().equals("10.1.1.0/24"));
assertTrue(implementednetwork.getGateway().equals("10.1.1.1")); assertTrue(implementednetwork.getGateway().equals("10.1.1.1"));
@ -355,16 +355,16 @@ public class NiciraNvpGuestNetworkGuruTest {
@Test @Test
public void testImplementURIException() throws InsufficientVirtualNetworkCapcityException { public void testImplementURIException() throws InsufficientVirtualNetworkCapcityException {
PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnetdao.findById((Long)any())).thenReturn(physnet); when(physnetdao.findById((Long)any())).thenReturn(physnet);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
when(physnet.getId()).thenReturn(NETWORK_ID); when(physnet.getId()).thenReturn(NETWORK_ID);
NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
when(device.getId()).thenReturn(1L); when(device.getId()).thenReturn(1L);
NetworkOffering offering = mock(NetworkOffering.class); final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated); when(offering.getGuestType()).thenReturn(GuestType.Isolated);
@ -373,53 +373,53 @@ public class NiciraNvpGuestNetworkGuruTest {
mock(DeploymentPlan.class); mock(DeploymentPlan.class);
NetworkVO network = mock(NetworkVO.class); final NetworkVO network = mock(NetworkVO.class);
when(network.getName()).thenReturn("testnetwork"); when(network.getName()).thenReturn("testnetwork");
when(network.getState()).thenReturn(State.Implementing); when(network.getState()).thenReturn(State.Implementing);
when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
DeployDestination dest = mock(DeployDestination.class); final DeployDestination dest = mock(DeployDestination.class);
DataCenter dc = mock(DataCenter.class); final DataCenter dc = mock(DataCenter.class);
when(dest.getDataCenter()).thenReturn(dc); when(dest.getDataCenter()).thenReturn(dc);
HostVO niciraHost = mock(HostVO.class); final HostVO niciraHost = mock(HostVO.class);
when(hostdao.findById(anyLong())).thenReturn(niciraHost); when(hostdao.findById(anyLong())).thenReturn(niciraHost);
when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
when(niciraHost.getId()).thenReturn(NETWORK_ID); when(niciraHost.getId()).thenReturn(NETWORK_ID);
when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
Domain dom = mock(Domain.class); final Domain dom = mock(Domain.class);
when(dom.getName()).thenReturn("domain"); when(dom.getName()).thenReturn("domain");
Account acc = mock(Account.class); final Account acc = mock(Account.class);
when(acc.getAccountName()).thenReturn("accountname"); when(acc.getAccountName()).thenReturn("accountname");
ReservationContext res = mock(ReservationContext.class); final ReservationContext res = mock(ReservationContext.class);
when(res.getDomain()).thenReturn(dom); when(res.getDomain()).thenReturn(dom);
when(res.getAccount()).thenReturn(acc); when(res.getAccount()).thenReturn(acc);
CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class);
when(answer.getResult()).thenReturn(true); when(answer.getResult()).thenReturn(true);
//when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); //when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa");
when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
Network implementednetwork = guru.implement(network, offering, dest, res); final Network implementednetwork = guru.implement(network, offering, dest, res);
assertTrue(implementednetwork == null); assertTrue(implementednetwork == null);
verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any());
} }
@Test @Test
public void testShutdown() throws InsufficientVirtualNetworkCapcityException, URISyntaxException { public void testShutdown() throws InsufficientVirtualNetworkCapcityException, URISyntaxException {
PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnetdao.findById((Long)any())).thenReturn(physnet); when(physnetdao.findById((Long)any())).thenReturn(physnet);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"}));
when(physnet.getId()).thenReturn(NETWORK_ID); when(physnet.getId()).thenReturn(NETWORK_ID);
NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device}));
when(device.getId()).thenReturn(1L); when(device.getId()).thenReturn(1L);
NetworkOffering offering = mock(NetworkOffering.class); final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID); when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated); when(offering.getGuestType()).thenReturn(GuestType.Isolated);
@ -428,7 +428,7 @@ public class NiciraNvpGuestNetworkGuruTest {
mock(DeploymentPlan.class); mock(DeploymentPlan.class);
NetworkVO network = mock(NetworkVO.class); final NetworkVO network = mock(NetworkVO.class);
when(network.getName()).thenReturn("testnetwork"); when(network.getName()).thenReturn("testnetwork");
when(network.getState()).thenReturn(State.Implementing); when(network.getState()).thenReturn(State.Implementing);
when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
@ -436,31 +436,31 @@ public class NiciraNvpGuestNetworkGuruTest {
when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
when(netdao.findById(NETWORK_ID)).thenReturn(network); when(netdao.findById(NETWORK_ID)).thenReturn(network);
DeployDestination dest = mock(DeployDestination.class); final DeployDestination dest = mock(DeployDestination.class);
DataCenter dc = mock(DataCenter.class); final DataCenter dc = mock(DataCenter.class);
when(dest.getDataCenter()).thenReturn(dc); when(dest.getDataCenter()).thenReturn(dc);
HostVO niciraHost = mock(HostVO.class); final HostVO niciraHost = mock(HostVO.class);
when(hostdao.findById(anyLong())).thenReturn(niciraHost); when(hostdao.findById(anyLong())).thenReturn(niciraHost);
when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
when(niciraHost.getId()).thenReturn(NETWORK_ID); when(niciraHost.getId()).thenReturn(NETWORK_ID);
when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID);
Domain dom = mock(Domain.class); final Domain dom = mock(Domain.class);
when(dom.getName()).thenReturn("domain"); when(dom.getName()).thenReturn("domain");
Account acc = mock(Account.class); final Account acc = mock(Account.class);
when(acc.getAccountName()).thenReturn("accountname"); when(acc.getAccountName()).thenReturn("accountname");
ReservationContext res = mock(ReservationContext.class); final ReservationContext res = mock(ReservationContext.class);
when(res.getDomain()).thenReturn(dom); when(res.getDomain()).thenReturn(dom);
when(res.getAccount()).thenReturn(acc); when(res.getAccount()).thenReturn(acc);
DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class); final DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class);
when(answer.getResult()).thenReturn(true); when(answer.getResult()).thenReturn(true);
when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer);
NetworkProfile implementednetwork = mock(NetworkProfile.class); final NetworkProfile implementednetwork = mock(NetworkProfile.class);
when(implementednetwork.getId()).thenReturn(NETWORK_ID); when(implementednetwork.getId()).thenReturn(NETWORK_ID);
when(implementednetwork.getBroadcastUri()).thenReturn(new URI("lswitch:aaaa")); when(implementednetwork.getBroadcastUri()).thenReturn(new URI("lswitch:aaaa"));
when(offering.getSpecifyVlan()).thenReturn(false); when(offering.getSpecifyVlan()).thenReturn(false);

View File

@ -31,22 +31,22 @@ public class NatRuleTest {
@Test @Test
public void testNatRuleEncoding() { public void testNatRuleEncoding() {
Gson gson = final Gson gson =
new GsonBuilder().registerTypeAdapter(NatRule.class, new com.cloud.network.nicira.NiciraNvpApi.NatRuleAdapter()) new GsonBuilder().registerTypeAdapter(NatRule.class, new NiciraNvpApi.NatRuleAdapter())
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create(); .create();
DestinationNatRule rn1 = new DestinationNatRule(); final DestinationNatRule rn1 = new DestinationNatRule();
rn1.setToDestinationIpAddress("10.10.10.10"); rn1.setToDestinationIpAddress("10.10.10.10");
rn1.setToDestinationPort(80); rn1.setToDestinationPort(80);
Match mr1 = new Match(); final Match mr1 = new Match();
mr1.setSourceIpAddresses("11.11.11.11/24"); mr1.setSourceIpAddresses("11.11.11.11/24");
mr1.setEthertype("IPv4"); mr1.setEthertype("IPv4");
mr1.setProtocol(6); mr1.setProtocol(6);
rn1.setMatch(mr1); rn1.setMatch(mr1);
String jsonString = gson.toJson(rn1); final String jsonString = gson.toJson(rn1);
NatRule dnr = gson.fromJson(jsonString, NatRule.class); final NatRule dnr = gson.fromJson(jsonString, NatRule.class);
assertTrue(dnr instanceof DestinationNatRule); assertTrue(dnr instanceof DestinationNatRule);
assertTrue(rn1.equals(dnr)); assertTrue(rn1.equals(dnr));

View File

@ -19,14 +19,15 @@
package com.cloud.network.nicira; package com.cloud.network.nicira;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
import java.util.UUID;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -84,22 +85,22 @@ public class NiciraNvpApiIT {
scInList = iProfile; scInList = iProfile;
} }
} }
Assert.assertEquals("Read a Security Profile different from the one just created and updated", assertEquals("Read a Security Profile different from the one just created and updated",
sProfile, scInList); sProfile, scInList);
// Read them filtered by uuid (get one) // Read them filtered by uuid (get one)
profiles = api.findSecurityProfile(sProfile.getUuid()); profiles = api.findSecurityProfile(sProfile.getUuid());
Assert.assertEquals("Read a Security Profile different from the one just created and updated", assertEquals("Read a Security Profile different from the one just created and updated",
sProfile, sProfile,
profiles.getResults().get(0)); profiles.getResults().get(0));
Assert.assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item", assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item",
1, profiles.getResults().size()); 1, profiles.getResults().size());
// We can now delete the new entity // We can now delete the new entity
api.deleteSecurityProfile(sProfile.getUuid()); api.deleteSecurityProfile(sProfile.getUuid());
} catch (final NiciraNvpApiException e) { } catch (final NiciraNvpApiException e) {
e.printStackTrace(); e.printStackTrace();
assertTrue("Errors creating Security Profile", false); assertTrue("Errors in Security Profile CRUD", false);
} }
} }
@ -145,22 +146,203 @@ public class NiciraNvpApiIT {
scInList = iAcl; scInList = iAcl;
} }
} }
Assert.assertEquals("Read a ACL different from the one just created and updated", assertEquals("Read a ACL different from the one just created and updated",
acl, scInList); acl, scInList);
// Read them filtered by uuid (get one) // Read them filtered by uuid (get one)
acls = api.findAcl(acl.getUuid()); acls = api.findAcl(acl.getUuid());
Assert.assertEquals("Read a ACL different from the one just created and updated", assertEquals("Read a ACL different from the one just created and updated",
acl, acl,
acls.getResults().get(0)); acls.getResults().get(0));
Assert.assertEquals("Read a ACL filtered by unique id (UUID) with more than one item", assertEquals("Read a ACL filtered by unique id (UUID) with more than one item",
1, acls.getResults().size()); 1, acls.getResults().size());
// We can now delete the new entity // We can now delete the new entity
api.deleteAcl(acl.getUuid()); api.deleteAcl(acl.getUuid());
} catch (final NiciraNvpApiException e) { } catch (final NiciraNvpApiException e) {
e.printStackTrace(); e.printStackTrace();
assertTrue("Errors creating ACL", false); assertTrue("Errors in ACL CRUD", false);
} }
} }
@Test
public void testCRUDLogicalSwitch() throws NiciraNvpApiException {
LogicalSwitch logicalSwitch = new LogicalSwitch();
logicalSwitch.setDisplayName("LogicalSwitch"+timestamp);
logicalSwitch.setPortIsolationEnabled(true);
logicalSwitch.setReplicationMode("service");
logicalSwitch.setTags(new ArrayList<NiciraNvpTag>());
logicalSwitch.getTags().add(new NiciraNvpTag("anto", "hugo"));
// In the creation we don't get to specify UUID, href or schema: they don't exist yet
try {
logicalSwitch = api.createLogicalSwitch(logicalSwitch);
// We can now update the new entity
logicalSwitch.setDisplayName("UpdatedLogicalSwitch"+timestamp);
api.updateLogicalSwitch(logicalSwitch, logicalSwitch.getUuid());
// Read them all
NiciraNvpList<LogicalSwitch> logicalSwitches = api.findLogicalSwitch();
for(final LogicalSwitch iLogicalSwitch : logicalSwitches.getResults()) {
if (iLogicalSwitch.getUuid().equalsIgnoreCase(logicalSwitch.getUuid())) {
assertEquals("Read a LogicalSwitch different from the one just created and updated",
logicalSwitch, iLogicalSwitch);
}
}
// Read them filtered by uuid (get one)
logicalSwitches = api.findLogicalSwitch(logicalSwitch.getUuid());
assertEquals("Read a LogicalSwitch different from the one just created and updated",
logicalSwitch,
logicalSwitches.getResults().get(0));
assertEquals("Read a LogicalSwitch filtered by unique id (UUID) with more than one item",
1, logicalSwitches.getResults().size());
// Before deleting the test LogicalSwitch, test its ports
final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
tags.add(new NiciraNvpTag("cs_account", "OwnerName"));
LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort("LSwitchPort"+timestamp, tags, true);
logicalSwitchPort = api.createLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);
logicalSwitchPort.setDisplayName("UpdatedLSwitchPort"+timestamp);
api.updateLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort);
final NiciraNvpList<LogicalSwitchPort> logicalSwitchePorts =
api.findLogicalSwitchPortsByUuid(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
for(final LogicalSwitchPort iLSwitchPort : logicalSwitchePorts.getResults()) {
if (iLSwitchPort.getUuid().equalsIgnoreCase(logicalSwitchPort.getUuid())) {
assertEquals("Read a LogicalSwitchPort different from the one just created and updated",
logicalSwitchPort, iLSwitchPort);
}
}
// And finally test attachments
final String attachmentUuid = UUID.randomUUID().toString();
final VifAttachment vifAttachment = new VifAttachment(attachmentUuid);
api.updateLogicalSwitchPortAttachment(logicalSwitch.getUuid(), logicalSwitchPort.getUuid(),
vifAttachment);
assertEquals("Read a LogicalSwitchPort by vifAttachment different than expected",
api.findLogicalSwitchPortUuidByVifAttachmentUuid(logicalSwitch.getUuid(), vifAttachment.getVifUuid()),
logicalSwitchPort.getUuid());
api.deleteLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
// We can now delete the new entity
api.deleteLogicalSwitch(logicalSwitch.getUuid());
} catch (final NiciraNvpApiException e) {
e.printStackTrace();
assertTrue("Errors in LogicalSwitch CRUD", false);
}
}
@Test
public void testCRUDLogicalRouter() throws NiciraNvpApiException {
LogicalRouter logicalRouter = new LogicalRouter();
logicalRouter.setDisplayName("LogicalRouter"+timestamp);
logicalRouter.setDistributed(true);
logicalRouter.setNatSynchronizationEnabled(true);
logicalRouter.setReplicationMode(LogicalRouter.REPLICATION_MODE_SERVICE);
final RoutingConfig routingConfig = new SingleDefaultRouteImplicitRoutingConfig(
new RouterNextHop("192.168.10.20"));
logicalRouter.setRoutingConfig(routingConfig);
// In the creation we don't get to specify UUID, href or schema: they don't exist yet
try {
logicalRouter = api.createLogicalRouter(logicalRouter);
// We can now update the new entity
logicalRouter.setDisplayName("UpdatedLogicalSwitch"+timestamp);
api.updateLogicalRouter(logicalRouter, logicalRouter.getUuid());
// Read them all
NiciraNvpList<LogicalRouter> logicalRouters = api.findLogicalRouter();
LogicalRouter lsInList = null;
for(final LogicalRouter iLogicalRouter : logicalRouters.getResults()) {
if (iLogicalRouter.getUuid().equalsIgnoreCase(logicalRouter.getUuid())) {
lsInList = iLogicalRouter;
}
}
assertEquals("Read a LogicalRouter different from the one just created and updated",
logicalRouter, lsInList);
// Read them filtered by uuid (get one)
logicalRouters = api.findLogicalRouter(logicalRouter.getUuid());
assertEquals("Read a LogicalRouter different from the one just created and updated",
logicalRouter,
logicalRouters.getResults().get(0));
assertEquals("Read a LogicalRouter filtered by unique id (UUID) with more than one item",
1, logicalRouters.getResults().size());
assertEquals("", logicalRouters.getResults().get(0),
api.findOneLogicalRouterByUuid(logicalRouter.getUuid()));
// Before deleting the test LogicalRouter, test its ports
final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
tags.add(new NiciraNvpTag("cs_account", "OwnerName"));
LogicalRouterPort logicalRouterPort = new LogicalRouterPort();
logicalRouterPort.setDisplayName("LRouterPort"+timestamp);
logicalRouterPort.setTags(tags);
logicalRouterPort.setAdminStatusEnabled(true);
logicalRouterPort.setPortno(1024);
logicalRouterPort.setMacAddress("00:00:00:00:00:00");
final List<String> ipAddresses = new ArrayList<String>();
// Add some ips to this list
logicalRouterPort.setIpAddresses(ipAddresses);
logicalRouterPort = api.createLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort);
logicalRouterPort.setDisplayName("UpdatedLRouterPort"+timestamp);
api.updateLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort);
final NiciraNvpList<LogicalRouterPort> logicalRouterePorts =
api.findLogicalRouterPortsByUuid(logicalRouter.getUuid(), logicalRouterPort.getUuid());
for(final LogicalRouterPort iLRouterPort : logicalRouterePorts.getResults()) {
if (iLRouterPort.getUuid().equalsIgnoreCase(logicalRouterPort.getUuid())) {
assertEquals("Read a LogicalRouterPort different from the one just created and updated",
logicalRouterPort, iLRouterPort);
}
}
UUID.randomUUID().toString();
// Test CRUD for Nat Rules
SourceNatRule snr = new SourceNatRule();
snr.setToSourceIpAddressMin("192.168.10.10");
snr.setToSourceIpAddressMax("192.168.10.20");
snr.setOrder(200);
final Match match = new Match();
match.setSourceIpAddresses("192.168.150.150");
snr.setMatch(match);
snr = (SourceNatRule) api.createLogicalRouterNatRule(logicalRouter.getUuid(), snr);
snr.setToSourceIpAddressMax("192.168.10.30");
api.updateLogicalRouterNatRule(logicalRouter.getUuid(), snr);
api.findNatRulesByLogicalRouterUuid(logicalRouter.getUuid());
api.deleteLogicalRouterNatRule(logicalRouter.getUuid(), snr.getUuid());
api.deleteLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort.getUuid());
// We can now delete the new entity
api.deleteLogicalRouter(logicalRouter.getUuid());
} catch (final NiciraNvpApiException e) {
e.printStackTrace();
assertTrue("Errors in LogicalRouter CRUD", false);
}
}
@Test
public void testGetControlClusterStatus() throws NiciraNvpApiException {
final ControlClusterStatus controlClusterStatus = api.getControlClusterStatus();
final String clusterStatus = controlClusterStatus.getClusterStatus();
final boolean correctStatus = (clusterStatus.equalsIgnoreCase("stable") ||
clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable"));
assertTrue("Not recognizable cluster status", correctStatus);
}
} }

View File

@ -19,457 +19,289 @@
package com.cloud.network.nicira; package com.cloud.network.nicira;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException; import java.io.IOException;
import java.util.Collections;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
public class NiciraNvpApiTest { public class NiciraNvpApiTest {
protected static final String UUID = "aaaa"; // protected static final String UUID = "aaaa";
protected static final String UUID2 = "bbbb"; // protected static final String UUID2 = "bbbb";
protected static final String UUID_SEC_PROFILE_URI = NiciraNvpApi.SEC_PROFILE_URI_PREFIX + "/aaaa"; // protected static final String UUID_SEC_PROFILE_URI = NiciraNvpApi.SEC_PROFILE_URI_PREFIX + "/aaaa";
protected static final String SCHEMA = "myTestSchema"; // protected static final String SCHEMA = "myTestSchema";
protected static final String SCHEMA2 = "myTestSchema2"; // protected static final String SCHEMA2 = "myTestSchema2";
protected static final String HREF = "myTestHref"; // protected static final String HREF = "myTestHref";
protected static final String HREF2 = "myTestHref2"; // protected static final String HREF2 = "myTestHref2";
protected static final String DISPLAY_NAME = "myTestName"; // protected static final String DISPLAY_NAME = "myTestName";
protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}"; // protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}";
protected static final String SEC_PROFILE_JSON_RESPONSE = // protected static final String SEC_PROFILE_JSON_RESPONSE =
"{\"uuid\" : \"aaaa\"," // "{\"uuid\" : \"aaaa\","
+ "\"display_name\" : \"myTestName\"," // + "\"display_name\" : \"myTestName\","
+ "\"href\" : \"myTestHref\"," // + "\"href\" : \"myTestHref\","
+ "\"schema\" : \"myTestSchema\"}"; // + "\"schema\" : \"myTestSchema\"}";
//
// protected static final String SEC_PROFILE_LIST_JSON_RESPONSE = "{\"results\" : [{\"uuid\" : \"aaaa\","
// + "\"display_name\" : \"myTestName\","
// + "\"href\" : \"myTestHref\","
// + "\"schema\" : \"myTestSchema\"},"
// + "{ \"uuid\" : \"bbbb\","
// + "\"display_name\" : \"myTestName2\","
// + "\"href\" : \"myTestHref2\","
// + "\"schema\" : \"myTestSchema2\"}],"
// + "\"result_count\": 2}";
//
// NiciraNvpApi api;
// HttpClient client = mock(HttpClient.class);
// HttpMethod method;
// String type;
// String uri;
//
// @Before
// public void setUp() {
// final HttpClientParams hmp = mock(HttpClientParams.class);
// when(client.getParams()).thenReturn(hmp);
// api = new NiciraNvpApi();
//
// api.restConnector = new RESTServiceConnector() {
// @Override
// public HttpClient createHttpClient() {
// return client;
// }
//
// @Override
// public HttpMethod createMethod(final String newType, final String newUri) {
// type = newType;
// uri = newUri;
// return method;
// }
// };
//
// api.setAdminCredentials("admin", "adminpass");
// api.setControllerAddress("localhost");
// }
//
// @Test
// public void testFindSecurityProfile() throws NiciraNvpApiException, IOException {
// // Prepare
// method = mock(GetMethod.class);
// when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
// when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE);
// final NameValuePair[] queryString = new NameValuePair[]{
// new NameValuePair("fields","*")};
//
// // Execute
// final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile();
//
// // Assert
// verify(method, times(1)).releaseConnection();
// verify(method, times(1)).setQueryString(queryString);
// assertEquals("Wrong Uuid in the newly created SecurityProfile",
// UUID, actualProfiles.getResults().get(0).getUuid());
// assertEquals("Wrong Uuid in the newly created SecurityProfile",
// HREF, actualProfiles.getResults().get(0).getHref());
// assertEquals("Wrong Schema in the newly created SecurityProfile",
// SCHEMA, actualProfiles.getResults().get(0).getSchema());
// assertEquals("Wrong Uuid in the newly created SecurityProfile",
// UUID2, actualProfiles.getResults().get(1).getUuid());
// assertEquals("Wrong Uuid in the newly created SecurityProfile",
// HREF2, actualProfiles.getResults().get(1).getHref());
// assertEquals("Wrong Schema in the newly created SecurityProfile",
// SCHEMA2, actualProfiles.getResults().get(1).getSchema());
// assertEquals("Wrong Schema in the newly created SecurityProfile",
// 2, actualProfiles.getResultCount());
// assertEquals("Wrong URI for SecurityProfile creation REST service",
// NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
// assertEquals("Wrong URI for SecurityProfile creation REST service",
// NiciraNvpApi.GET_METHOD_TYPE, type);
// }
//
// @Test
// public void testFindSecurityProfileByUuid() throws NiciraNvpApiException, IOException {
// // Prepare
// method = mock(GetMethod.class);
// when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
// when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE);
// final NameValuePair[] queryString = new NameValuePair[]{
// new NameValuePair("uuid", UUID),
// new NameValuePair("fields","*")
// };
//
// // Execute
// final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile(UUID);
//
// // Assert
// verify(method, times(1)).releaseConnection();
// verify(method, times(1)).setQueryString(queryString);
// assertEquals("Wrong Uuid in the newly created SecurityProfile",
// UUID, actualProfiles.getResults().get(0).getUuid());
// assertEquals("Wrong Uuid in the newly created SecurityProfile",
// HREF, actualProfiles.getResults().get(0).getHref());
// assertEquals("Wrong Schema in the newly created SecurityProfile",
// SCHEMA, actualProfiles.getResults().get(0).getSchema());
// assertEquals("Wrong Uuid in the newly created SecurityProfile",
// UUID2, actualProfiles.getResults().get(1).getUuid());
// assertEquals("Wrong Uuid in the newly created SecurityProfile",
// HREF2, actualProfiles.getResults().get(1).getHref());
// assertEquals("Wrong Schema in the newly created SecurityProfile",
// SCHEMA2, actualProfiles.getResults().get(1).getSchema());
// assertEquals("Wrong Schema in the newly created SecurityProfile",
// 2, actualProfiles.getResultCount());
// assertEquals("Wrong URI for SecurityProfile creation REST service",
// NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
// assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
// NiciraNvpApi.GET_METHOD_TYPE, type);
// }
//
// @Test
// public void testCreateSecurityProfile() throws NiciraNvpApiException, IOException {
// // Prepare
// final SecurityProfile inputSecProfile = new SecurityProfile();
// method = mock(PostMethod.class);
// when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
// when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_JSON_RESPONSE);
//
// // Execute
// final SecurityProfile actualSecProfile = api.createSecurityProfile(inputSecProfile);
//
// // Assert
// verify(method, times(1)).releaseConnection();
// assertEquals("Wrong Uuid in the newly created SecurityProfile",
// UUID, actualSecProfile.getUuid());
// assertEquals("Wrong Uuid in the newly created SecurityProfile",
// HREF, actualSecProfile.getHref());
// assertEquals("Wrong Schema in the newly created SecurityProfile",
// SCHEMA, actualSecProfile.getSchema());
// assertEquals("Wrong URI for SecurityProfile creation REST service",
// NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
// assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
// NiciraNvpApi.POST_METHOD_TYPE, type);
// }
//
// @Test
// public void testUpdateSecurityProfile() throws NiciraNvpApiException, IOException {
// // Prepare
// final SecurityProfile inputSecProfile = new SecurityProfile();
// method = mock(PutMethod.class);
// when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
//
// // Execute
// api.updateSecurityProfile(inputSecProfile, UUID);
//
// // Assert
// verify(method, times(1)).releaseConnection();
// assertEquals("Wrong URI for SecurityProfile creation REST service",
// UUID_SEC_PROFILE_URI, uri);
// assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
// NiciraNvpApi.PUT_METHOD_TYPE, type);
// }
//
// @Test
// public void testDeleteSecurityProfile() throws NiciraNvpApiException, IOException {
// // Prepare
// method = mock(DeleteMethod.class);
// when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
//
// // Execute
// api.deleteSecurityProfile(UUID);
//
// // Assert
// verify(method, times(1)).releaseConnection();
// assertEquals("Wrong URI for SecurityProfile deletion REST service", UUID_SEC_PROFILE_URI, uri);
// assertEquals("Wrong HTTP method for SecurityProfile deletion REST service", NiciraNvpApi.DELETE_METHOD_TYPE, type);
// }
protected static final String SEC_PROFILE_LIST_JSON_RESPONSE = "{\"results\" : [{\"uuid\" : \"aaaa\"," @Test(expected = JsonParseException.class)
+ "\"display_name\" : \"myTestName\"," public void testRoutingConfigAdapterNoType() throws NiciraNvpApiException, IOException {
+ "\"href\" : \"myTestHref\","
+ "\"schema\" : \"myTestSchema\"},"
+ "{ \"uuid\" : \"bbbb\","
+ "\"display_name\" : \"myTestName2\","
+ "\"href\" : \"myTestHref2\","
+ "\"schema\" : \"myTestSchema2\"}],"
+ "\"result_count\": 2}";
NiciraNvpApi api;
HttpClient client = mock(HttpClient.class);
HttpMethod method;
String type;
String uri;
@Before
public void setUp() {
final HttpClientParams hmp = mock(HttpClientParams.class);
when(client.getParams()).thenReturn(hmp);
api = new NiciraNvpApi() {
@Override
protected HttpClient createHttpClient() {
return client;
}
@Override
protected HttpMethod createMethod(final String newType, final String newUri) {
type = newType;
uri = newUri;
return method;
}
};
api.setAdminCredentials("admin", "adminpass");
api.setControllerAddress("localhost");
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteLoginWithoutHostname() throws NiciraNvpApiException {
api.setControllerAddress(null);
api.login();
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteLoginWithoutCredentials() throws NiciraNvpApiException {
api.setAdminCredentials(null, null);
api.login();
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteUpdateObjectWithoutHostname() throws NiciraNvpApiException {
api.setControllerAddress(null);
api.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap());
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteUpdateObjectWithoutCredentials() throws NiciraNvpApiException {
api.setAdminCredentials(null, null);
api.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap());
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteCreateObjectWithoutHostname() throws NiciraNvpApiException {
api.setControllerAddress(null);
api.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap());
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteCreateObjectWithoutCredentials() throws NiciraNvpApiException {
api.setAdminCredentials(null, null);
api.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap());
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteDeleteObjectWithoutHostname() throws NiciraNvpApiException {
api.setControllerAddress(null);
api.executeDeleteObject("/");
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteDeleteObjectWithoutCredentials() throws NiciraNvpApiException {
api.setAdminCredentials(null, null);
api.executeDeleteObject("/");
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteRetrieveObjectWithoutHostname() throws NiciraNvpApiException {
api.setControllerAddress(null);
api.executeRetrieveObject(String.class, "/", Collections.<String, String> emptyMap());
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteRetrieveObjectWithoutCredentials() throws NiciraNvpApiException {
api.setAdminCredentials(null, null);
api.executeDeleteObject("/");
}
@Test
public void executeMethodTest() throws NiciraNvpApiException {
final GetMethod gm = mock(GetMethod.class);
when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK);
api.executeMethod(gm);
verify(gm, times(1)).getStatusCode();
}
/* Bit of a roundabout way to ensure that login is called after an un authorized result
* It not possible to properly mock login()
*/
@Test(expected = NiciraNvpApiException.class)
public void executeMethodTestWithLogin() throws NiciraNvpApiException, HttpException, IOException {
final GetMethod gm = mock(GetMethod.class);
when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED);
api.executeMethod(gm);
verify(gm, times(1)).getStatusCode();
}
@Test
public void testExecuteCreateObject() throws NiciraNvpApiException, IOException {
LogicalSwitch ls = new LogicalSwitch();
method = mock(PostMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
ls = api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections.<String, String> emptyMap());
assertTrue(UUID.equals(ls.getUuid()));
verify(method, times(1)).releaseConnection();
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteCreateObjectFailure() throws NiciraNvpApiException, IOException {
LogicalSwitch ls = new LogicalSwitch();
method = mock(PostMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
final Header header = mock(Header.class);
when(header.getValue()).thenReturn("text/html");
when(method.getResponseHeader("Content-Type")).thenReturn(header);
when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
when(method.isRequestSent()).thenReturn(true);
try {
ls = api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteCreateObjectException() throws NiciraNvpApiException, IOException {
LogicalSwitch ls = new LogicalSwitch();
when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
method = mock(PostMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
final Header header = mock(Header.class);
when(header.getValue()).thenReturn("text/html");
when(method.getResponseHeader("Content-Type")).thenReturn(header);
when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
try {
ls = api.executeCreateObject(ls, LogicalSwitch.class, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test
public void testExecuteUpdateObject() throws NiciraNvpApiException, IOException {
final LogicalSwitch ls = new LogicalSwitch();
method = mock(PutMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
api.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
verify(method, times(1)).releaseConnection();
verify(client, times(1)).executeMethod(method);
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteUpdateObjectFailure() throws NiciraNvpApiException, IOException {
final LogicalSwitch ls = new LogicalSwitch();
method = mock(PutMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
final Header header = mock(Header.class);
when(header.getValue()).thenReturn("text/html");
when(method.getResponseHeader("Content-Type")).thenReturn(header);
when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
when(method.isRequestSent()).thenReturn(true);
try {
api.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteUpdateObjectException() throws NiciraNvpApiException, IOException {
final LogicalSwitch ls = new LogicalSwitch();
method = mock(PutMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
when(client.executeMethod((HttpMethod)any())).thenThrow(new IOException());
try {
api.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test
public void testExecuteDeleteObject() throws NiciraNvpApiException, IOException {
method = mock(DeleteMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
api.executeDeleteObject("/");
verify(method, times(1)).releaseConnection();
verify(client, times(1)).executeMethod(method);
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteDeleteObjectFailure() throws NiciraNvpApiException, IOException {
method = mock(DeleteMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
final Header header = mock(Header.class);
when(header.getValue()).thenReturn("text/html");
when(method.getResponseHeader("Content-Type")).thenReturn(header);
when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
when(method.isRequestSent()).thenReturn(true);
try {
api.executeDeleteObject("/");
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteDeleteObjectException() throws NiciraNvpApiException, IOException {
method = mock(DeleteMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
try {
api.executeDeleteObject("/");
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test
public void testExecuteRetrieveObject() throws NiciraNvpApiException, IOException {
method = mock(GetMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
api.executeRetrieveObject(LogicalSwitch.class, "/", Collections.<String, String> emptyMap());
verify(method, times(1)).releaseConnection();
verify(client, times(1)).executeMethod(method);
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteRetrieveObjectFailure() throws NiciraNvpApiException, IOException {
method = mock(GetMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
final Header header = mock(Header.class);
when(header.getValue()).thenReturn("text/html");
when(method.getResponseHeader("Content-Type")).thenReturn(header);
when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
when(method.isRequestSent()).thenReturn(true);
try {
api.executeRetrieveObject(LogicalSwitch.class, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test(expected = NiciraNvpApiException.class)
public void testExecuteRetrieveObjectException() throws NiciraNvpApiException, IOException {
method = mock(GetMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
try {
api.executeRetrieveObject(LogicalSwitch.class, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test
public void testFindSecurityProfile() throws NiciraNvpApiException, IOException {
// Prepare // Prepare
method = mock(GetMethod.class); final NiciraNvpApi api = new NiciraNvpApi();
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); final Gson gson = api.restConnector.getGson();
when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE);
final NameValuePair[] queryString = new NameValuePair[]{
new NameValuePair("fields","*")};
// Execute // Execute
final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile(); gson.fromJson("{}", RoutingConfig.class);
// Assert // Assert: JsonParseException should be thrown
verify(method, times(1)).releaseConnection();
verify(method, times(1)).setQueryString(queryString);
assertEquals("Wrong Uuid in the newly created SecurityProfile",
UUID, actualProfiles.getResults().get(0).getUuid());
assertEquals("Wrong Uuid in the newly created SecurityProfile",
HREF, actualProfiles.getResults().get(0).getHref());
assertEquals("Wrong Schema in the newly created SecurityProfile",
SCHEMA, actualProfiles.getResults().get(0).getSchema());
assertEquals("Wrong Uuid in the newly created SecurityProfile",
UUID2, actualProfiles.getResults().get(1).getUuid());
assertEquals("Wrong Uuid in the newly created SecurityProfile",
HREF2, actualProfiles.getResults().get(1).getHref());
assertEquals("Wrong Schema in the newly created SecurityProfile",
SCHEMA2, actualProfiles.getResults().get(1).getSchema());
assertEquals("Wrong Schema in the newly created SecurityProfile",
2, actualProfiles.getResultCount());
assertEquals("Wrong URI for SecurityProfile creation REST service",
NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
assertEquals("Wrong URI for SecurityProfile creation REST service",
NiciraNvpApi.GET_METHOD_TYPE, type);
} }
@Test @Test(expected = JsonParseException.class)
public void testFindSecurityProfileByUuid() throws NiciraNvpApiException, IOException { public void testRoutingConfigAdapterWrongType() throws NiciraNvpApiException, IOException {
// Prepare // Prepare
method = mock(GetMethod.class); final NiciraNvpApi api = new NiciraNvpApi();
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); final Gson gson = api.restConnector.getGson();
when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_LIST_JSON_RESPONSE);
final NameValuePair[] queryString = new NameValuePair[]{
new NameValuePair("uuid", UUID),
new NameValuePair("fields","*")
};
// Execute // Execute
final NiciraNvpList<SecurityProfile> actualProfiles = api.findSecurityProfile(UUID); gson.fromJson("{type : \"WrongType\"}", RoutingConfig.class);
// Assert // Assert: JsonParseException should be thrown
verify(method, times(1)).releaseConnection();
verify(method, times(1)).setQueryString(queryString);
assertEquals("Wrong Uuid in the newly created SecurityProfile",
UUID, actualProfiles.getResults().get(0).getUuid());
assertEquals("Wrong Uuid in the newly created SecurityProfile",
HREF, actualProfiles.getResults().get(0).getHref());
assertEquals("Wrong Schema in the newly created SecurityProfile",
SCHEMA, actualProfiles.getResults().get(0).getSchema());
assertEquals("Wrong Uuid in the newly created SecurityProfile",
UUID2, actualProfiles.getResults().get(1).getUuid());
assertEquals("Wrong Uuid in the newly created SecurityProfile",
HREF2, actualProfiles.getResults().get(1).getHref());
assertEquals("Wrong Schema in the newly created SecurityProfile",
SCHEMA2, actualProfiles.getResults().get(1).getSchema());
assertEquals("Wrong Schema in the newly created SecurityProfile",
2, actualProfiles.getResultCount());
assertEquals("Wrong URI for SecurityProfile creation REST service",
NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
NiciraNvpApi.GET_METHOD_TYPE, type);
} }
@Test @Test()
public void testCreateSecurityProfile() throws NiciraNvpApiException, IOException { public void testRoutingConfigAdapter() throws NiciraNvpApiException, IOException {
// Prepare // Prepare
final SecurityProfile inputSecProfile = new SecurityProfile(); final NiciraNvpApi api = new NiciraNvpApi();
method = mock(PostMethod.class); final Gson gson = api.restConnector.getGson();
when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_JSON_RESPONSE);
// Execute // Execute
final SecurityProfile actualSecProfile = api.createSecurityProfile(inputSecProfile); final SingleDefaultRouteImplicitRoutingConfig singleDefaultRouteImplicitRoutingConfig =
(SingleDefaultRouteImplicitRoutingConfig) gson.fromJson("{type : \"SingleDefaultRouteImplicitRoutingConfig\"}", RoutingConfig.class);
// Assert // Assert: JsonParseException should be thrown
verify(method, times(1)).releaseConnection(); assertEquals("", SingleDefaultRouteImplicitRoutingConfig.class, singleDefaultRouteImplicitRoutingConfig.getClass());
assertEquals("Wrong Uuid in the newly created SecurityProfile",
UUID, actualSecProfile.getUuid());
assertEquals("Wrong Uuid in the newly created SecurityProfile",
HREF, actualSecProfile.getHref());
assertEquals("Wrong Schema in the newly created SecurityProfile",
SCHEMA, actualSecProfile.getSchema());
assertEquals("Wrong URI for SecurityProfile creation REST service",
NiciraNvpApi.SEC_PROFILE_URI_PREFIX, uri);
assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
NiciraNvpApi.POST_METHOD_TYPE, type);
} }
@Test @Test(expected = JsonParseException.class)
public void testUpdateSecurityProfile() throws NiciraNvpApiException, IOException { public void testNatRuleAdapterNoType() throws NiciraNvpApiException, IOException {
// Prepare // Prepare
final SecurityProfile inputSecProfile = new SecurityProfile(); final NiciraNvpApi api = new NiciraNvpApi();
method = mock(PutMethod.class); final Gson gson = api.restConnector.getGson();
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
// Execute // Execute
api.updateSecurityProfile(inputSecProfile, UUID); gson.fromJson("{}", NatRule.class);
// Assert // Assert: JsonParseException should be thrown
verify(method, times(1)).releaseConnection();
assertEquals("Wrong URI for SecurityProfile creation REST service",
UUID_SEC_PROFILE_URI, uri);
assertEquals("Wrong HTTP method for SecurityProfile creation REST service",
NiciraNvpApi.PUT_METHOD_TYPE, type);
} }
@Test @Test(expected = JsonParseException.class)
public void testDeleteSecurityProfile() throws NiciraNvpApiException, IOException { public void testNatRuleAdapterWrongType() throws NiciraNvpApiException, IOException {
// Prepare // Prepare
method = mock(DeleteMethod.class); final NiciraNvpApi api = new NiciraNvpApi();
when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); final Gson gson = api.restConnector.getGson();
// Execute // Execute
api.deleteSecurityProfile(UUID); gson.fromJson("{type : \"WrongType\"}", NatRule.class);
// Assert // Assert: JsonParseException should be thrown
verify(method, times(1)).releaseConnection();
assertEquals("Wrong URI for SecurityProfile deletion REST service",
UUID_SEC_PROFILE_URI, uri);
assertEquals("Wrong HTTP method for SecurityProfile deletion REST service",
NiciraNvpApi.DELETE_METHOD_TYPE, type);
} }
@Test()
public void testRoutingConfigAdapterWithSourceNatRule() throws NiciraNvpApiException, IOException {
// Prepare
final NiciraNvpApi api = new NiciraNvpApi();
final Gson gson = api.restConnector.getGson();
// Execute
final SourceNatRule sourceNatRule =
(SourceNatRule) gson.fromJson("{type : \"SourceNatRule\"}", NatRule.class);
// Assert: JsonParseException should be thrown
assertEquals("", SourceNatRule.class, sourceNatRule.getClass());
}
@Test()
public void testRoutingConfigAdapterWithDestinationNatRule() throws NiciraNvpApiException, IOException {
// Prepare
final NiciraNvpApi api = new NiciraNvpApi();
final Gson gson = api.restConnector.getGson();
// Execute
final DestinationNatRule destinationNatRule =
(DestinationNatRule) gson.fromJson("{type : \"DestinationNatRule\"}", NatRule.class);
// Assert: JsonParseException should be thrown
assertEquals("", DestinationNatRule.class, destinationNatRule.getClass());
}
} }

View File

@ -26,21 +26,21 @@ import org.junit.Test;
public class NiciraTagTest { public class NiciraTagTest {
@Test @Test
public void testCreateTag() { public void testCreateTag() {
NiciraNvpTag tag = new NiciraNvpTag("scope", "tag"); final NiciraNvpTag tag = new NiciraNvpTag("scope", "tag");
assertEquals("scope part set", "scope", tag.getScope()); assertEquals("scope part set", "scope", tag.getScope());
assertEquals("tag part set", "tag", tag.getTag()); assertEquals("tag part set", "tag", tag.getTag());
} }
@Test @Test
public void testCreateLongTag() { public void testCreateLongTag() {
NiciraNvpTag tag = new NiciraNvpTag("scope", "verylongtagthatshouldattheminimumexceedthefortycharacterlenght"); final NiciraNvpTag tag = new NiciraNvpTag("scope", "verylongtagthatshouldattheminimumexceedthefortycharacterlenght");
assertEquals("scope part set", "scope", tag.getScope()); assertEquals("scope part set", "scope", tag.getScope());
assertEquals("tag part set", "verylongtagthatshouldattheminimumexceedt", tag.getTag()); assertEquals("tag part set", "verylongtagthatshouldattheminimumexceedt", tag.getTag());
} }
@Test @Test
public void testSetTag() { public void testSetTag() {
NiciraNvpTag tag = new NiciraNvpTag(); final NiciraNvpTag tag = new NiciraNvpTag();
tag.setScope("scope"); tag.setScope("scope");
tag.setTag("tag"); tag.setTag("tag");
assertEquals("scope part set", "scope", tag.getScope()); assertEquals("scope part set", "scope", tag.getScope());
@ -49,7 +49,7 @@ public class NiciraTagTest {
@Test @Test
public void testSetLongTag() { public void testSetLongTag() {
NiciraNvpTag tag = new NiciraNvpTag(); final NiciraNvpTag tag = new NiciraNvpTag();
tag.setScope("scope"); tag.setScope("scope");
tag.setTag("verylongtagthatshouldattheminimumexceedthefortycharacterlenght"); tag.setTag("verylongtagthatshouldattheminimumexceedthefortycharacterlenght");
assertEquals("scope part set", "scope", tag.getScope()); assertEquals("scope part set", "scope", tag.getScope());

View File

@ -76,7 +76,7 @@ import com.cloud.host.Host;
import com.cloud.network.nicira.Attachment; import com.cloud.network.nicira.Attachment;
import com.cloud.network.nicira.ControlClusterStatus; import com.cloud.network.nicira.ControlClusterStatus;
import com.cloud.network.nicira.DestinationNatRule; import com.cloud.network.nicira.DestinationNatRule;
import com.cloud.network.nicira.LogicalRouterConfig; import com.cloud.network.nicira.LogicalRouter;
import com.cloud.network.nicira.LogicalRouterPort; import com.cloud.network.nicira.LogicalRouterPort;
import com.cloud.network.nicira.LogicalSwitch; import com.cloud.network.nicira.LogicalSwitch;
import com.cloud.network.nicira.LogicalSwitchPort; import com.cloud.network.nicira.LogicalSwitchPort;
@ -132,7 +132,7 @@ public class NiciraNvpResourceTest {
public void testInitialization() throws ConfigurationException { public void testInitialization() throws ConfigurationException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
StartupCommand[] sc = resource.initialize(); final StartupCommand[] sc = resource.initialize();
assertTrue(sc.length == 1); assertTrue(sc.length == 1);
assertTrue("Incorrect startup command GUID", "aaaaa-bbbbb-ccccc".equals(sc[0].getGuid())); assertTrue("Incorrect startup command GUID", "aaaaa-bbbbb-ccccc".equals(sc[0].getGuid()));
assertTrue("Incorrect NVP device name", "nvptestdevice".equals(sc[0].getName())); assertTrue("Incorrect NVP device name", "nvptestdevice".equals(sc[0].getName()));
@ -143,11 +143,11 @@ public class NiciraNvpResourceTest {
public void testPingCommandStatusOk() throws ConfigurationException, NiciraNvpApiException { public void testPingCommandStatusOk() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
ControlClusterStatus ccs = mock(ControlClusterStatus.class); final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
when(ccs.getClusterStatus()).thenReturn("stable"); when(ccs.getClusterStatus()).thenReturn("stable");
when(nvpApi.getControlClusterStatus()).thenReturn(ccs); when(nvpApi.getControlClusterStatus()).thenReturn(ccs);
PingCommand ping = resource.getCurrentStatus(42); final PingCommand ping = resource.getCurrentStatus(42);
assertTrue(ping != null); assertTrue(ping != null);
assertTrue(ping.getHostId() == 42); assertTrue(ping.getHostId() == 42);
assertTrue(ping.getHostType() == Host.Type.L2Networking); assertTrue(ping.getHostType() == Host.Type.L2Networking);
@ -157,11 +157,11 @@ public class NiciraNvpResourceTest {
public void testPingCommandStatusFail() throws ConfigurationException, NiciraNvpApiException { public void testPingCommandStatusFail() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
ControlClusterStatus ccs = mock(ControlClusterStatus.class); final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
when(ccs.getClusterStatus()).thenReturn("unstable"); when(ccs.getClusterStatus()).thenReturn("unstable");
when(nvpApi.getControlClusterStatus()).thenReturn(ccs); when(nvpApi.getControlClusterStatus()).thenReturn(ccs);
PingCommand ping = resource.getCurrentStatus(42); final PingCommand ping = resource.getCurrentStatus(42);
assertTrue(ping == null); assertTrue(ping == null);
} }
@ -169,11 +169,11 @@ public class NiciraNvpResourceTest {
public void testPingCommandStatusApiException() throws ConfigurationException, NiciraNvpApiException { public void testPingCommandStatusApiException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
ControlClusterStatus ccs = mock(ControlClusterStatus.class); final ControlClusterStatus ccs = mock(ControlClusterStatus.class);
when(ccs.getClusterStatus()).thenReturn("unstable"); when(ccs.getClusterStatus()).thenReturn("unstable");
when(nvpApi.getControlClusterStatus()).thenThrow(new NiciraNvpApiException()); when(nvpApi.getControlClusterStatus()).thenThrow(new NiciraNvpApiException());
PingCommand ping = resource.getCurrentStatus(42); final PingCommand ping = resource.getCurrentStatus(42);
assertTrue(ping == null); assertTrue(ping == null);
} }
@ -181,12 +181,12 @@ public class NiciraNvpResourceTest {
public void testRetries() throws ConfigurationException, NiciraNvpApiException { public void testRetries() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
LogicalSwitch ls = mock(LogicalSwitch.class); final LogicalSwitch ls = mock(LogicalSwitch.class);
when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls); when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls);
CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner"); final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc); final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
assertTrue(clsa.getResult()); assertTrue(clsa.getResult());
} }
@ -194,12 +194,12 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { public void testCreateLogicalSwitch() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
LogicalSwitch ls = mock(LogicalSwitch.class); final LogicalSwitch ls = mock(LogicalSwitch.class);
when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenReturn(ls); when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenReturn(ls);
CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner"); final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc); final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
assertTrue(clsa.getResult()); assertTrue(clsa.getResult());
assertTrue("cccc".equals(clsa.getLogicalSwitchUuid())); assertTrue("cccc".equals(clsa.getLogicalSwitchUuid()));
} }
@ -208,12 +208,12 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException { public void testCreateLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
LogicalSwitch ls = mock(LogicalSwitch.class); final LogicalSwitch ls = mock(LogicalSwitch.class);
when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc");
when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException()); when(nvpApi.createLogicalSwitch((LogicalSwitch)any())).thenThrow(new NiciraNvpApiException());
CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner"); final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String)parameters.get("guid"), "stt", "loigicalswitch", "owner");
CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc); final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer)resource.executeRequest(clsc);
assertFalse(clsa.getResult()); assertFalse(clsa.getResult());
} }
@ -221,8 +221,8 @@ public class NiciraNvpResourceTest {
public void testDeleteLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { public void testDeleteLogicalSwitch() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc); final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
assertTrue(dlsa.getResult()); assertTrue(dlsa.getResult());
} }
@ -232,8 +232,8 @@ public class NiciraNvpResourceTest {
doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitch((String)any()); doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitch((String)any());
DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc");
DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc); final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer)resource.executeRequest(dlsc);
assertFalse(dlsa.getResult()); assertFalse(dlsa.getResult());
} }
@ -241,12 +241,12 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException { public void testCreateLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lsp.getUuid()).thenReturn("eeee"); when(lsp.getUuid()).thenReturn("eeee");
when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp); when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp);
CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc); final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
assertTrue(clspa.getResult()); assertTrue(clspa.getResult());
assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid())); assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid()));
@ -256,12 +256,12 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalSwitchPortApiExceptionInCreate() throws ConfigurationException, NiciraNvpApiException { public void testCreateLogicalSwitchPortApiExceptionInCreate() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lsp.getUuid()).thenReturn("eeee"); when(lsp.getUuid()).thenReturn("eeee");
when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenThrow(new NiciraNvpApiException()); when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenThrow(new NiciraNvpApiException());
CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc); final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
assertFalse(clspa.getResult()); assertFalse(clspa.getResult());
} }
@ -269,13 +269,13 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalSwitchPortApiExceptionInModify() throws ConfigurationException, NiciraNvpApiException { public void testCreateLogicalSwitchPortApiExceptionInModify() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lsp.getUuid()).thenReturn("eeee"); when(lsp.getUuid()).thenReturn("eeee");
when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp); when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort)any())).thenReturn(lsp);
doThrow(new NiciraNvpApiException()).when(nvpApi).modifyLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any()); doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname");
CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc); final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer)resource.executeRequest(clspc);
assertFalse(clspa.getResult()); assertFalse(clspa.getResult());
verify(nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String)any(), (String)any()); verify(nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String)any(), (String)any());
} }
@ -285,7 +285,7 @@ public class NiciraNvpResourceTest {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitchPort((String)any(), (String)any()); doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitchPort((String)any(), (String)any());
DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer)resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb")); final DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer)resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb"));
assertFalse(dlspa.getResult()); assertFalse(dlspa.getResult());
} }
@ -293,8 +293,8 @@ public class NiciraNvpResourceTest {
public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
doThrow(new NiciraNvpApiException()).when(nvpApi).modifyLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any()); doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
UpdateLogicalSwitchPortAnswer dlspa = final UpdateLogicalSwitchPortAnswer dlspa =
(UpdateLogicalSwitchPortAnswer)resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname")); (UpdateLogicalSwitchPortAnswer)resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname"));
assertFalse(dlspa.getResult()); assertFalse(dlspa.getResult());
} }
@ -304,11 +304,12 @@ public class NiciraNvpResourceTest {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class); NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class);
when(lspl.getResultCount()).thenReturn(1); when(lspl.getResultCount()).thenReturn(1);
when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
assertTrue(flspa.getResult()); assertTrue(flspa.getResult());
} }
@ -317,11 +318,12 @@ public class NiciraNvpResourceTest {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class); NiciraNvpList<LogicalSwitchPort> lspl = mock(NiciraNvpList.class);
when(lspl.getResultCount()).thenReturn(0); when(lspl.getResultCount()).thenReturn(0);
when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl);
FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
assertFalse(flspa.getResult()); assertFalse(flspa.getResult());
} }
@ -331,7 +333,7 @@ public class NiciraNvpResourceTest {
when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException()); when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException());
FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer)resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb"));
assertFalse(flspa.getResult()); assertFalse(flspa.getResult());
} }
@ -339,17 +341,17 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalRouter() throws ConfigurationException, NiciraNvpApiException { public void testCreateLogicalRouter() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); final LogicalRouter lrc = mock(LogicalRouter.class);
LogicalRouterPort lrp = mock(LogicalRouterPort.class); final LogicalRouterPort lrp = mock(LogicalRouterPort.class);
LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lrc.getUuid()).thenReturn("ccccc"); when(lrc.getUuid()).thenReturn("ccccc");
when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee");
when(lsp.getUuid()).thenReturn("fffff"); when(lsp.getUuid()).thenReturn("fffff");
when(nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp); when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp);
when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp); when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp);
CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
assertTrue(clra.getResult()); assertTrue(clra.getResult());
assertTrue("ccccc".equals(clra.getLogicalRouterUuid())); assertTrue("ccccc".equals(clra.getLogicalRouterUuid()));
@ -360,9 +362,9 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
when(nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenThrow(new NiciraNvpApiException()); when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenThrow(new NiciraNvpApiException());
CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
assertFalse(clra.getResult()); assertFalse(clra.getResult());
} }
@ -371,12 +373,12 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalRouterApiExceptionRollbackRouter() throws ConfigurationException, NiciraNvpApiException { public void testCreateLogicalRouterApiExceptionRollbackRouter() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); final LogicalRouter lrc = mock(LogicalRouter.class);
when(lrc.getUuid()).thenReturn("ccccc"); when(lrc.getUuid()).thenReturn("ccccc");
when(nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenThrow(new NiciraNvpApiException()); when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenThrow(new NiciraNvpApiException());
CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
assertFalse(clra.getResult()); assertFalse(clra.getResult());
verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc"));
@ -386,18 +388,18 @@ public class NiciraNvpResourceTest {
public void testCreateLogicalRouterApiExceptionRollbackRouterAndSwitchPort() throws ConfigurationException, NiciraNvpApiException { public void testCreateLogicalRouterApiExceptionRollbackRouterAndSwitchPort() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
LogicalRouterConfig lrc = mock(LogicalRouterConfig.class); final LogicalRouter lrc = mock(LogicalRouter.class);
LogicalRouterPort lrp = mock(LogicalRouterPort.class); final LogicalRouterPort lrp = mock(LogicalRouterPort.class);
LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class);
when(lrc.getUuid()).thenReturn("ccccc"); when(lrc.getUuid()).thenReturn("ccccc");
when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee");
when(lsp.getUuid()).thenReturn("fffff"); when(lsp.getUuid()).thenReturn("fffff");
when(nvpApi.createLogicalRouter((LogicalRouterConfig)any())).thenReturn(lrc); when(nvpApi.createLogicalRouter((LogicalRouter)any())).thenReturn(lrc);
when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp); when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort)any())).thenReturn(lrp);
when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp); when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort)any())).thenReturn(lsp);
when(nvpApi.createLogicalRouterNatRule((String)any(), (NatRule)any())).thenThrow(new NiciraNvpApiException()); when(nvpApi.createLogicalRouterNatRule((String)any(), (NatRule)any())).thenThrow(new NiciraNvpApiException());
CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner");
CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc); final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer)resource.executeRequest(clrc);
assertFalse(clra.getResult()); assertFalse(clra.getResult());
verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc"));
@ -409,7 +411,7 @@ public class NiciraNvpResourceTest {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalRouter(eq("aaaaa")); doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalRouter(eq("aaaaa"));
DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer)resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa")); final DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer)resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa"));
assertFalse(dlspa.getResult()); assertFalse(dlspa.getResult());
} }
@ -417,16 +419,17 @@ public class NiciraNvpResourceTest {
public void testConfigurePublicIpsOnLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { public void testConfigurePublicIpsOnLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException {
resource.configure("NiciraNvpResource", parameters); resource.configure("NiciraNvpResource", parameters);
ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class); final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<LogicalRouterPort> list = mock(NiciraNvpList.class); NiciraNvpList<LogicalRouterPort> list = mock(NiciraNvpList.class);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb"); when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb");
doThrow(new NiciraNvpApiException()).when(nvpApi).modifyLogicalRouterPort((String)any(), (LogicalRouterPort)any()); doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String)any(), (LogicalRouterPort)any());
when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenReturn(list); when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenReturn(list);
ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd); final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertFalse(answer.getResult()); assertFalse(answer.getResult());
} }
@ -440,31 +443,32 @@ public class NiciraNvpResourceTest {
*/ */
// Mock the command // Mock the command
ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>(); final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
rules.add(rule); rules.add(rule);
when(cmd.getRules()).thenReturn(rules); when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api find call // Mock the api find call
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class); NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
// Mock the api create calls // Mock the api create calls
NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
rulepair[0].setUuid(UUID.randomUUID()); rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() { verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override @Override
public boolean matches(Object argument) { public boolean matches(final Object argument) {
NatRule rule = (NatRule)argument; final NatRule rule = (NatRule)argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true; return true;
} }
@ -485,33 +489,34 @@ public class NiciraNvpResourceTest {
*/ */
// Mock the command // Mock the command
ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>(); final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
rules.add(rule); rules.add(rule);
when(cmd.getRules()).thenReturn(rules); when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls // Mock the api create calls
NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
rulepair[0].setUuid(UUID.randomUUID()); rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call // Mock the api find call
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class); NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(2); when(storedRules.getResultCount()).thenReturn(2);
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() { verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override @Override
public boolean matches(Object argument) { public boolean matches(final Object argument) {
NatRule rule = (NatRule)argument; final NatRule rule = (NatRule)argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true; return true;
} }
@ -532,15 +537,15 @@ public class NiciraNvpResourceTest {
*/ */
// Mock the command // Mock the command
ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, true, false); final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, true, false);
List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>(); final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
rules.add(rule); rules.add(rule);
when(cmd.getRules()).thenReturn(rules); when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls // Mock the api create calls
NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
final UUID rule0Uuid = UUID.randomUUID(); final UUID rule0Uuid = UUID.randomUUID();
final UUID rule1Uuid = UUID.randomUUID(); final UUID rule1Uuid = UUID.randomUUID();
rulepair[0].setUuid(rule0Uuid); rulepair[0].setUuid(rule0Uuid);
@ -549,18 +554,19 @@ public class NiciraNvpResourceTest {
// Mock the api find call // Mock the api find call
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class); NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(2); when(storedRules.getResultCount()).thenReturn(2);
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() { verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
@Override @Override
public boolean matches(Object argument) { public boolean matches(final Object argument) {
UUID uuid = (UUID)argument; final UUID uuid = (UUID)argument;
if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
return true; return true;
} }
@ -578,26 +584,27 @@ public class NiciraNvpResourceTest {
*/ */
// Mock the command // Mock the command
ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class);
StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false);
List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>(); final List<StaticNatRuleTO> rules = new ArrayList<StaticNatRuleTO>();
rules.add(rule); rules.add(rule);
when(cmd.getRules()).thenReturn(rules); when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls // Mock the api create calls
NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
rulepair[0].setUuid(UUID.randomUUID()); rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
// Mock the api find call // Mock the api find call
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class); NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(0); when(storedRules.getResultCount()).thenReturn(0);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertFalse(a.getResult()); assertFalse(a.getResult());
verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid())); verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid()));
@ -612,31 +619,32 @@ public class NiciraNvpResourceTest {
*/ */
// Mock the command // Mock the command
ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false);
List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>(); final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
rules.add(rule); rules.add(rule);
when(cmd.getRules()).thenReturn(rules); when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api find call // Mock the api find call
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class); NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
// Mock the api create calls // Mock the api create calls
NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp"); final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
rulepair[0].setUuid(UUID.randomUUID()); rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() { verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override @Override
public boolean matches(Object argument) { public boolean matches(final Object argument) {
NatRule rule = (NatRule)argument; final NatRule rule = (NatRule)argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true; return true;
} }
@ -657,33 +665,34 @@ public class NiciraNvpResourceTest {
*/ */
// Mock the command // Mock the command
ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, true); final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, true);
List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>(); final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
rules.add(rule); rules.add(rule);
when(cmd.getRules()).thenReturn(rules); when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls // Mock the api create calls
NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp"); final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
rulepair[0].setUuid(UUID.randomUUID()); rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
// Mock the api find call // Mock the api find call
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class); NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(2); when(storedRules.getResultCount()).thenReturn(2);
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() { verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override @Override
public boolean matches(Object argument) { public boolean matches(final Object argument) {
NatRule rule = (NatRule)argument; final NatRule rule = (NatRule)argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) { if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule)rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true; return true;
} }
@ -704,15 +713,15 @@ public class NiciraNvpResourceTest {
*/ */
// Mock the command // Mock the command
ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", true, true); final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", true, true);
List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>(); final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
rules.add(rule); rules.add(rule);
when(cmd.getRules()).thenReturn(rules); when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls // Mock the api create calls
NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp"); final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
final UUID rule0Uuid = UUID.randomUUID(); final UUID rule0Uuid = UUID.randomUUID();
final UUID rule1Uuid = UUID.randomUUID(); final UUID rule1Uuid = UUID.randomUUID();
rulepair[0].setUuid(rule0Uuid); rulepair[0].setUuid(rule0Uuid);
@ -721,18 +730,19 @@ public class NiciraNvpResourceTest {
// Mock the api find call // Mock the api find call
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class); NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(2); when(storedRules.getResultCount()).thenReturn(2);
when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair)); when(storedRules.getResults()).thenReturn(Arrays.asList(rulepair));
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() { verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
@Override @Override
public boolean matches(Object argument) { public boolean matches(final Object argument) {
UUID uuid = (UUID)argument; final UUID uuid = (UUID)argument;
if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
return true; return true;
} }
@ -750,26 +760,27 @@ public class NiciraNvpResourceTest {
*/ */
// Mock the command // Mock the command
ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false);
List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>(); final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
rules.add(rule); rules.add(rule);
when(cmd.getRules()).thenReturn(rules); when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api create calls // Mock the api create calls
NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp"); final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
rulepair[0].setUuid(UUID.randomUUID()); rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException());
// Mock the api find call // Mock the api find call
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class); NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(storedRules.getResultCount()).thenReturn(0); when(storedRules.getResultCount()).thenReturn(0);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
assertFalse(a.getResult()); assertFalse(a.getResult());
verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid())); verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid()));
@ -784,25 +795,26 @@ public class NiciraNvpResourceTest {
*/ */
// Mock the command // Mock the command
ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class);
PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 85, "10.10.10.10", 80, 85, "tcp", false, false); final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 85, "10.10.10.10", 80, 85, "tcp", false, false);
List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>(); final List<PortForwardingRuleTO> rules = new ArrayList<PortForwardingRuleTO>();
rules.add(rule); rules.add(rule);
when(cmd.getRules()).thenReturn(rules); when(cmd.getRules()).thenReturn(rules);
when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
// Mock the api find call // Mock the api find call
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final
NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class); NiciraNvpList<NatRule> storedRules = mock(NiciraNvpList.class);
when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules);
// Mock the api create calls // Mock the api create calls
NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {80, 85}, "11.11.11.11", new int[] {80, 85}, "tcp"); final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {80, 85}, "11.11.11.11", new int[] {80, 85}, "tcp");
rulepair[0].setUuid(UUID.randomUUID()); rulepair[0].setUuid(UUID.randomUUID());
rulepair[1].setUuid(UUID.randomUUID()); rulepair[1].setUuid(UUID.randomUUID());
when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule)any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]);
ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd); final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)resource.executeRequest(cmd);
// The expected result is false, Nicira does not support port ranges in DNAT // The expected result is false, Nicira does not support port ranges in DNAT
assertFalse(a.getResult()); assertFalse(a.getResult());
@ -811,16 +823,16 @@ public class NiciraNvpResourceTest {
@Test @Test
public void testGenerateStaticNatRulePair() { public void testGenerateStaticNatRulePair() {
NatRule[] rules = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); final NatRule[] rules = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11");
assertTrue("DestinationNatRule".equals(rules[0].getType())); assertTrue("DestinationNatRule".equals(rules[0].getType()));
assertTrue("SourceNatRule".equals(rules[1].getType())); assertTrue("SourceNatRule".equals(rules[1].getType()));
DestinationNatRule dnr = (DestinationNatRule)rules[0]; final DestinationNatRule dnr = (DestinationNatRule)rules[0];
assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10")); assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10"));
assertTrue(dnr.getToDestinationPort() == null); assertTrue(dnr.getToDestinationPort() == null);
assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11")); assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11"));
SourceNatRule snr = (SourceNatRule)rules[1]; final SourceNatRule snr = (SourceNatRule)rules[1];
assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11")); assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11"));
assertTrue(snr.getToSourcePort() == null); assertTrue(snr.getToSourcePort() == null);
assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10")); assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10"));
@ -828,18 +840,18 @@ public class NiciraNvpResourceTest {
@Test @Test
public void testGeneratePortForwardingRulePair() { public void testGeneratePortForwardingRulePair() {
NatRule[] rules = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp"); final NatRule[] rules = resource.generatePortForwardingRulePair("10.10.10.10", new int[] {8080, 8080}, "11.11.11.11", new int[] {80, 80}, "tcp");
assertTrue("DestinationNatRule".equals(rules[0].getType())); assertTrue("DestinationNatRule".equals(rules[0].getType()));
assertTrue("SourceNatRule".equals(rules[1].getType())); assertTrue("SourceNatRule".equals(rules[1].getType()));
DestinationNatRule dnr = (DestinationNatRule)rules[0]; final DestinationNatRule dnr = (DestinationNatRule)rules[0];
assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10")); assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10"));
assertTrue(dnr.getToDestinationPort() == 8080); assertTrue(dnr.getToDestinationPort() == 8080);
assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11")); assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11"));
assertTrue(dnr.getMatch().getDestinationPort() == 80); assertTrue(dnr.getMatch().getDestinationPort() == 80);
assertTrue(dnr.getMatch().getEthertype().equals("IPv4") && dnr.getMatch().getProtocol() == 6); assertTrue(dnr.getMatch().getEthertype().equals("IPv4") && dnr.getMatch().getProtocol() == 6);
SourceNatRule snr = (SourceNatRule)rules[1]; final SourceNatRule snr = (SourceNatRule)rules[1];
assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11")); assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11"));
assertTrue(snr.getToSourcePort() == 80); assertTrue(snr.getToSourcePort() == 80);
assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10")); assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10"));

View File

@ -36,6 +36,7 @@
<properties> <properties>
<cs.jdk.version>1.7</cs.jdk.version> <cs.jdk.version>1.7</cs.jdk.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<cs.log4j.version>1.2.16</cs.log4j.version> <cs.log4j.version>1.2.16</cs.log4j.version>
<cs.log4j.extras.version>1.1</cs.log4j.extras.version> <cs.log4j.extras.version>1.1</cs.log4j.extras.version>
@ -499,6 +500,11 @@
</plugins> </plugins>
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.3</version>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId> <artifactId>maven-checkstyle-plugin</artifactId>

View File

@ -141,6 +141,10 @@
<artifactId>commons-net</artifactId> <artifactId>commons-net</artifactId>
<version>3.3</version> <version>3.3</version>
</dependency> </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
@ -173,4 +177,27 @@
</resource> </resource>
</resources> </resources>
</build> </build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project> </project>

View File

@ -0,0 +1,47 @@
package com.cloud.utils.rest;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodBase;
/**
* Base 64 encoded authorization strategy. This implementation as opposed to
* {@link RESTValidationStrategy} doesn't do a login after auth error, but instead
* includes the encoded credentials in each request, instead of a cookie.
*/
public class BasicEncodedRESTValidationStrategy extends RESTValidationStrategy {
public BasicEncodedRESTValidationStrategy(final String host, final String adminuser, final String adminpass) {
super();
this.host = host;
user = adminuser;
password = adminpass;
}
public BasicEncodedRESTValidationStrategy() {
}
@Override
public void executeMethod(final HttpMethodBase method, final HttpClient client,
final String protocol)
throws CloudstackRESTException, HttpException, IOException {
if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
throw new CloudstackRESTException("Hostname/credentials are null or empty");
}
final String encodedCredentials = encodeCredentials();
method.setRequestHeader("Authorization", "Basic " + encodedCredentials);
client.executeMethod(method);
}
private String encodeCredentials() {
final String authString = user + ":" + password;
final byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
final String authStringEnc = new String(authEncBytes);
return authStringEnc;
}
}

View File

@ -0,0 +1,36 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.rest;
public class CloudstackRESTException extends Exception {
public CloudstackRESTException() {
}
public CloudstackRESTException(final String message) {
super(message);
}
public CloudstackRESTException(final Throwable cause) {
super(cause);
}
public CloudstackRESTException(final String message, final Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,377 @@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.utils.rest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
import org.apache.log4j.Logger;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
import com.google.gson.reflect.TypeToken;
/**
* This abstraction encapsulates client side code for REST service communication. It encapsulates
* access in a delegate validation strategy. There may different implementations extending
* {@link RESTValidationStrategy}, and any of them should mention the needed data to work.
*
* This connector allows the use of {@link JsonDeserializer} for specific classes. You can provide
* in the constructor a list of classes and a list of deserializers for these classes. These should
* be a correlated so that Nth deserializer is correctly mapped to Nth class.
*/
public class RESTServiceConnector {
private static final String HTTPS = "https";
protected static final String GET_METHOD_TYPE = "get";
protected static final String DELETE_METHOD_TYPE = "delete";
protected static final String PUT_METHOD_TYPE = "put";
protected static final String POST_METHOD_TYPE = "post";
private static final String TEXT_HTML_CONTENT_TYPE = "text/html";
private static final String JSON_CONTENT_TYPE = "application/json";
private static final String CONTENT_TYPE = "Content-Type";
private static final int BODY_RESP_MAX_LEN = 1024;
private static final int HTTPS_PORT = 443;
private static final Logger s_logger = Logger.getLogger(RESTServiceConnector.class);
protected final static String protocol = HTTPS;
private final static MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager();
protected RESTValidationStrategy validation;
private final HttpClient client;
private final Gson gson;
/**
* Getter that may be needed only for test purpose
*
* @return
*/
public Gson getGson() {
return gson;
}
public RESTServiceConnector(final RESTValidationStrategy validationStrategy) {
this(validationStrategy, null, null);
}
public RESTServiceConnector(final RESTValidationStrategy validationStrategy, final List<Class<?>> classList, final List<JsonDeserializer<?>> deserializerList) {
validation = validationStrategy;
client = createHttpClient();
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
try {
// Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter
Protocol.registerProtocol(HTTPS, new Protocol(HTTPS, (ProtocolSocketFactory)new TrustingProtocolSocketFactory(), HTTPS_PORT));
} catch (final IOException e) {
s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
}
final GsonBuilder gsonBuilder = new GsonBuilder();
if(classList != null && deserializerList != null) {
for(int i = 0; i < classList.size() && i < deserializerList.size(); i++) {
gsonBuilder.registerTypeAdapter(classList.get(i), deserializerList.get(i));
}
}
gson = gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
}
public HttpClient createHttpClient() {
return new HttpClient(s_httpClientManager);
}
public HttpMethod createMethod(final String type, final String uri) throws CloudstackRESTException {
String url;
try {
url = new URL(protocol, validation.getHost(), uri).toString();
} catch (final MalformedURLException e) {
s_logger.error("Unable to build REST Service URL", e);
throw new CloudstackRESTException("Unable to build Nicira API URL", e);
}
if (POST_METHOD_TYPE.equalsIgnoreCase(type)) {
return new PostMethod(url);
} else if (GET_METHOD_TYPE.equalsIgnoreCase(type)) {
return new GetMethod(url);
} else if (DELETE_METHOD_TYPE.equalsIgnoreCase(type)) {
return new DeleteMethod(url);
} else if (PUT_METHOD_TYPE.equalsIgnoreCase(type)) {
return new PutMethod(url);
} else {
throw new CloudstackRESTException("Requesting unknown method type");
}
}
public void setControllerAddress(final String address) {
validation.setHost(address);
}
public void setAdminCredentials(final String username, final String password) {
validation.setUser(username);
validation.setPassword(password);
}
public <T> void executeUpdateObject(final T newObject, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
final PutMethod pm = (PutMethod)createMethod(PUT_METHOD_TYPE, uri);
pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
try {
pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
} catch (final UnsupportedEncodingException e) {
throw new CloudstackRESTException("Failed to encode json request body", e);
}
executeMethod(pm);
if (pm.getStatusCode() != HttpStatus.SC_OK) {
final String errorMessage = responseToErrorMessage(pm);
pm.releaseConnection();
s_logger.error("Failed to update object : " + errorMessage);
throw new CloudstackRESTException("Failed to update object : " + errorMessage);
}
pm.releaseConnection();
}
@SuppressWarnings("unchecked")
public <T> T executeCreateObject(final T newObject, final Type returnObjectType, final String uri, final Map<String, String> parameters)
throws CloudstackRESTException {
final PostMethod pm = (PostMethod)createMethod(POST_METHOD_TYPE, uri);
pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
try {
pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
} catch (final UnsupportedEncodingException e) {
throw new CloudstackRESTException("Failed to encode json request body", e);
}
executeMethod(pm);
if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
final String errorMessage = responseToErrorMessage(pm);
pm.releaseConnection();
s_logger.error("Failed to create object : " + errorMessage);
throw new CloudstackRESTException("Failed to create object : " + errorMessage);
}
T result;
try {
result = (T)gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
} catch (final IOException e) {
throw new CloudstackRESTException("Failed to decode json response body", e);
} finally {
pm.releaseConnection();
}
return result;
}
public void executeDeleteObject(final String uri) throws CloudstackRESTException {
final DeleteMethod dm = (DeleteMethod)createMethod(DELETE_METHOD_TYPE, uri);
dm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
executeMethod(dm);
if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
final String errorMessage = responseToErrorMessage(dm);
dm.releaseConnection();
s_logger.error("Failed to delete object : " + errorMessage);
throw new CloudstackRESTException("Failed to delete object : " + errorMessage);
}
dm.releaseConnection();
}
@SuppressWarnings("unchecked")
public <T> T executeRetrieveObject(final Type returnObjectType, final String uri, final Map<String, String> parameters) throws CloudstackRESTException {
final GetMethod gm = (GetMethod)createMethod(GET_METHOD_TYPE, uri);
gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
if (parameters != null && !parameters.isEmpty()) {
final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
for (final Entry<String, String> e : parameters.entrySet()) {
nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue()));
}
gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
}
executeMethod(gm);
if (gm.getStatusCode() != HttpStatus.SC_OK) {
final String errorMessage = responseToErrorMessage(gm);
gm.releaseConnection();
s_logger.error("Failed to retrieve object : " + errorMessage);
throw new CloudstackRESTException("Failed to retrieve object : " + errorMessage);
}
T returnValue;
try {
returnValue = (T)gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
} catch (final IOException e) {
s_logger.error("IOException while retrieving response body", e);
throw new CloudstackRESTException(e);
} finally {
gm.releaseConnection();
}
return returnValue;
}
public void executeMethod(final HttpMethodBase method) throws CloudstackRESTException {
try {
validation.executeMethod(method, client, protocol);
} catch (final HttpException e) {
s_logger.error("HttpException caught while trying to connect to the REST Service", e);
method.releaseConnection();
throw new CloudstackRESTException("API call to REST Service Failed", e);
} catch (final IOException e) {
s_logger.error("IOException caught while trying to connect to the REST Service", e);
method.releaseConnection();
throw new CloudstackRESTException("API call to Nicira REST Service Failed", e);
}
}
private String responseToErrorMessage(final HttpMethodBase method) {
assert method.isRequestSent() : "no use getting an error message unless the request is sent";
if (TEXT_HTML_CONTENT_TYPE.equals(method.getResponseHeader(CONTENT_TYPE).getValue())) {
// The error message is the response content
// Safety margin of 1024 characters, anything longer is probably useless
// and will clutter the logs
try {
return method.getResponseBodyAsString(BODY_RESP_MAX_LEN);
} catch (final IOException e) {
s_logger.debug("Error while loading response body", e);
}
}
// The default
return method.getStatusText();
}
/* Some controllers use a self-signed certificate. The
* TrustingProtocolSocketFactory will accept any provided
* certificate when making an SSL connection to the SDN
* Manager
*/
private class TrustingProtocolSocketFactory implements SecureProtocolSocketFactory {
private SSLSocketFactory ssf;
public TrustingProtocolSocketFactory() throws IOException {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
// Trust always
}
@Override
public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
// Trust always
}
}};
try {
// Install the all-trusting trust manager
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
ssf = sc.getSocketFactory();
} catch (final KeyManagementException e) {
throw new IOException(e);
} catch (final NoSuchAlgorithmException e) {
throw new IOException(e);
}
}
@Override
public Socket createSocket(final String host, final int port) throws IOException {
return ssf.createSocket(host, port);
}
@Override
public Socket createSocket(final String address, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException {
return ssf.createSocket(address, port, localAddress, localPort);
}
@Override
public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
return ssf.createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
final int timeout = params.getConnectionTimeout();
if (timeout == 0) {
return createSocket(host, port, localAddress, localPort);
} else {
final Socket s = ssf.createSocket();
s.bind(new InetSocketAddress(localAddress, localPort));
s.connect(new InetSocketAddress(host, port), timeout);
return s;
}
}
}
}

View File

@ -0,0 +1,146 @@
package com.cloud.utils.rest;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
/**
* Basic authentication strategy. This strategy needs user and password for authentication.
*
* A login URL is needed which will be used for login and getting the cookie to be
* used in next requests. If an executeMethod request fails due to authorization it will try
* to login, get the cookie and repeat the attempt to execute the method.
*/
public class RESTValidationStrategy {
private static final Logger s_logger = Logger.getLogger(RESTValidationStrategy.class);
protected String host;
protected String user;
protected String password;
protected String serverVersion;
protected String loginUrl;
public RESTValidationStrategy(final String host, final String user, final String password,
final String serverVersion, final String loginUrl) {
super();
this.host = host;
this.user = user;
this.password = password;
this.serverVersion = serverVersion;
this.loginUrl = loginUrl;
}
public RESTValidationStrategy(final String loginUrl) {
this.loginUrl = loginUrl;
}
public RESTValidationStrategy() {
}
public String getUser() {
return user;
}
public void setUser(final String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(final String loginUrl) {
this.loginUrl = loginUrl;
}
public String getHost() {
return host;
}
public void setHost(final String host) {
this.host = host;
}
public void executeMethod(final HttpMethodBase method, final HttpClient client,
final String protocol)
throws CloudstackRESTException, HttpException, IOException {
if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
throw new CloudstackRESTException("Hostname/credentials are null or empty");
}
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
method.releaseConnection();
// login and try again
login(protocol, client);
client.executeMethod(method);
}
}
/**
* Logs against the REST server. The cookie is stored in the <code>_authcookie<code> variable.
* <p>
* The method returns false if the login failed or the connection could not be made.
*
*/
protected void login(final String protocol,
final HttpClient client)
throws CloudstackRESTException {
String url;
if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {
throw new CloudstackRESTException("Hostname/credentials are null or empty");
}
try {
url = new URL(protocol, host, loginUrl).toString();
} catch (final MalformedURLException e) {
s_logger.error("Unable to build Nicira API URL", e);
throw new CloudstackRESTException("Unable to build Nicira API URL", e);
}
final PostMethod pm = new PostMethod(url);
pm.addParameter("username", user);
pm.addParameter("password", password);
try {
client.executeMethod(pm);
} catch (final HttpException e) {
throw new CloudstackRESTException("REST Service API login failed ", e);
} catch (final IOException e) {
throw new CloudstackRESTException("REST Service API login failed ", e);
} finally {
pm.releaseConnection();
}
if (pm.getStatusCode() != HttpStatus.SC_OK) {
s_logger.error("REST Service API login failed : " + pm.getStatusText());
throw new CloudstackRESTException("REST Service API login failed " + pm.getStatusText());
}
// Extract the version for later use
if (pm.getResponseHeader("Server") != null) {
serverVersion = pm.getResponseHeader("Server").getValue();
s_logger.debug("Server reports version " + serverVersion);
}
// Success; the cookie required for login is kept in _client
}
}

View File

@ -0,0 +1,373 @@
package com.cloud.utils.rest;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Collections;
//import java.util.List;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
public class RESTServiceConnectorTest {
protected static final String UUID = "aaaa";
protected static final String UUID2 = "bbbb";
protected static final String SCHEMA = "myTestSchema";
protected static final String SCHEMA2 = "myTestSchema2";
protected static final String HREF = "myTestHref";
protected static final String HREF2 = "myTestHref2";
protected static final String DISPLAY_NAME = "myTestName";
protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}";
protected static final String SEC_PROFILE_JSON_RESPONSE =
"{\"uuid\" : \"aaaa\","
+ "\"display_name\" : \"myTestName\","
+ "\"href\" : \"myTestHref\","
+ "\"schema\" : \"myTestSchema\"}";
protected static final String SEC_PROFILE_LIST_JSON_RESPONSE = "{\"results\" : [{\"uuid\" : \"aaaa\","
+ "\"display_name\" : \"myTestName\","
+ "\"href\" : \"myTestHref\","
+ "\"schema\" : \"myTestSchema\"},"
+ "{ \"uuid\" : \"bbbb\","
+ "\"display_name\" : \"myTestName2\","
+ "\"href\" : \"myTestHref2\","
+ "\"schema\" : \"myTestSchema2\"}],"
+ "\"result_count\": 2}";
RESTServiceConnector connector;
HttpClient client = mock(HttpClient.class);
HttpMethod method;
String type;
String uri;
@Before
public void setUp() {
final HttpClientParams hmp = mock(HttpClientParams.class);
when(client.getParams()).thenReturn(hmp);
connector = new RESTServiceConnector(null) {
@Override
public HttpClient createHttpClient() {
return client;
}
@Override
public HttpMethod createMethod(final String newType, final String newUri) {
type = newType;
uri = newUri;
return method;
}
};
connector.validation = new RESTValidationStrategy();
connector.setAdminCredentials("admin", "adminpass");
connector.setControllerAddress("localhost");
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteLoginWithoutHostname() throws CloudstackRESTException {
connector.setControllerAddress(null);
connector.validation.login(RESTServiceConnector.protocol, client);
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteLoginWithoutCredentials() throws CloudstackRESTException {
method = mock(PutMethod.class);
connector.setAdminCredentials(null, null);
connector.validation.login(RESTServiceConnector.protocol, client);
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteUpdateObjectWithoutHostname() throws CloudstackRESTException {
method = mock(PutMethod.class);
connector.setControllerAddress(null);
connector.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap());
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteUpdateObjectWithoutCredentials() throws CloudstackRESTException {
method = mock(PutMethod.class);
connector.setAdminCredentials(null, null);
connector.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap());
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteCreateObjectWithoutHostname() throws CloudstackRESTException {
method = mock(PostMethod.class);
connector.setControllerAddress(null);
connector.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap());
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteCreateObjectWithoutCredentials() throws CloudstackRESTException {
method = mock(PostMethod.class);
connector.setAdminCredentials(null, null);
connector.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap());
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteDeleteObjectWithoutHostname() throws CloudstackRESTException {
method = mock(DeleteMethod.class);
connector.setControllerAddress(null);
connector.executeDeleteObject("/");
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteDeleteObjectWithoutCredentials() throws CloudstackRESTException {
method = mock(DeleteMethod.class);
connector.setAdminCredentials(null, null);
connector.executeDeleteObject("/");
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteRetrieveObjectWithoutHostname() throws CloudstackRESTException {
method = mock(GetMethod.class);
connector.setControllerAddress(null);
connector.executeRetrieveObject(String.class, "/", Collections.<String, String> emptyMap());
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteRetrieveObjectWithoutCredentials() throws CloudstackRESTException {
method = mock(GetMethod.class);
connector.setAdminCredentials(null, null);
connector.executeRetrieveObject(String.class, "/", Collections.<String, String> emptyMap());
}
@Test
public void testExecuteMethod() throws CloudstackRESTException {
final GetMethod gm = mock(GetMethod.class);
when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK);
connector.executeMethod(gm);
verify(gm, times(1)).getStatusCode();
}
/* Bit of a roundabout way to ensure that login is called after an un authorized result
* It not possible to properly mock login()
*/
@Test(expected = CloudstackRESTException.class)
public void testExecuteMethodWithLogin() throws CloudstackRESTException, HttpException, IOException {
final GetMethod gm = mock(GetMethod.class);
when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED);
connector.executeMethod(gm);
verify(gm, times(1)).getStatusCode();
}
@Test
public void testExecuteCreateObject() throws CloudstackRESTException, IOException {
JsonEntity ls = new JsonEntity();
method = mock(PostMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
assertTrue(UUID.equals(ls.getUuid()));
verify(method, times(1)).releaseConnection();
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteCreateObjectFailure() throws CloudstackRESTException, IOException {
JsonEntity ls = new JsonEntity();
method = mock(PostMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
final Header header = mock(Header.class);
when(header.getValue()).thenReturn("text/html");
when(method.getResponseHeader("Content-Type")).thenReturn(header);
when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
when(method.isRequestSent()).thenReturn(true);
try {
ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteCreateObjectException() throws CloudstackRESTException, IOException {
JsonEntity ls = new JsonEntity();
when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
method = mock(PostMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
final Header header = mock(Header.class);
when(header.getValue()).thenReturn("text/html");
when(method.getResponseHeader("Content-Type")).thenReturn(header);
when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
try {
ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test
public void testExecuteUpdateObject() throws CloudstackRESTException, IOException {
final JsonEntity ls = new JsonEntity();
method = mock(PutMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
verify(method, times(1)).releaseConnection();
verify(client, times(1)).executeMethod(method);
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteUpdateObjectFailure() throws CloudstackRESTException, IOException {
final JsonEntity ls = new JsonEntity();
method = mock(PutMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
final Header header = mock(Header.class);
when(header.getValue()).thenReturn("text/html");
when(method.getResponseHeader("Content-Type")).thenReturn(header);
when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
when(method.isRequestSent()).thenReturn(true);
try {
connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteUpdateObjectException() throws CloudstackRESTException, IOException {
final JsonEntity ls = new JsonEntity();
method = mock(PutMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
when(client.executeMethod((HttpMethod)any())).thenThrow(new IOException());
try {
connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test
public void testExecuteDeleteObject() throws CloudstackRESTException, IOException {
method = mock(DeleteMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
connector.executeDeleteObject("/");
verify(method, times(1)).releaseConnection();
verify(client, times(1)).executeMethod(method);
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteDeleteObjectFailure() throws CloudstackRESTException, IOException {
method = mock(DeleteMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
final Header header = mock(Header.class);
when(header.getValue()).thenReturn("text/html");
when(method.getResponseHeader("Content-Type")).thenReturn(header);
when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
when(method.isRequestSent()).thenReturn(true);
try {
connector.executeDeleteObject("/");
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteDeleteObjectException() throws CloudstackRESTException, IOException {
method = mock(DeleteMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
try {
connector.executeDeleteObject("/");
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test
public void testExecuteRetrieveObject() throws CloudstackRESTException, IOException {
method = mock(GetMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
verify(method, times(1)).releaseConnection();
verify(client, times(1)).executeMethod(method);
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteRetrieveObjectFailure() throws CloudstackRESTException, IOException {
method = mock(GetMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
final Header header = mock(Header.class);
when(header.getValue()).thenReturn("text/html");
when(method.getResponseHeader("Content-Type")).thenReturn(header);
when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
when(method.isRequestSent()).thenReturn(true);
try {
connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
@Test(expected = CloudstackRESTException.class)
public void testExecuteRetrieveObjectException() throws CloudstackRESTException, IOException {
method = mock(GetMethod.class);
when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK);
when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE);
when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException());
try {
connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap());
} finally {
verify(method, times(1)).releaseConnection();
}
}
}
class JsonEntity {
private String displayName;
private String uuid;
private String href;
private String schema;
public String getDisplayName() {
return displayName;
}
public void setDisplayName(final String displayName) {
this.displayName = displayName;
}
public String getUuid() {
return uuid;
}
public void setUuid(final String uuid) {
this.uuid = uuid;
}
public String getHref() {
return href;
}
public void setHref(final String href) {
this.href = href;
}
public String getSchema() {
return schema;
}
public void setSchema(final String schema) {
this.schema = schema;
}
}