Phase 1 of Nicira integration

This commit is contained in:
Hugo Trippaers 2012-07-11 16:14:28 -07:00 committed by Murali Reddy
parent 8b7b838c8a
commit 79c7da07ab
61 changed files with 3155 additions and 22 deletions

View File

@ -21,6 +21,7 @@ public class NicTO extends NetworkTO {
Integer networkRateMbps;
Integer networkRateMulticastMbps;
boolean defaultNic;
String uuid;
public NicTO() {
super();
@ -54,6 +55,16 @@ public class NicTO extends NetworkTO {
this.defaultNic = defaultNic;
}
@Override
public String getUuid() {
return uuid;
}
@Override
public void setUuid(String uuid) {
this.uuid = uuid;
}
@Override
public String toString() {
return new StringBuilder("[Nic:").append(type).append("-").append(ip).append("-").append(broadcastUri).append("]").toString();

View File

@ -42,6 +42,7 @@ public class VirtualMachineTO {
String vncPassword;
String vncAddr;
Map<String, String> params;
String uuid;
VolumeTO[] disks;
NicTO[] nics;
@ -208,4 +209,14 @@ public class VirtualMachineTO {
public void setDetails(Map<String, String> params) {
this.params = params;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}

View File

@ -361,6 +361,10 @@ public class ApiConstants {
public static final String RESOURCE_IDS = "resourceids";
public static final String RESOURCE_ID = "resourceid";
public static final String CUSTOMER = "customer";
public static final String NICIRA_NVP_DEVICE_ID = "nvpdeviceid";
public static final String NICIRA_NVP_TRANSPORT_ZONE_UUID = "transportzoneuuid";
public static final String NICIRA_NVP_DEVICE_NAME = "niciradevicename";
public enum HostDetails {
all, capacity, events, stats, min;

View File

@ -41,7 +41,8 @@ public interface Host extends StateObject<Status> {
ExternalDhcp(false),
SecondaryStorageVM(true),
LocalSecondaryStorage(false);
LocalSecondaryStorage(false),
L2Networking(false);
boolean _virtual;
private Type(boolean virtual) {
_virtual = virtual;

View File

@ -52,6 +52,7 @@ public interface Network extends ControlledEntity {
public static final Service StaticNat = new Service("StaticNat", Capability.ElasticIp);
public static final Service PortForwarding = new Service("PortForwarding");
public static final Service SecurityGroup = new Service("SecurityGroup");
public static final Service Connectivity = new Service("Connectivity");
private String name;
private Capability[] caps;
@ -114,6 +115,7 @@ public interface Network extends ControlledEntity {
public static final Provider ElasticLoadBalancerVm = new Provider("ElasticLoadBalancerVm", false);
public static final Provider SecurityGroupProvider = new Provider("SecurityGroupProvider", false);
public static final Provider None = new Provider("None", false);
public static final Provider NiciraNvp = new Provider("NiciraNvp", true);
private String name;
private boolean isExternal;

View File

@ -61,6 +61,7 @@ public class Networks {
LinkLocal(null, null),
Vnet("vnet", Long.class),
Storage("storage", Integer.class),
Lswitch("lswitch", String.class),
UnDecided(null, null);
private String scheme;

View File

@ -31,7 +31,8 @@ public interface PhysicalNetwork {
public enum IsolationMethod {
VLAN,
L3,
GRE;
GRE,
STT;
}
public enum BroadcastDomainRange {

View File

@ -279,8 +279,8 @@
<!-- ===================== Network Elements ===================== -->
<target name="compile-network-elements" depends="compile-netscaler, compile-f5, compile-srx, compile-ovs, compile-elb" description="Compile all network elements"/>
<target name="build-network-elements" depends="build-netscaler, build-f5, build-srx, build-ovs, build-elb" description="build all network elements"/>
<target name="compile-network-elements" depends="compile-netscaler, compile-f5, compile-srx, compile-ovs, compile-elb, compile-nicira-nvp" description="Compile all network elements"/>
<target name="build-network-elements" depends="build-netscaler, build-f5, build-srx, build-ovs, build-elb, build-nicira-nvp" description="build all network elements"/>
<target name="compile-netscaler" depends="-init, compile-server" description="Compile NetScaler plugin">
<ant antfile="${base.dir}/plugins/network-elements/netscaler/build.xml" target="build"/>
@ -301,6 +301,12 @@
<ant antfile="${base.dir}/plugins/network-elements/ovs/build.xml" target="build"/>
</target>
<target name="build-ovs" depends="compile-ovs"/>
<target name="compile-nicira-nvp" depends="-init, compile-server" description="Compile Nicira NVP plugin">
<ant antfile="${base.dir}/plugins/network-elements/nicira-nvp/build.xml" target="build"/>
</target>
<target name="build-nicira-nvp" depends="compile-nicira-nvp"/>
<target name="compile-elb" depends="-init, compile-server" description="Compile ELB plugin">
<ant antfile="${base.dir}/plugins/network-elements/elastic-loadbalancer/build.xml" target="build"/>

View File

@ -225,6 +225,7 @@
<include name="${core.jar}" />
<include name="${api.jar}" />
<include name="${vmware-base.jar}" />
<include name="${vmware.jar}" />
</zipfileset>
<zipfileset dir="${console-proxy.dist.dir}" filemode="555"/>
<zipfileset dir="${scripts.dir}/storage/secondary" prefix="scripts/storage/secondary" filemode="555">

View File

@ -70,7 +70,7 @@
However, above case barely happens.
-->
<adapter name="StorageNetworkGuru" class="com.cloud.network.guru.StorageNetworkGuru"/>
<adapter name="StorageNetworkGuru" class="com.cloud.network.guru.StorageNetworkGuru"/>
<adapter name="ExternalGuestNetworkGuru" class="com.cloud.network.guru.ExternalGuestNetworkGuru"/>
<adapter name="PublicNetworkGuru" class="com.cloud.network.guru.PublicNetworkGuru"/>
<adapter name="PodBasedNetworkGuru" class="com.cloud.network.guru.PodBasedNetworkGuru"/>
@ -78,6 +78,7 @@
<adapter name="DirectNetworkGuru" class="com.cloud.network.guru.DirectNetworkGuru"/>
<adapter name="DirectPodBasedNetworkGuru" class="com.cloud.network.guru.DirectPodBasedNetworkGuru"/>
<adapter name="OvsGuestNetworkGuru" class="com.cloud.network.guru.OvsGuestNetworkGuru"/>
<adapter name="NiciraNvpGuestNetworkGuru" class="com.cloud.network.guru.NiciraNvpGuestNetworkGuru"/>
</adapters>
<adapters key="com.cloud.cluster.ClusterServiceAdapter">
<adapter name="ClusterService" class="com.cloud.cluster.ClusterServiceServletAdapter"/>
@ -142,6 +143,7 @@
<adapter name="BareMetal" class="com.cloud.network.element.BareMetalElement"/>
<adapter name="SecurityGroupProvider" class="com.cloud.network.element.SecurityGroupElement"/>
<adapter name="CiscoNexus1000vVSM" class="com.cloud.network.element.CiscoNexusVSMElement"/>
<adapter name="NiciraNvp" class="com.cloud.network.element.NiciraNvpElement"/>
</adapters>
<adapters key="com.cloud.cluster.agentlb.AgentLoadBalancerPlanner">
<adapter name="ClusterBasedAgentLbPlanner" class="com.cloud.cluster.agentlb.ClusterBasedAgentLoadBalancerPlanner"/>
@ -165,10 +167,13 @@
<pluggableservice name="F5ExternalLoadBalancerElementService" key="com.cloud.network.element.F5ExternalLoadBalancerElementService" class="com.cloud.network.element.F5ExternalLoadBalancerElement"/>
<pluggableservice name="JuniperSRXFirewallElementService" key="com.cloud.network.element.JuniperSRXFirewallElementService" class="com.cloud.network.element.JuniperSRXExternalFirewallElement"/>
<pluggableservice name="CiscoNexusVSMElementService" key="com.coud.network.element.CiscoNexusVSMElementService" class="com.cloud.network.element.CiscoNexusVSMElement"/>
<pluggableservice name="NiciraNvpElementService" key="com.coud.network.element.NiciraNvpElementService" class="com.cloud.network.element.NiciraNvpElement"/>
<dao name="NetScalerPodDao" class="com.cloud.network.dao.NetScalerPodDaoImpl" singleton="false"/>
<dao name="CiscoNexusVSMDeviceDao" class="com.cloud.network.dao.CiscoNexusVSMDeviceDaoImpl" singleton="false"/>
<dao name="OvsTunnelInterfaceDao" class="com.cloud.network.ovs.dao.OvsTunnelInterfaceDaoImpl" singleton="false"/>
<dao name="OvsTunnelAccountDao" class="com.cloud.network.ovs.dao.OvsTunnelNetworkDaoImpl" singleton="false"/>
<dao name="NiciraNvpDao" class="com.cloud.network.dao.NiciraNvpDaoImpl" singleton="false"/>
<dao name="NiciraNvpNicMappingDao" class="com.cloud.network.dao.NiciraNvpNicMappingDaoImpl" singleton="false"/>
<dao name="NetappPool" class="com.cloud.netapp.dao.PoolDaoImpl" singleton="false"/>
<dao name="NetappVolume" class="com.cloud.netapp.dao.VolumeDaoImpl" singleton="false"/>
<dao name="NetappLun" class="com.cloud.netapp.dao.LunDaoImpl" singleton="false"/>

View File

@ -0,0 +1,12 @@
### bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER
### Please standardize naming conventions to camel-case (even for acronyms).
#### nicira nvp commands
addNiciraNvpDevice = com.cloud.api.commands.AddNiciraNvpDeviceCmd;1
deleteNiciraNvpDevice = com.cloud.api.commands.DeleteNiciraNvpDeviceCmd;1
listNiciraNvpDevices = com.cloud.api.commands.ListNiciraNvpDevicesCmd;1
listNiciraNvpDeviceNetworks = com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd;1
# Not implemented (yet)
#configureNiciraNvpDevice = com.cloud.api.commands.ConfigureNiciraNvpDeviceCmd;1

View File

@ -427,6 +427,7 @@ fi
%{_javadir}/%{name}-user-authenticator-plaintext.jar
%{_javadir}/%{name}-vmware.jar
%{_javadir}/%{name}-xen.jar
%{_javadir}/%{name}-plugin-nicira-nvp.jar
%{_javadir}/%{name}-plugin-elb.jar
%{_javadir}/%{name}-plugin-netapp.jar
%config(noreplace) %{_sysconfdir}/%{name}/server/*

View File

@ -751,12 +751,17 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
long vlan = Long.parseLong(broadcastUri.getHost());
return enableVlanNetwork(conn, vlan, network);
}
} else if (nic.getBroadcastType() == BroadcastDomainType.Lswitch) {
// Nicira Logical Switch
return network.getNetwork();
}
throw new CloudRuntimeException("Unable to support this type of network broadcast domain: " + nic.getBroadcastUri());
}
protected VIF createVif(Connection conn, String vmName, VM vm, NicTO nic) throws XmlRpcException, XenAPIException {
assert(nic.getUuid() != null) : "Nic should have a uuid value";
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating VIF for " + vmName + " on nic " + nic);
}
@ -765,7 +770,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
vifr.VM = vm;
vifr.device = Integer.toString(nic.getDeviceId());
vifr.MAC = nic.getMac();
// Nicira needs these IDs to find the NIC
vifr.otherConfig = new HashMap<String, String>();
vifr.otherConfig.put("nicira-iface-id", nic.getUuid());
vifr.otherConfig.put("nicira-vm-id", vm.getUuid(conn));
vifr.network = getNetwork(conn, nic);
if (nic.getNetworkRateMbps() != null && nic.getNetworkRateMbps().intValue() != -1) {

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jdk1.6.0_31"/>
<classpathentry combineaccessrules="false" kind="src" path="/agent"/>
<classpathentry combineaccessrules="false" kind="src" path="/core"/>
<classpathentry combineaccessrules="false" kind="src" path="/deps"/>
<classpathentry combineaccessrules="false" kind="src" path="/server"/>
<classpathentry combineaccessrules="false" kind="src" path="/utils"/>
<classpathentry combineaccessrules="false" kind="src" path="/api"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>nicira-nvp</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,68 @@
Nicira Network Virtualization Platform (NVP) integration code is contributed
by Nicira and Schuberg Philis and copyright is donated to the Apache Software
Foundation.
Authors
Somik Behera <sbehera@nicira.com>
Hugo Trippaers <htrippaers@schubergphilis.com>
== New API Calls
The following API calls are added to CloudStack to support the integrations with
the Nicira NVP platform. Please see the API documentation of CloudStack for
parameters and return values.
* addNiciraNvpDevice
* deleteNiciraNvpDevice
* listNiciraNvpDevices
* listNiciraNvpDeviceNetworks
== How to enable the Nicira NVP integration.
When configuring a zone create a new physical network for "Guest" traffic and
select "STT" as the isolation type. Set the Xen traffic label for "Guest"
traffic to the label of the integration bridge (refer to the Nicira
Documentation for setting up the integration bridge). Note that this requires
all traffic types to have their traffic labels set.
These steps are specified by the API calls as there is currently no GUI
available.
1. addNetworkServiceProvider
name="NiciraNvp", physicalnetworkid=<see above>,
servicelist="Connectivity"
2. updateNetworkServiceProvider
id=<id from step1>, state="Enabled"
3. addNiciraNvpDevice
physicalnetworkid=<see step 1>,
hostname=<hostname or IP of the controller>
username=<admin username>
password=<admin password>
transportzoneuuid=<transport zone uuid>
== How to use the Nicira integration
When creating a guest network make sure it is created in the physical network
with the isolation type set to "STT". When the first virtual machine is
launched in this network the NiciraNvpNetworkGuru will configure a logical
switch on the NVP Controller. During the startup of a virtual machine the
NiciraNvpElement will create a logical port for any NICs in the guest networks
and attach the port to the existing logical swith.
== Debugging/Troubleshooting
All elements created on the NVP controller have tags with the name of the
account, this can be used to search the items using the NVP manager. The NVP
uuid of the logical switch is also stored in the BroadcastUri of the
corresponding Guest network in an lswitch uri scheme. The CloudStack uuid of
the NIC is used to make the Vif attachement on the logical switchport.
The following classes should be set to log level debug when troubleshooting.
com.cloud.network
(Most NiciraNvp related objects live in this package and subpackages)
org.apache.commons.httpclient
(used by NiciraNvpApi to make calls to the SDN Controller)
httpclient.wire
(wirelevel http tracing of httpclient)
Please report any findings to the developer mailing list.

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project name="Cloud Stack Nicira NVP network element" default="help" basedir=".">
<description>
Cloud Stack ant build file
</description>
<dirname property="nicira-nvp.base.dir" file="${ant.file.Cloud Stack Nicira NVP network element}/"/>
<!-- This directory must be set -->
<property name="top.dir" location="${nicira-nvp.base.dir}/../../.."/>
<property name="build.dir" location="${top.dir}/build"/>
<echo message="build.dir=${build.dir}; top.dir=${top.dir}; nicira-nvp.base.dir=${nicira-nvp.base.dir}"/>
<!-- Import anything that the user wants to set-->
<!-- Import properties files and environment variables here -->
<property environment="env" />
<condition property="build-cloud.properties.file" value="${build.dir}/override/build-cloud.properties" else="${build.dir}/build-cloud.properties">
<available file="${build.dir}/override/build-cloud.properties" />
</condition>
<condition property="cloud.properties.file" value="${build.dir}/override/cloud.properties" else="${build.dir}/cloud.properties">
<available file="${build.dir}/override/cloud.properties" />
</condition>
<condition property="override.file" value="${build.dir}/override/replace.properties" else="${build.dir}/replace.properties">
<available file="${build.dir}/override/replace.properties" />
</condition>
<echo message="Using build parameters from ${build-cloud.properties.file}" />
<property file="${build-cloud.properties.file}" />
<echo message="Using company info from ${cloud.properties.file}" />
<property file="${cloud.properties.file}" />
<echo message="Using override file from ${override.file}" />
<property file="${override.file}" />
<property file="${build.dir}/build.number" />
<!-- In case these didn't get defined in the build-cloud.properties -->
<property name="branding.name" value="default" />
<property name="deprecation" value="off" />
<property name="target.compat.version" value="1.6" />
<property name="source.compat.version" value="1.6" />
<property name="debug" value="true" />
<property name="debuglevel" value="lines,source"/>
<echo message="target.dir=${target.dir}; top.dir=${top.dir}"/>
<!-- directories for build and distribution -->
<property name="target.dir" location="${top.dir}/target" />
<property name="classes.dir" location="${target.dir}/classes" />
<property name="jar.dir" location="${target.dir}/jar" />
<property name="dep.cache.dir" location="${target.dir}/dep-cache" />
<property name="build.log" location="${target.dir}/ant_verbose.txt" />
<property name="deps.dir" location="${top.dir}/deps" />
<property name="cloud-plugin-nicira-nvp.jar" value="cloud-plugin-nicira-nvp.jar" />
<import file="${build.dir}/build-common.xml"/>
<echo message="target.dir=${target.dir}; top.dir=${top.dir}"/>
<!-- This section needs to be replaced by some kind of dependency library-->
<path id="deps.classpath">
<!--filelist files="${deps.classpath}" /-->
<fileset dir="${deps.dir}" erroronmissingdir="false">
<include name="*.jar" />
</fileset>
</path>
<path id="cloudstack.classpath">
<fileset dir="${jar.dir}">
<include name="*.jar"/>
</fileset>
</path>
<path id="nicira-nvp.classpath">
<path refid="deps.classpath"/>
<path refid="cloudstack.classpath"/>
</path>
<!-- This section needs to be replaced by some kind of dependency library-->
<target name="deploy-nicira-nvp" >
</target>
<target name="init" description="Initialize binaries directory">
<mkdir dir="${classes.dir}/${cloud-plugin-nicira-nvp.jar}"/>
<mkdir dir="${jar.dir}"/>
</target>
<target name="compile-nicira-nvp" depends="init" description="Compile Nicira Nvp">
<compile-java jar.name="${cloud-plugin-nicira-nvp.jar}" top.dir="${nicira-nvp.base.dir}" classpath="nicira-nvp.classpath" />
</target>
<target name="clean-nicira-nvp">
<delete dir="${classes.dir}/${cloud-plugin-nicira-nvp.jar}"/>
</target>
<target name="build" depends="compile-nicira-nvp"/>
<target name="clean" depends="clean-nicira-nvp"/>
<target name="help" description="help">
<echo level="info" message="This is the build file for Nicira Nvp"/>
<echo level="info" message="You can do a build by doing ant build or clean by doing ant clean" />
</target>
</project>

View File

@ -0,0 +1,20 @@
package com.cloud.agent.api;
public class CreateLogicalSwitchAnswer extends Answer {
private String _logicalSwitchUuid;
public CreateLogicalSwitchAnswer(Command command, boolean success,
String details, String logicalSwitchUuid) {
super(command, success, details);
this._logicalSwitchUuid = logicalSwitchUuid;
}
public CreateLogicalSwitchAnswer(Command command, Exception e) {
super(command, e);
}
public String getLogicalSwitchUuid() {
return _logicalSwitchUuid;
}
}

View File

@ -0,0 +1,38 @@
package com.cloud.agent.api;
public class CreateLogicalSwitchCommand extends Command {
private String _transportUuid;
private String _transportType;
private String _name;
private String _ownerName;
public CreateLogicalSwitchCommand(String transportUuid, String transportType, String name, String ownerName) {
this._transportUuid = transportUuid;
this._transportType = transportType;
this._name = name;
this._ownerName = ownerName;
}
@Override
public boolean executeInSequence() {
return false;
}
public String getTransportUuid() {
return _transportUuid;
}
public String getTransportType() {
return _transportType;
}
public String getName() {
return _name;
}
public String getOwnerName() {
return _ownerName;
}
}

View File

@ -0,0 +1,20 @@
package com.cloud.agent.api;
public class CreateLogicalSwitchPortAnswer extends Answer {
private String _logicalSwitchPortUuid;
public CreateLogicalSwitchPortAnswer(Command command, boolean success,
String details, String localSwitchPortUuid) {
super(command, success, details);
this._logicalSwitchPortUuid = localSwitchPortUuid;
}
public String getLogicalSwitchPortUuid() {
return _logicalSwitchPortUuid;
}
public CreateLogicalSwitchPortAnswer(Command command, Exception e) {
super(command, e);
}
}

View File

@ -0,0 +1,42 @@
package com.cloud.agent.api;
public class CreateLogicalSwitchPortCommand extends Command {
private String _logicalSwitchUuid;
private String _attachmentUuid;
private String _ownerName;
private String _nicName;
public CreateLogicalSwitchPortCommand(String logicalSwitchUuid, String attachmentUuid, String ownerName, String nicName) {
this._logicalSwitchUuid = logicalSwitchUuid;
this._attachmentUuid = attachmentUuid;
this._ownerName = ownerName;
this._nicName = nicName;
}
public String getLogicalSwitchUuid() {
return _logicalSwitchUuid;
}
public String getAttachmentUuid() {
return _attachmentUuid;
}
public String getOwnerName() {
return _ownerName;
}
public String getNicName() {
return _nicName;
}
@Override
public boolean executeInSequence() {
return false;
}
}

View File

@ -0,0 +1,14 @@
package com.cloud.agent.api;
public class DeleteLogicalSwitchAnswer extends Answer {
public DeleteLogicalSwitchAnswer(Command command, boolean success,
String details) {
super(command, success, details);
}
public DeleteLogicalSwitchAnswer(Command command, Exception e) {
super(command, e);
}
}

View File

@ -0,0 +1,19 @@
package com.cloud.agent.api;
public class DeleteLogicalSwitchCommand extends Command {
private String _logicalSwitchUuid;
public DeleteLogicalSwitchCommand(String logicalSwitchUuid) {
this._logicalSwitchUuid = logicalSwitchUuid;
}
@Override
public boolean executeInSequence() {
return false;
}
public String getLogicalSwitchUuid() {
return _logicalSwitchUuid;
}
}

View File

@ -0,0 +1,14 @@
package com.cloud.agent.api;
public class DeleteLogicalSwitchPortAnswer extends Answer {
public DeleteLogicalSwitchPortAnswer(Command command, boolean success,
String details) {
super(command, success, details);
}
public DeleteLogicalSwitchPortAnswer(Command command, Exception e) {
super(command, e);
}
}

View File

@ -0,0 +1,25 @@
package com.cloud.agent.api;
public class DeleteLogicalSwitchPortCommand extends Command {
private String _logicalSwitchUuid;
private String _logicalSwithPortUuid;
public DeleteLogicalSwitchPortCommand(String logicalSwitchUuid, String logicalSwitchPortUuid) {
this._logicalSwitchUuid = logicalSwitchUuid;
this._logicalSwithPortUuid = logicalSwitchPortUuid;
}
public String getLogicalSwitchUuid() {
return _logicalSwitchUuid;
}
public String getLogicalSwitchPortUuid() {
return _logicalSwithPortUuid;
}
@Override
public boolean executeInSequence() {
return false;
}
}

View File

@ -0,0 +1,11 @@
package com.cloud.agent.api;
import com.cloud.host.Host;
public class StartupNiciraNvpCommand extends StartupCommand {
public StartupNiciraNvpCommand() {
super(Host.Type.L2Networking);
}
}

View File

@ -0,0 +1,110 @@
package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseAsyncCmd;
import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.PlugService;
import com.cloud.api.ServerApiException;
import com.cloud.api.BaseCmd.CommandType;
import com.cloud.api.response.NiciraNvpDeviceResponse;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.ExternalLoadBalancerDeviceVO;
import com.cloud.network.NiciraNvpDeviceVO;
import com.cloud.network.element.NiciraNvpElementService;
import com.cloud.user.UserContext;
import com.cloud.utils.exception.CloudRuntimeException;
@Implementation(responseObject=NiciraNvpDeviceResponse.class, description="Adds a Nicira NVP device")
public class AddNiciraNvpDeviceCmd extends BaseCmd {
private static final Logger s_logger = Logger.getLogger(AddNiciraNvpDeviceCmd.class.getName());
private static final String s_name = "addniciranvpdevice";
@PlugService NiciraNvpElementService _niciraNvpElementService;
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@IdentityMapper(entityTableName="physical_network")
@Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID")
private Long physicalNetworkId;
@Parameter(name=ApiConstants.HOST_NAME, type=CommandType.STRING, required = true, description="Hostname of ip address of the Nicira NVP Controller.")
private String host;
@Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required = true, description="Credentials to access the Nicira Controller API")
private String username;
@Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Credentials to access the Nicira Controller API")
private String password;
@Parameter(name=ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID, type=CommandType.STRING, required = true, description="The Transportzone UUID configured on the Nicira Controller")
private String transportzoneuuid;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getPhysicalNetworkId() {
return physicalNetworkId;
}
public String getHost() {
return host;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getTransportzoneUuid() {
return transportzoneuuid;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
try {
NiciraNvpDeviceVO niciraNvpDeviceVO = _niciraNvpElementService.addNiciraNvpDevice(this);
if (niciraNvpDeviceVO != null) {
NiciraNvpDeviceResponse response = _niciraNvpElementService.createNiciraNvpDeviceResponse(niciraNvpDeviceVO);
response.setObjectName("niciranvpdevice");
response.setResponseName(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseAsyncCmd.INTERNAL_ERROR, "Failed to add Nicira NVP device due to internal error.");
}
} catch (InvalidParameterValueException invalidParamExcp) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage());
} catch (CloudRuntimeException runtimeExcp) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage());
}
}
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return UserContext.current().getCaller().getId();
}
}

View File

@ -0,0 +1,76 @@
package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.PlugService;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.SuccessResponse;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.element.NiciraNvpElementService;
import com.cloud.user.UserContext;
import com.cloud.utils.exception.CloudRuntimeException;
@Implementation(responseObject=SuccessResponse.class, description=" delete a nicira nvp device")
public class DeleteNiciraNvpDeviceCmd extends BaseCmd {
private static final Logger s_logger = Logger.getLogger(DeleteNiciraNvpDeviceCmd.class.getName());
private static final String s_name = "addniciranvpdevice";
@PlugService NiciraNvpElementService _niciraNvpElementService;
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@IdentityMapper(entityTableName="external_nicira_nvp_devices")
@Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.LONG, required=true, description="Nicira device ID")
private Long niciraNvpDeviceId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getNiciraNvpDeviceId() {
return niciraNvpDeviceId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
try {
boolean result = _niciraNvpElementService.deleteNiciraNvpDevice(this);
if (result) {
SuccessResponse response = new SuccessResponse(getCommandName());
response.setResponseName(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete Nicira device.");
}
} catch (InvalidParameterValueException invalidParamExcp) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage());
} catch (CloudRuntimeException runtimeExcp) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage());
}
}
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return UserContext.current().getCaller().getId();
}
}

View File

@ -0,0 +1,85 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseCmd;
import com.cloud.api.BaseListCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.PlugService;
import com.cloud.api.ServerApiException;
import com.cloud.api.BaseCmd.CommandType;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.NetworkResponse;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Network;
import com.cloud.network.element.NiciraNvpElementService;
import com.cloud.utils.exception.CloudRuntimeException;
@Implementation(responseObject=NetworkResponse.class, description="lists network that are using a nicira nvp device")
public class ListNiciraNvpDeviceNetworksCmd extends BaseListCmd {
public static final Logger s_logger = Logger.getLogger(ListNiciraNvpDeviceNetworksCmd.class.getName());
private static final String s_name = "listniciranvpdevicenetworks";
@PlugService NiciraNvpElementService _niciraNvpElementService;
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@IdentityMapper(entityTableName="external_nicira_nvp_devices")
@Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.LONG, required = true, description="nicira nvp device ID")
private Long niciraNvpDeviceId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getNiciraNvpDeviceId() {
return niciraNvpDeviceId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
try {
List<? extends Network> networks = _niciraNvpElementService.listNiciraNvpDeviceNetworks(this);
ListResponse<NetworkResponse> response = new ListResponse<NetworkResponse>();
List<NetworkResponse> networkResponses = new ArrayList<NetworkResponse>();
if (networks != null && !networks.isEmpty()) {
for (Network network : networks) {
NetworkResponse networkResponse = _responseGenerator.createNetworkResponse(network);
networkResponses.add(networkResponse);
}
}
response.setResponses(networkResponses);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} catch (InvalidParameterValueException invalidParamExcp) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage());
} catch (CloudRuntimeException runtimeExcp) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage());
}
}
@Override
public String getCommandName() {
return s_name;
}
}

View File

@ -0,0 +1,90 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseCmd;
import com.cloud.api.BaseListCmd;
import com.cloud.api.IdentityMapper;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.PlugService;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.NiciraNvpDeviceResponse;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.NiciraNvpDeviceVO;
import com.cloud.network.element.NiciraNvpElementService;
import com.cloud.utils.exception.CloudRuntimeException;
@Implementation(responseObject=NiciraNvpDeviceResponse.class, description="Lists Nicira NVP devices")
public class ListNiciraNvpDevicesCmd extends BaseListCmd {
private static final Logger s_logger = Logger.getLogger(ListNiciraNvpDevicesCmd.class.getName());
private static final String s_name = "listniciranvpdevices";
@PlugService NiciraNvpElementService _niciraNvpElementService;
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@IdentityMapper(entityTableName="physical_network")
@Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID")
private Long physicalNetworkId;
@IdentityMapper(entityTableName="external_nicira_nvp_devices")
@Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.LONG, description="nicira nvp device ID")
private Long niciraNvpDeviceId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getNiciraNvpDeviceId() {
return niciraNvpDeviceId;
}
public Long getPhysicalNetworkId() {
return physicalNetworkId;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
try {
List<NiciraNvpDeviceVO> niciraDevices = _niciraNvpElementService.listNiciraNvpDevices(this);
ListResponse<NiciraNvpDeviceResponse> response = new ListResponse<NiciraNvpDeviceResponse>();
List<NiciraNvpDeviceResponse> niciraDevicesResponse = new ArrayList<NiciraNvpDeviceResponse>();
if (niciraDevices != null && !niciraDevices.isEmpty()) {
for (NiciraNvpDeviceVO niciraDeviceVO : niciraDevices) {
NiciraNvpDeviceResponse niciraDeviceResponse = _niciraNvpElementService.createNiciraNvpDeviceResponse(niciraDeviceVO);
niciraDevicesResponse.add(niciraDeviceResponse);
}
}
response.setResponses(niciraDevicesResponse);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} catch (InvalidParameterValueException invalidParamExcp) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, invalidParamExcp.getMessage());
} catch (CloudRuntimeException runtimeExcp) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, runtimeExcp.getMessage());
}
}
@Override
public String getCommandName() {
return s_name;
}
}

View File

@ -0,0 +1,37 @@
package com.cloud.api.response;
import com.cloud.api.ApiConstants;
import com.cloud.serializer.Param;
import com.cloud.utils.IdentityProxy;
import com.google.gson.annotations.SerializedName;
public class NiciraNvpDeviceResponse extends BaseResponse {
@SerializedName(ApiConstants.NICIRA_NVP_DEVICE_ID) @Param(description="device id of the Nicire Nvp")
private IdentityProxy id = new IdentityProxy("external_nicira_nvp_devices");
@SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network to which this Nirica Nvp belongs to")
private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network");
@SerializedName(ApiConstants.PROVIDER) @Param(description="name of the provider")
private String providerName;
@SerializedName(ApiConstants.NICIRA_NVP_DEVICE_NAME) @Param(description="device name")
private String deviceName;
public void setId(long nvpDeviceId) {
this.id.setValue(nvpDeviceId);
}
public void setPhysicalNetworkId(long physicalNetworkId) {
this.physicalNetworkId.setValue(physicalNetworkId);
}
public void setProviderName(String providerName) {
this.providerName = providerName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
}

View File

@ -0,0 +1,79 @@
package com.cloud.network;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="external_nicira_nvp_devices")
public class NiciraNvpDeviceVO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private long id;
@Column(name="uuid")
private String uuid;
@Column(name="host_id")
private long hostId;
@Column(name="physical_network_id")
private long physicalNetworkId;
@Column(name="provider_name")
private String providerName;
@Column(name="device_name")
private String deviceName;
public NiciraNvpDeviceVO() {
this.uuid = UUID.randomUUID().toString();
}
public NiciraNvpDeviceVO(long hostId, long physicalNetworkId,
String providerName, String deviceName) {
super();
this.hostId = hostId;
this.physicalNetworkId = physicalNetworkId;
this.providerName = providerName;
this.deviceName = deviceName;
this.uuid = UUID.randomUUID().toString();
}
public long getId() {
return id;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public long getPhysicalNetworkId() {
return physicalNetworkId;
}
public long getHostId() {
return hostId;
}
public String getProviderName() {
return providerName;
}
public String getDeviceName() {
return deviceName;
}
}

View File

@ -0,0 +1,65 @@
package com.cloud.network;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="nicira_nvp_nic_map")
public class NiciraNvpNicMappingVO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private long id;
@Column(name="logicalswitch")
private String logicalSwitchUuid;
@Column(name="logicalswitchport")
private String logicalSwitchPortUuid;
@Column(name="nic")
private String nicUuid;
public NiciraNvpNicMappingVO () {
}
public NiciraNvpNicMappingVO (String logicalSwitchUuid, String logicalSwitchPortUuid, String nicUuid) {
this.logicalSwitchUuid = logicalSwitchUuid;
this.logicalSwitchPortUuid = logicalSwitchPortUuid;
this.nicUuid = nicUuid;
}
public String getLogicalSwitchUuid() {
return logicalSwitchUuid;
}
public void setLogicalSwitchUuid(String logicalSwitchUuid) {
this.logicalSwitchUuid = logicalSwitchUuid;
}
public String getLogicalSwitchPortUuid() {
return logicalSwitchPortUuid;
}
public void setLogicalSwitchPortUuid(String logicalSwitchPortUuid) {
this.logicalSwitchPortUuid = logicalSwitchPortUuid;
}
public String getNicUuid() {
return nicUuid;
}
public void setNicUuid(String nicUuid) {
this.nicUuid = nicUuid;
}
public long getId() {
return id;
}
}

View File

@ -0,0 +1,16 @@
package com.cloud.network.dao;
import java.util.List;
import com.cloud.network.NiciraNvpDeviceVO;
import com.cloud.utils.db.GenericDao;
public interface NiciraNvpDao extends GenericDao<NiciraNvpDeviceVO, Long>{
/**
* list all the nicira nvp devices added in to this physical network
* @param physicalNetworkId physical Network Id
* @return list of NiciraNvpDeviceVO for this physical network.
*/
List<NiciraNvpDeviceVO> listByPhysicalNetwork(long physicalNetworkId);
}

View File

@ -0,0 +1,32 @@
package com.cloud.network.dao;
import java.util.List;
import javax.ejb.Local;
import com.cloud.network.NiciraNvpDeviceVO;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op;
@Local(value=NiciraNvpDao.class)
public class NiciraNvpDaoImpl extends GenericDaoBase<NiciraNvpDeviceVO, Long>
implements NiciraNvpDao {
protected final SearchBuilder<NiciraNvpDeviceVO> physicalNetworkIdSearch;
public NiciraNvpDaoImpl() {
physicalNetworkIdSearch = createSearchBuilder();
physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ);
physicalNetworkIdSearch.done();
}
@Override
public List<NiciraNvpDeviceVO> listByPhysicalNetwork(long physicalNetworkId) {
SearchCriteria<NiciraNvpDeviceVO> sc = physicalNetworkIdSearch.create();
sc.setParameters("physicalNetworkId", physicalNetworkId);
return search(sc, null);
}
}

View File

@ -0,0 +1,13 @@
package com.cloud.network.dao;
import com.cloud.network.NiciraNvpNicMappingVO;
import com.cloud.utils.db.GenericDao;
public interface NiciraNvpNicMappingDao extends GenericDao<NiciraNvpNicMappingVO, Long> {
/** find the mapping for a nic
* @param nicUuid the Uuid of a nic attached to a logical switch port
* @return NiciraNvpNicMapping for this nic uuid or null if it does not exist
*/
public NiciraNvpNicMappingVO findByNicUuid(String nicUuid);
}

View File

@ -0,0 +1,30 @@
package com.cloud.network.dao;
import javax.ejb.Local;
import com.cloud.network.NiciraNvpNicMappingVO;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op;
@Local(value=NiciraNvpNicMappingDao.class)
public class NiciraNvpNicMappingDaoImpl extends
GenericDaoBase<NiciraNvpNicMappingVO, Long> implements NiciraNvpNicMappingDao {
protected final SearchBuilder<NiciraNvpNicMappingVO> nicSearch;
public NiciraNvpNicMappingDaoImpl() {
nicSearch = createSearchBuilder();
nicSearch.and("nicUuid", nicSearch.entity().getNicUuid(), Op.EQ);
nicSearch.done();
}
@Override
public NiciraNvpNicMappingVO findByNicUuid(String nicUuid) {
SearchCriteria<NiciraNvpNicMappingVO> sc = nicSearch.create();
sc.setParameters("nicUuid", nicUuid);
return findOneBy(sc);
}
}

View File

@ -0,0 +1,502 @@
/** 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.element;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupNiciraNvpCommand;
import com.cloud.api.commands.AddNiciraNvpDeviceCmd;
import com.cloud.api.commands.DeleteNiciraNvpDeviceCmd;
import com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd;
import com.cloud.api.commands.ListNiciraNvpDevicesCmd;
import com.cloud.api.response.NiciraNvpDeviceResponse;
import com.cloud.deploy.DeployDestination;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.host.DetailVO;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.Network;
import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.NiciraNvpDeviceVO;
import com.cloud.network.NiciraNvpNicMappingVO;
import com.cloud.network.PhysicalNetworkServiceProvider;
import com.cloud.network.PhysicalNetworkVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NiciraNvpDao;
import com.cloud.network.dao.NiciraNvpNicMappingDao;
import com.cloud.network.dao.PhysicalNetworkDao;
import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
import com.cloud.network.guru.NiciraNvpGuestNetworkGuru;
import com.cloud.network.resource.NiciraNvpResource;
import com.cloud.offering.NetworkOffering;
import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceState;
import com.cloud.resource.ResourceStateAdapter;
import com.cloud.resource.ServerResource;
import com.cloud.resource.UnableDeleteHostException;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.NicProfile;
import com.cloud.vm.NicVO;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.NicDao;
@Local(value = NetworkElement.class)
public class NiciraNvpElement extends AdapterBase implements NetworkElement, NiciraNvpElementService, ResourceStateAdapter {
private static final Logger s_logger = Logger.getLogger(NiciraNvpElement.class);
private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
@Inject
NicDao _nicDao;
@Inject
ResourceManager _resourceMgr;
@Inject
PhysicalNetworkDao _physicalNetworkDao;
@Inject
PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao;
@Inject
NiciraNvpDao _niciraNvpDao;
@Inject
HostDetailsDao _hostDetailsDao;
@Inject
HostDao _hostDao;
@Inject
AgentManager _agentMgr;
@Inject
NiciraNvpNicMappingDao _niciraNvpNicMappingDao;
@Inject
NetworkDao _networkDao;
@Override
public Map<Service, Map<Capability, String>> getCapabilities() {
return capabilities;
}
@Override
public Provider getProvider() {
return Provider.NiciraNvp;
}
private boolean canHandle(Network network) {
if (network.getBroadcastDomainType() != BroadcastDomainType.Lswitch) {
return false;
}
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
super.configure(name, params);
_resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
return true;
}
@Override
public boolean implement(Network network, NetworkOffering offering,
DeployDestination dest, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
if (!canHandle(network)) {
return false;
}
return true;
}
@Override
public boolean prepare(Network network, NicProfile nic,
VirtualMachineProfile<? extends VirtualMachine> vm,
DeployDestination dest, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
if (!canHandle(network)) {
return false;
}
if (network.getBroadcastUri() == null) {
s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid");
return false;
}
NicVO nicVO = _nicDao.findById(nic.getId());
List<NiciraNvpDeviceVO> devices = _niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
if (devices.isEmpty()) {
s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
return false;
}
NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId());
CreateLogicalSwitchPortCommand cmd = new CreateLogicalSwitchPortCommand(network.getBroadcastUri().getSchemeSpecificPart(), nicVO.getUuid(),
context.getDomain().getName() + "-" + context.getAccount().getAccountName(), nic.getName());
CreateLogicalSwitchPortAnswer answer = (CreateLogicalSwitchPortAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd);
if (answer == null || !answer.getResult()) {
s_logger.error ("CreateLogicalSwitchPortCommand failed");
return false;
}
NiciraNvpNicMappingVO nicMap = new NiciraNvpNicMappingVO(network.getBroadcastUri().getSchemeSpecificPart(), answer.getLogicalSwitchPortUuid(), nicVO.getUuid());
_niciraNvpNicMappingDao.persist(nicMap);
return true;
}
@Override
public boolean release(Network network, NicProfile nic,
VirtualMachineProfile<? extends VirtualMachine> vm,
ReservationContext context) throws ConcurrentOperationException,
ResourceUnavailableException {
if (!canHandle(network)) {
return false;
}
if (network.getBroadcastUri() == null) {
s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid");
return false;
}
NicVO nicVO = _nicDao.findById(nic.getId());
List<NiciraNvpDeviceVO> devices = _niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
if (devices.isEmpty()) {
s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
return false;
}
NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId());
NiciraNvpNicMappingVO nicMap = _niciraNvpNicMappingDao.findByNicUuid(nicVO.getUuid());
if (nicMap == null) {
s_logger.error("No mapping for nic " + nic.getName());
return false;
}
DeleteLogicalSwitchPortCommand cmd = new DeleteLogicalSwitchPortCommand(nicMap.getLogicalSwitchUuid(), nicMap.getLogicalSwitchPortUuid());
DeleteLogicalSwitchPortAnswer answer = (DeleteLogicalSwitchPortAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd);
if (answer == null || !answer.getResult()) {
s_logger.error ("DeleteLogicalSwitchPortCommand failed");
return false;
}
_niciraNvpNicMappingDao.remove(nicMap.getId());
return true;
}
@Override
public boolean shutdown(Network network, ReservationContext context,
boolean cleanup) throws ConcurrentOperationException,
ResourceUnavailableException {
if (!canHandle(network)) {
return false;
}
return true;
}
@Override
public boolean destroy(Network network)
throws ConcurrentOperationException, ResourceUnavailableException {
if (!canHandle(network)) {
return false;
}
return true;
}
@Override
public boolean isReady(PhysicalNetworkServiceProvider provider) {
return true;
}
@Override
public boolean shutdownProviderInstances(
PhysicalNetworkServiceProvider provider, ReservationContext context)
throws ConcurrentOperationException, ResourceUnavailableException {
// Nothing to do here.
return true;
}
@Override
public boolean canEnableIndividualServices() {
return false;
}
@Override
public boolean verifyServicesCombination(List<String> services) {
return true;
}
private static Map<Service, Map<Capability, String>> setCapabilities() {
Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
capabilities.put(Service.Connectivity, null);
return capabilities;
}
@Override
public String getPropertiesFile() {
return "nicira-nvp_commands.properties";
}
@Override
@DB
public NiciraNvpDeviceVO addNiciraNvpDevice(AddNiciraNvpDeviceCmd cmd) {
ServerResource resource = new NiciraNvpResource();
String deviceName = Network.Provider.NiciraNvp.getName();
NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName);
Long physicalNetworkId = cmd.getPhysicalNetworkId();
NiciraNvpDeviceVO niciraNvpDevice = null;
PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
}
long zoneId = physicalNetwork.getDataCenterId();
PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder());
if (ntwkSvcProvider == null) {
throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() +
" is not enabled in the physical network: " + physicalNetworkId + "to add this device");
} else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() +
" is in shutdown state in the physical network: " + physicalNetworkId + "to add this device");
}
if (_niciraNvpDao.listByPhysicalNetwork(physicalNetworkId).size() != 0) {
throw new CloudRuntimeException("A NiciraNvp device is already configured on this physical network");
}
Map<String, String> params = new HashMap<String,String>();
params.put("guid", UUID.randomUUID().toString());
params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId()));
params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId()));
params.put("name", "Nicira Controller - " + cmd.getHost());
params.put("ip", cmd.getHost());
params.put("adminuser", cmd.getUsername());
params.put("adminpass", cmd.getPassword());
params.put("transportzoneuuid", cmd.getTransportzoneUuid());
params.put("transportzoneisotype", physicalNetwork.getIsolationMethods().get(0).toLowerCase()); // FIXME What to do with multiple isolation types
Map<String, Object> hostdetails = new HashMap<String,Object>();
hostdetails.putAll(params);
Transaction txn = Transaction.currentTxn();
try {
resource.configure(cmd.getHost(), hostdetails);
Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params);
if (host != null) {
txn.start();
niciraNvpDevice = new NiciraNvpDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName);
_niciraNvpDao.persist(niciraNvpDevice);
DetailVO detail = new DetailVO(host.getId(), "niciranvpdeviceid", String.valueOf(niciraNvpDevice.getId()));
_hostDetailsDao.persist(detail);
txn.commit();
return niciraNvpDevice;
} else {
throw new CloudRuntimeException("Failed to add Nicira Nvp Device due to internal error.");
}
} catch (ConfigurationException e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
@Override
public NiciraNvpDeviceResponse createNiciraNvpDeviceResponse(
NiciraNvpDeviceVO niciraNvpDeviceVO) {
NiciraNvpDeviceResponse response = new NiciraNvpDeviceResponse();
response.setDeviceName(niciraNvpDeviceVO.getDeviceName());
response.setPhysicalNetworkId(niciraNvpDeviceVO.getPhysicalNetworkId());
response.setId(niciraNvpDeviceVO.getId());
response.setProviderName(niciraNvpDeviceVO.getProviderName());
return response;
}
@Override
public boolean deleteNiciraNvpDevice(DeleteNiciraNvpDeviceCmd cmd) {
Long niciraDeviceId = cmd.getNiciraNvpDeviceId();
NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao.findById(niciraDeviceId);
if (niciraNvpDevice == null) {
throw new InvalidParameterValueException("Could not find a nicira device with id " + niciraDeviceId);
}
// Find the physical network we work for
Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId();
PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork != null) {
// Lets see if there are networks that use us
// Find the nicira networks on this physical network
List<NetworkVO> networkList = _networkDao.listByPhysicalNetwork(physicalNetworkId);
// Networks with broadcast type lswitch are ours
for (NetworkVO network : networkList) {
if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) {
if ((network.getState() != Network.State.Shutdown) && (network.getState() != Network.State.Destroy)) {
throw new CloudRuntimeException("This Nicira Nvp device can not be deleted as there are one or more logical networks provisioned by cloudstack.");
}
}
}
}
HostVO niciraHost = _hostDao.findById(niciraNvpDevice.getHostId());
Long hostId = niciraHost.getId();
niciraHost.setResourceState(ResourceState.Maintenance);
_hostDao.update(hostId, niciraHost);
_resourceMgr.deleteHost(hostId, false, false);
_niciraNvpDao.remove(niciraDeviceId);
return true;
}
@Override
public List<NiciraNvpDeviceVO> listNiciraNvpDevices(ListNiciraNvpDevicesCmd cmd) {
Long physicalNetworkId = cmd.getPhysicalNetworkId();
Long niciraNvpDeviceId = cmd.getNiciraNvpDeviceId();
List<NiciraNvpDeviceVO> responseList = new ArrayList<NiciraNvpDeviceVO>();
if (physicalNetworkId == null && niciraNvpDeviceId == null) {
throw new InvalidParameterValueException("Either physical network Id or nicira device Id must be specified");
}
if (niciraNvpDeviceId != null) {
NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao.findById(niciraNvpDeviceId);
if (niciraNvpDevice == null) {
throw new InvalidParameterValueException("Could not find Nicira Nvp device with id: " + niciraNvpDevice);
}
responseList.add(niciraNvpDevice);
}
else {
PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId);
}
responseList = _niciraNvpDao.listByPhysicalNetwork(physicalNetworkId);
}
return responseList;
}
@Override
public List<? extends Network> listNiciraNvpDeviceNetworks(ListNiciraNvpDeviceNetworksCmd cmd) {
Long niciraDeviceId = cmd.getNiciraNvpDeviceId();
NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao.findById(niciraDeviceId);
if (niciraNvpDevice == null) {
throw new InvalidParameterValueException("Could not find a nicira device with id " + niciraDeviceId);
}
// Find the physical network we work for
Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId();
PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
// No such physical network, so no provisioned networks
return Collections.emptyList();
}
// Find the nicira networks on this physical network
List<NetworkVO> networkList = _networkDao.listByPhysicalNetwork(physicalNetworkId);
// Networks with broadcast type lswitch are ours
List<NetworkVO> responseList = new ArrayList<NetworkVO>();
for (NetworkVO network : networkList) {
if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) {
responseList.add(network);
}
}
return responseList;
}
@Override
public HostVO createHostVOForConnectedAgent(HostVO host,
StartupCommand[] cmd) {
// TODO Auto-generated method stub
return null;
}
@Override
public HostVO createHostVOForDirectConnectAgent(HostVO host,
StartupCommand[] startup, ServerResource resource,
Map<String, String> details, List<String> hostTags) {
if (!(startup[0] instanceof StartupNiciraNvpCommand)) {
return null;
}
host.setType(Host.Type.L2Networking);
return host;
}
@Override
public DeleteHostAnswer deleteHost(HostVO host, boolean isForced,
boolean isForceDeleteStorage) throws UnableDeleteHostException {
if (!(host.getType() == Host.Type.L2Networking)) {
return null;
}
return new DeleteHostAnswer(true);
}
}

View File

@ -0,0 +1,28 @@
package com.cloud.network.element;
import java.util.List;
import com.cloud.api.commands.AddNiciraNvpDeviceCmd;
import com.cloud.api.commands.DeleteNiciraNvpDeviceCmd;
import com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd;
import com.cloud.api.commands.ListNiciraNvpDevicesCmd;
import com.cloud.api.response.NiciraNvpDeviceResponse;
import com.cloud.network.Network;
import com.cloud.network.NiciraNvpDeviceVO;
import com.cloud.utils.component.PluggableService;
public interface NiciraNvpElementService extends PluggableService {
public NiciraNvpDeviceVO addNiciraNvpDevice(AddNiciraNvpDeviceCmd cmd);
public NiciraNvpDeviceResponse createNiciraNvpDeviceResponse(
NiciraNvpDeviceVO niciraDeviceVO);
boolean deleteNiciraNvpDevice(DeleteNiciraNvpDeviceCmd cmd);
List<? extends Network> listNiciraNvpDeviceNetworks(
ListNiciraNvpDeviceNetworksCmd cmd);
List<NiciraNvpDeviceVO> listNiciraNvpDevices(ListNiciraNvpDevicesCmd cmd);
}

View File

@ -0,0 +1,257 @@
/** 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.guru;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.CreateLogicalSwitchAnswer;
import com.cloud.agent.api.CreateLogicalSwitchCommand;
import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
import com.cloud.agent.api.DeleteLogicalSwitchCommand;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.Network;
import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkProfile;
import com.cloud.network.NetworkVO;
import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.State;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.NiciraNvpDeviceVO;
import com.cloud.network.PhysicalNetwork;
import com.cloud.network.PhysicalNetwork.IsolationMethod;
import com.cloud.network.PhysicalNetworkVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NiciraNvpDao;
import com.cloud.network.dao.PhysicalNetworkDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.resource.ResourceManager;
import com.cloud.user.Account;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.component.Inject;
import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
@Local(value=NetworkGuru.class)
public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru {
private static final Logger s_logger = Logger.getLogger(NiciraNvpGuestNetworkGuru.class);
@Inject
NetworkManager _externalNetworkManager;
@Inject
NetworkManager _networkMgr;
@Inject
NetworkDao _networkDao;
@Inject
DataCenterDao _zoneDao;
@Inject
PhysicalNetworkDao _physicalNetworkDao;
@Inject
AccountDao _accountDao;
@Inject
NiciraNvpDao _niciraNvpDao;
@Inject
HostDao _hostDao;
@Inject
ResourceManager _resourceMgr;
@Inject
AgentManager _agentMgr;
@Inject
HostDetailsDao _hostDetailsDao;
public NiciraNvpGuestNetworkGuru() {
super();
_isolationMethods = new IsolationMethod[] { IsolationMethod.STT };
}
@Override
protected boolean canHandle(NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) {
// This guru handles only Guest Isolated network that supports Source nat service
if (networkType == NetworkType.Advanced
&& isMyTrafficType(offering.getTrafficType())
&& offering.getGuestType() == Network.GuestType.Isolated
&& isMyIsolationMethod(physicalNetwork)) {
return true;
} else {
s_logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced);
return false;
}
}
@Override
public Network design(NetworkOffering offering, DeploymentPlan plan,
Network userSpecified, Account owner) {
// Check of the isolation type of the related physical network is STT
PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId());
if (physnet == null || physnet.getIsolationMethods() == null || !physnet.getIsolationMethods().contains("STT")) {
s_logger.debug("Refusing to design this network, the physical isolation type is not STT");
return null;
}
List<NiciraNvpDeviceVO> devices = _niciraNvpDao.listByPhysicalNetwork(physnet.getId());
if (devices.isEmpty()) {
s_logger.error("No NiciraNvp Controller on physical network " + physnet.getName());
return null;
}
s_logger.debug("Nicira Nvp " + devices.get(0).getUuid() + " found on physical network " + physnet.getId());
s_logger.debug("Physical isolation type is STT, asking GuestNetworkGuru to design this network");
NetworkVO networkObject = (NetworkVO) super.design(offering, plan, userSpecified, owner);
if (networkObject == null) {
return null;
}
// Override the broadcast domain type
networkObject.setBroadcastDomainType(BroadcastDomainType.Lswitch);
return networkObject;
}
@Override
public Network implement(Network network, NetworkOffering offering,
DeployDestination dest, ReservationContext context)
throws InsufficientVirtualNetworkCapcityException {
assert (network.getState() == State.Implementing) : "Why are we implementing " + network;
long dcId = dest.getDataCenter().getId();
//get physical network id
long physicalNetworkId = _networkMgr.findPhysicalNetworkId(dcId, offering.getTags(), offering.getTrafficType());
NetworkVO implemented = new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), State.Allocated,
network.getDataCenterId(), physicalNetworkId);
if (network.getGateway() != null) {
implemented.setGateway(network.getGateway());
}
if (network.getCidr() != null) {
implemented.setCidr(network.getCidr());
}
// Name is either the given name or the uuid
String name = implemented.getName();
if (name == null || name.isEmpty()) {
name = implemented.getUuid();
}
if (name.length() > 40 ) {
name = name.substring(0, 39); // max length 40
}
List<NiciraNvpDeviceVO> devices = _niciraNvpDao.listByPhysicalNetwork(physicalNetworkId);
if (devices.isEmpty()) {
s_logger.error("No NiciraNvp Controller on physical network " + physicalNetworkId);
return null;
}
NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId());
_hostDao.loadDetails(niciraNvpHost);
String transportzoneuuid = niciraNvpHost.getDetail("transportzoneuuid");
String transportzoneisotype = niciraNvpHost.getDetail("transportzoneisotype");
CreateLogicalSwitchCommand cmd = new CreateLogicalSwitchCommand(transportzoneuuid, transportzoneisotype, network.getName(),
context.getDomain().getName() + "-" + context.getAccount().getAccountName());
CreateLogicalSwitchAnswer answer = (CreateLogicalSwitchAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd);
if (answer == null || !answer.getResult()) {
s_logger.error ("CreateLogicalSwitchCommand failed");
return null;
}
try {
implemented.setBroadcastUri(new URI("lswitch", answer.getLogicalSwitchUuid(), null));
implemented.setBroadcastDomainType(BroadcastDomainType.Lswitch);
s_logger.info("Implemented OK, network linked to = " + implemented.getBroadcastUri().toString());
} catch (URISyntaxException e) {
s_logger.error("Unable to store logical switch id in broadcast uri, uuid = " + implemented.getUuid(), e);
}
return implemented;
}
@Override
public void reserve(NicProfile nic, Network network,
VirtualMachineProfile<? extends VirtualMachine> vm,
DeployDestination dest, ReservationContext context)
throws InsufficientVirtualNetworkCapcityException,
InsufficientAddressCapacityException {
// TODO Auto-generated method stub
super.reserve(nic, network, vm, dest, context);
}
@Override
public boolean release(NicProfile nic,
VirtualMachineProfile<? extends VirtualMachine> vm,
String reservationId) {
// TODO Auto-generated method stub
return super.release(nic, vm, reservationId);
}
@Override
public void shutdown(NetworkProfile profile, NetworkOffering offering) {
NetworkVO networkObject = _networkDao.findById(profile.getId());
if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Lswitch ||
networkObject.getBroadcastUri() == null) {
s_logger.warn("BroadcastUri is empty or incorrect for guestnetwork " + networkObject.getDisplayText());
return;
}
List<NiciraNvpDeviceVO> devices = _niciraNvpDao.listByPhysicalNetwork(networkObject.getPhysicalNetworkId());
if (devices.isEmpty()) {
s_logger.error("No NiciraNvp Controller on physical network " + networkObject.getPhysicalNetworkId());
return;
}
NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId());
DeleteLogicalSwitchCommand cmd = new DeleteLogicalSwitchCommand(networkObject.getBroadcastUri().getSchemeSpecificPart());
DeleteLogicalSwitchAnswer answer = (DeleteLogicalSwitchAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd);
if (answer == null || !answer.getResult()) {
s_logger.error ("DeleteLogicalSwitchCommand failed");
}
super.shutdown(profile, offering);
}
@Override
public boolean trash(Network network, NetworkOffering offering,
Account owner) {
return super.trash(network, offering, owner);
}
}

View File

@ -0,0 +1,22 @@
/** 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 abstract class Attachment {
}

View File

@ -0,0 +1,99 @@
/** 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.util.List;
public class LogicalSwitch {
private String display_name;
private boolean port_isolation_enabled;
private List<NiciraNvpTag> tags;
private List<TransportZoneBinding> transport_zones;
private String type;
private String uuid;
private String _href;
//private RequestQueryParameters _query;
//private LogicalSwitchRelations _relations;
private String _schema;
public String getDisplay_name() {
return display_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public boolean isPort_isolation_enabled() {
return port_isolation_enabled;
}
public void setPort_isolation_enabled(boolean port_isolation_enabled) {
this.port_isolation_enabled = port_isolation_enabled;
}
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;
}
public String get_href() {
return _href;
}
public void set_href(String _href) {
this._href = _href;
}
public String get_schema() {
return _schema;
}
public void set_schema(String _schema) {
this._schema = _schema;
}
public List<NiciraNvpTag> getTags() {
return tags;
}
public void setTags(List<NiciraNvpTag> tags) {
this.tags = tags;
}
public List<TransportZoneBinding> getTransport_zones() {
return transport_zones;
}
public void setTransport_zones(List<TransportZoneBinding> transport_zones) {
this.transport_zones = transport_zones;
}
}

View File

@ -0,0 +1,118 @@
/** 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.util.List;
public class LogicalSwitchPort {
private String display_name;
private List<NiciraNvpTag> tags;
private Integer portno;
private boolean admin_status_enabled;
//private List<AddressPairs> allowed_address_pairs;
private String queue_uuid;
private List<String> security_profiles;
private List<String> mirror_targets;
private String type;
private String uuid;
public LogicalSwitchPort() {
super();
}
public LogicalSwitchPort(String display_name, List<NiciraNvpTag> tags,
boolean admin_status_enabled) {
super();
this.display_name = display_name;
this.tags = tags;
this.admin_status_enabled = admin_status_enabled;
}
public String getDisplay_name() {
return display_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public List<NiciraNvpTag> getTags() {
return tags;
}
public void setTags(List<NiciraNvpTag> tags) {
this.tags = tags;
}
public Integer getPortno() {
return portno;
}
public void setPortno(Integer portno) {
this.portno = portno;
}
public boolean isAdmin_status_enabled() {
return admin_status_enabled;
}
public void setAdmin_status_enabled(boolean admin_status_enabled) {
this.admin_status_enabled = admin_status_enabled;
}
public String getQueue_uuid() {
return queue_uuid;
}
public void setQueue_uuid(String queue_uuid) {
this.queue_uuid = queue_uuid;
}
public List<String> getSecurity_profiles() {
return security_profiles;
}
public void setSecurity_profiles(List<String> security_profiles) {
this.security_profiles = security_profiles;
}
public List<String> getMirror_targets() {
return mirror_targets;
}
public void setMirror_targets(List<String> mirror_targets) {
this.mirror_targets = mirror_targets;
}
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

@ -0,0 +1,413 @@
/** 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.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.Collections;
import java.util.HashMap;
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.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
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.Gson;
import com.google.gson.reflect.TypeToken;
public class NiciraNvpApi {
private static final Logger s_logger = Logger.getLogger(NiciraNvpApi.class);
private String _name;
private String _host;
private String _adminuser;
private String _adminpass;
private HttpClient _client;
public NiciraNvpApi(String host, String adminuser, String adminpass) throws NiciraNvpApiException {
this._host = host;
this._adminpass = adminpass;
this._adminuser = adminuser;
if (_host == null || _adminpass == null || _adminuser == null) {
throw new NiciraNvpApiException("host, adminuser and adminpass may not be null");
}
_client = new HttpClient( );
_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(), 443));
} catch (IOException e) {
s_logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e);
}
}
/**
* Logs into the Nicira API. 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.
*
*/
private void login() throws NiciraNvpApiException {
String url;
try {
url = new URL("https", _host, "/ws.v1/login").toString();
} catch (MalformedURLException e) {
s_logger.error("Unable to build Nicira API URL", e);
throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
}
PostMethod pm = new PostMethod(url);
pm.addParameter("username", _adminuser);
pm.addParameter("password", _adminpass);
try {
_client.executeMethod(pm);
} catch (HttpException e) {
throw new NiciraNvpApiException("Nicira NVP API login failed ", e);
} catch (IOException e) {
throw new NiciraNvpApiException("Nicira NVP API login failed ", e);
}
if (pm.getStatusCode() != HttpStatus.SC_OK) {
s_logger.error("Nicira NVP API login failed : " + pm.getStatusText());
throw new NiciraNvpApiException("Nicira NVP API login failed " + pm.getStatusText());
}
// Success; the cookie required for login is kept in _client
}
public LogicalSwitch createLogicalSwitch(LogicalSwitch logicalSwitch) throws NiciraNvpApiException {
String uri = "/ws.v1/lswitch";
LogicalSwitch createdLogicalSwitch = executeCreateObject(logicalSwitch, new TypeToken<LogicalSwitch>(){}.getType(), uri, Collections.<String,String>emptyMap());
return createdLogicalSwitch;
}
public void deleteLogicalSwitch(String uuid) throws NiciraNvpApiException {
String uri = "/ws.v1/lswitch/" + uuid;
executeDeleteObject(uri);
}
public LogicalSwitchPort createLogicalSwitchPort(String logicalSwitchUuid, LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException {
String uri = "/ws.v1/lswitch/" + logicalSwitchUuid + "/lport";
LogicalSwitchPort createdLogicalSwitchPort = executeCreateObject(logicalSwitchPort, new TypeToken<LogicalSwitchPort>(){}.getType(), uri, Collections.<String,String>emptyMap());;
return createdLogicalSwitchPort;
}
public void modifyLogicalSwitchPortAttachment(String logicalSwitchUuid, String logicalSwitchPortUuid, Attachment attachment) throws NiciraNvpApiException {
String uri = "/ws.v1/lswitch/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid + "/attachment";
executeUpdateObject(attachment, uri, Collections.<String,String>emptyMap());
}
public void deleteLogicalSwitchPort(String logicalSwitchUuid, String logicalSwitchPortUuid) throws NiciraNvpApiException {
String uri = "/ws.v1/lswitch/" + logicalSwitchUuid + "/lport/" + logicalSwitchPortUuid;
executeDeleteObject(uri);
}
public String findLogicalSwitchPortUuidByVifAttachmentUuid(String logicalSwitchUuid, String vifAttachmentUuid) throws NiciraNvpApiException {
String uri = "/ws.v1/lswitch/" + logicalSwitchUuid + "/lport";
Map<String,String> params = new HashMap<String,String>();
params.put("attachment_vif_uuid", vifAttachmentUuid);
params.put("fields", "uuid");
NiciraNvpList<LogicalSwitchPort> lspl = executeRetrieveObject(new TypeToken<NiciraNvpList<LogicalSwitchPort>>(){}.getType(), uri, params);
if (lspl == null || lspl.getResult_count() != 1) {
throw new NiciraNvpApiException("Unexpected response from API");
}
LogicalSwitchPort lsp = lspl.getResults().get(0);
return lsp.getUuid();
}
private <T> void executeUpdateObject(T newObject, String uri, Map<String,String> parameters) throws NiciraNvpApiException {
String url;
try {
url = new URL("https", _host, uri).toString();
} catch (MalformedURLException e) {
s_logger.error("Unable to build Nicira API URL", e);
throw new NiciraNvpApiException("Connection to NVP Failed");
}
Gson gson = new Gson();
PutMethod pm = new PutMethod(url);
pm.setRequestHeader("Content-Type", "application/json");
try {
pm.setRequestEntity(new StringRequestEntity(
gson.toJson(newObject),"application/json", null));
} catch (UnsupportedEncodingException e) {
throw new NiciraNvpApiException("Failed to encode json request body", e);
}
executeMethod(pm);
if (pm.getStatusCode() != HttpStatus.SC_OK) {
String errorMessage = responseToErrorMessage(pm);
s_logger.error("Failed to update object : " + errorMessage);
throw new NiciraNvpApiException("Failed to update object : " + errorMessage);
}
}
private <T> T executeCreateObject(T newObject, Type returnObjectType, String uri, Map<String,String> parameters) throws NiciraNvpApiException {
String url;
try {
url = new URL("https", _host, uri).toString();
} catch (MalformedURLException e) {
s_logger.error("Unable to build Nicira API URL", e);
throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
}
Gson gson = new Gson();
PostMethod pm = new PostMethod(url);
pm.setRequestHeader("Content-Type", "application/json");
try {
pm.setRequestEntity(new StringRequestEntity(
gson.toJson(newObject),"application/json", null));
} catch (UnsupportedEncodingException e) {
throw new NiciraNvpApiException("Failed to encode json request body", e);
}
executeMethod(pm);
if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
String errorMessage = responseToErrorMessage(pm);
s_logger.error("Failed to create object : " + errorMessage);
throw new NiciraNvpApiException("Failed to create object : " + errorMessage);
}
T result;
try {
result = gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
} catch (IOException e) {
throw new NiciraNvpApiException("Failed to decode json response body", e);
}
return result;
}
private void executeDeleteObject(String uri) throws NiciraNvpApiException {
String url;
try {
url = new URL("https", _host, uri).toString();
} catch (MalformedURLException e) {
s_logger.error("Unable to build Nicira API URL", e);
throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
}
DeleteMethod dm = new DeleteMethod(url);
dm.setRequestHeader("Content-Type", "application/json");
executeMethod(dm);
if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
String errorMessage = responseToErrorMessage(dm);
s_logger.error("Failed to delete object : " + errorMessage);
throw new NiciraNvpApiException("Failed to delete object : " + errorMessage);
}
}
private <T> T executeRetrieveObject(Type returnObjectType, String uri, Map<String,String> parameters) throws NiciraNvpApiException {
String url;
try {
url = new URL("https", _host, uri).toString();
} catch (MalformedURLException e) {
s_logger.error("Unable to build Nicira API URL", e);
throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
}
GetMethod gm = new GetMethod(url);
gm.setRequestHeader("Content-Type", "application/json");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
for (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) {
String errorMessage = responseToErrorMessage(gm);
s_logger.error("Failed to retrieve object : " + errorMessage);
throw new NiciraNvpApiException("Failed to retrieve object : " + errorMessage);
}
Gson gson = new Gson();
T returnValue;
try {
returnValue = gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
} catch (IOException e) {
s_logger.error("IOException while retrieving response body",e);
throw new NiciraNvpApiException(e);
}
return returnValue;
}
private void executeMethod(HttpMethodBase method) throws NiciraNvpApiException {
try {
_client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
// login and try again
login();
_client.executeMethod(method);
}
} catch (HttpException e) {
s_logger.error("HttpException caught while trying to connect to the Nicira NVP Controller", e);
throw new NiciraNvpApiException("API call to Nicira NVP Controller Failed", e);
} catch (IOException e) {
s_logger.error("IOException caught while trying to connect to the Nicira NVP Controller", e);
throw new NiciraNvpApiException("API call to Nicira NVP Controller Failed", e);
}
}
private String responseToErrorMessage(HttpMethodBase method) {
assert method.isRequestSent() : "no use getting an error message unless the request is sent";
if ("text/html".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(1024);
} catch (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
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// Trust always
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// Trust always
}
}
};
try {
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
ssf = sc.getSocketFactory();
} catch (KeyManagementException e) {
throw new IOException(e);
} catch (NoSuchAlgorithmException e) {
throw new IOException(e);
}
}
@Override
public Socket createSocket(String host, int port) throws IOException,
UnknownHostException {
return ssf.createSocket(host, port);
}
@Override
public Socket createSocket(String address, int port, InetAddress localAddress,
int localPort) throws IOException, UnknownHostException {
return ssf.createSocket(address, port, localAddress, localPort);
}
@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return ssf.createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket(String host, int port, InetAddress localAddress,
int localPort, HttpConnectionParams params) throws IOException,
UnknownHostException, ConnectTimeoutException {
int timeout = params.getConnectionTimeout();
if (timeout == 0) {
return createSocket(host, port, localAddress, localPort);
}
else {
Socket s = ssf.createSocket();
s.bind(new InetSocketAddress(localAddress, localPort));
s.connect(new InetSocketAddress(host, port), timeout);
return s;
}
}
}
}

View File

@ -0,0 +1,20 @@
package com.cloud.network.nicira;
public class NiciraNvpApiException extends Exception {
public NiciraNvpApiException() {
}
public NiciraNvpApiException(String message) {
super(message);
}
public NiciraNvpApiException(Throwable cause) {
super(cause);
}
public NiciraNvpApiException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,25 @@
package com.cloud.network.nicira;
import java.util.List;
public class NiciraNvpList<T> {
private List<T> results;
private int result_count;
public List<T> getResults() {
return results;
}
public void setResults(List<T> results) {
this.results = results;
}
public int getResult_count() {
return result_count;
}
public void setResult_count(int result_count) {
this.result_count = result_count;
}
}

View File

@ -0,0 +1,47 @@
/** 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 NiciraNvpTag {
private String scope;
private String tag;
public NiciraNvpTag() {}
public NiciraNvpTag(String scope, String tag) {
this.scope = scope;
this.tag = tag;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}

View File

@ -0,0 +1,47 @@
/** 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 TransportZoneBinding {
private String zone_uuid;
private String transport_type;
public TransportZoneBinding() {}
public TransportZoneBinding(String zone_uuid, String transport_type) {
this.zone_uuid = zone_uuid;
this.transport_type = transport_type;
}
public String getZone_uuid() {
return zone_uuid;
}
public void setZone_uuid(String zone_uuid) {
this.zone_uuid = zone_uuid;
}
public String getTransport_type() {
return transport_type;
}
public void setTransport_type(String transport_type) {
this.transport_type = transport_type;
}
}

View File

@ -0,0 +1,43 @@
/** 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 VifAttachment extends Attachment {
private final String type = "VifAttachment";
private String vif_uuid;
public VifAttachment() {
}
public VifAttachment(String vifUuid) {
this.vif_uuid = vifUuid;
}
public String getVif_uuid() {
return vif_uuid;
}
public void setVif_uuid(String vif_uuid) {
this.vif_uuid = vif_uuid;
}
public String getType() {
return type;
}
}

View File

@ -0,0 +1,240 @@
package com.cloud.network.resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.IAgentControl;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.CreateLogicalSwitchAnswer;
import com.cloud.agent.api.CreateLogicalSwitchCommand;
import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
import com.cloud.agent.api.DeleteLogicalSwitchCommand;
import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
import com.cloud.agent.api.MaintainAnswer;
import com.cloud.agent.api.MaintainCommand;
import com.cloud.agent.api.PingCommand;
import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupNiciraNvpCommand;
import com.cloud.host.Host;
import com.cloud.host.Host.Type;
import com.cloud.network.nicira.LogicalSwitch;
import com.cloud.network.nicira.LogicalSwitchPort;
import com.cloud.network.nicira.NiciraNvpApi;
import com.cloud.network.nicira.NiciraNvpApiException;
import com.cloud.network.nicira.NiciraNvpTag;
import com.cloud.network.nicira.TransportZoneBinding;
import com.cloud.network.nicira.VifAttachment;
import com.cloud.resource.ServerResource;
public class NiciraNvpResource implements ServerResource {
private static final Logger s_logger = Logger.getLogger(NiciraNvpResource.class);
private String _name;
private String _ip;
private String _adminuser;
private String _adminpass;
private String _guid;
private String _zoneId;
private NiciraNvpApi _niciraNvpApi;
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
_name = (String) params.get("name");
if (_name == null) {
throw new ConfigurationException("Unable to find name");
}
_ip = (String) params.get("ip");
if (_ip == null) {
throw new ConfigurationException("Unable to find IP");
}
_adminuser = (String) params.get("adminuser");
if (_adminuser == null) {
throw new ConfigurationException("Unable to find admin username");
}
_adminpass = (String) params.get("adminpass");
if (_adminpass == null) {
throw new ConfigurationException("Unable to find admin password");
}
_guid = (String)params.get("guid");
if (_guid == null) {
throw new ConfigurationException("Unable to find the guid");
}
_zoneId = (String) params.get("zoneId");
if (_zoneId == null) {
throw new ConfigurationException("Unable to find zone");
}
try {
_niciraNvpApi = new NiciraNvpApi(_ip, _adminuser, _adminpass);
} catch (NiciraNvpApiException e) {
throw new ConfigurationException(e.getMessage());
}
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public Type getType() {
// Think up a better name for this Type?
return Host.Type.L2Networking;
}
@Override
public StartupCommand[] initialize() {
StartupNiciraNvpCommand sc = new StartupNiciraNvpCommand();
sc.setGuid(_guid);
sc.setName(_name);
sc.setDataCenter(_zoneId);
sc.setPod("");
sc.setPrivateIpAddress("");
sc.setStorageIpAddress("");
sc.setVersion("");
return new StartupCommand[] { sc };
}
@Override
public PingCommand getCurrentStatus(long id) {
return new PingCommand(Host.Type.L2Networking, id);
}
@Override
public Answer executeRequest(Command cmd) {
if (cmd instanceof ReadyCommand) {
return executeRequest((ReadyCommand) cmd);
}
else if (cmd instanceof MaintainCommand) {
return executeRequest((MaintainCommand)cmd);
}
else if (cmd instanceof CreateLogicalSwitchCommand) {
return executeRequest((CreateLogicalSwitchCommand)cmd);
}
else if (cmd instanceof DeleteLogicalSwitchCommand) {
return executeRequest((DeleteLogicalSwitchCommand) cmd);
}
else if (cmd instanceof CreateLogicalSwitchPortCommand) {
return executeRequest((CreateLogicalSwitchPortCommand) cmd);
}
else if (cmd instanceof DeleteLogicalSwitchPortCommand) {
return executeRequest((DeleteLogicalSwitchPortCommand) cmd);
}
s_logger.debug("Received unsupported command " + cmd.toString());
return Answer.createUnsupportedCommandAnswer(cmd);
}
@Override
public void disconnected() {
}
@Override
public IAgentControl getAgentControl() {
return null;
}
@Override
public void setAgentControl(IAgentControl agentControl) {
}
private Answer executeRequest(CreateLogicalSwitchCommand cmd) {
LogicalSwitch logicalSwitch = new LogicalSwitch();
logicalSwitch.setDisplay_name("lswitch-" + cmd.getOwnerName());
logicalSwitch.setPort_isolation_enabled(false);
// Set transport binding
List<TransportZoneBinding> ltzb = new ArrayList<TransportZoneBinding>();
ltzb.add(new TransportZoneBinding(cmd.getTransportUuid(), cmd.getTransportType()));
logicalSwitch.setTransport_zones(ltzb);
// Tags set to scope cs_account and account name
List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
tags.add(new NiciraNvpTag("cs_account",cmd.getOwnerName()));
logicalSwitch.setTags(tags);
try {
logicalSwitch = _niciraNvpApi.createLogicalSwitch(logicalSwitch);
return new CreateLogicalSwitchAnswer(cmd, true, "Logicalswitch " + logicalSwitch.getUuid() + " created", logicalSwitch.getUuid());
} catch (NiciraNvpApiException e) {
return new CreateLogicalSwitchAnswer(cmd, e);
}
}
private Answer executeRequest(DeleteLogicalSwitchCommand cmd) {
try {
_niciraNvpApi.deleteLogicalSwitch(cmd.getLogicalSwitchUuid());
return new DeleteLogicalSwitchAnswer(cmd, true, "Logicalswitch " + cmd.getLogicalSwitchUuid() + " deleted");
} catch (NiciraNvpApiException e) {
return new DeleteLogicalSwitchAnswer(cmd, e);
}
}
private Answer executeRequest(CreateLogicalSwitchPortCommand cmd) {
String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
String attachmentUuid = cmd.getAttachmentUuid();
try {
// Tags set to scope cs_account and account name
List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
tags.add(new NiciraNvpTag("cs_account",cmd.getOwnerName()));
LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true);
LogicalSwitchPort newPort = _niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort);
_niciraNvpApi.modifyLogicalSwitchPortAttachment(cmd.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid));
return new CreateLogicalSwitchPortAnswer(cmd, true, "Logical switch port " + newPort.getUuid() + " created", newPort.getUuid());
} catch (NiciraNvpApiException e) {
return new CreateLogicalSwitchPortAnswer(cmd, e);
}
}
private Answer executeRequest(DeleteLogicalSwitchPortCommand cmd) {
try {
_niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), cmd.getLogicalSwitchPortUuid());
return new DeleteLogicalSwitchPortAnswer(cmd, true, "Logical switch port " + cmd.getLogicalSwitchPortUuid() + " deleted");
} catch (NiciraNvpApiException e) {
return new DeleteLogicalSwitchPortAnswer(cmd, e);
}
}
private Answer executeRequest(ReadyCommand cmd) {
return new ReadyAnswer(cmd);
}
private Answer executeRequest(MaintainCommand cmd) {
return new MaintainAnswer(cmd);
}
}

View File

@ -12,11 +12,14 @@
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network.guru;
import java.util.List;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.event.EventTypes;
@ -38,7 +41,10 @@ import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.State;
import com.cloud.network.PhysicalNetwork;
import com.cloud.network.PhysicalNetwork.IsolationMethod;
@Local(value=NetworkGuru.class)
public class OvsGuestNetworkGuru extends GuestNetworkGuru {
@ -46,6 +52,28 @@ public class OvsGuestNetworkGuru extends GuestNetworkGuru {
@Inject NetworkManager _externalNetworkManager;
@Inject OvsTunnelManager _ovsTunnelMgr;
OvsGuestNetworkGuru() {
super();
_isolationMethods = new IsolationMethod[] { IsolationMethod.GRE, IsolationMethod.L3, IsolationMethod.VLAN };
}
protected boolean canHandle(NetworkOffering offering,
final NetworkType networkType, final PhysicalNetwork physicalNetwork) {
// This guru handles only Guest Isolated network that supports Source
// nat service
if (networkType == NetworkType.Advanced
&& isMyTrafficType(offering.getTrafficType())
&& offering.getGuestType() == Network.GuestType.Isolated
&& isMyIsolationMethod(physicalNetwork)) {
return true;
} else {
s_logger.trace("We only take care of Guest networks of type "
+ GuestType.Isolated + " in zone of type "
+ NetworkType.Advanced);
return false;
}
}
@Override
public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) {

View File

@ -354,7 +354,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
txn.start();
SearchCriteria<HostVO> sc = UnmanagedApplianceSearch.create();
sc.setParameters("lastPinged", lastPingSecondsAfter);
sc.setParameters("types", Type.ExternalDhcp, Type.ExternalFirewall, Type.ExternalLoadBalancer, Type.PxeServer, Type.TrafficMonitor);
sc.setParameters("types", Type.ExternalDhcp, Type.ExternalFirewall, Type.ExternalLoadBalancer, Type.PxeServer, Type.TrafficMonitor, Type.L2Networking);
List<HostVO> hosts = lockRows(sc, null, true);
for (HostVO host : hosts) {
@ -493,7 +493,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
List<HostVO> result = new ArrayList<HostVO>();
ResultSet rs = null;
try {
String sql = "select h.id from host h left join cluster c on h.cluster_id=c.id where h.mgmt_server_id is not null and h.last_ping < ? and h.status in ('Up', 'Updating', 'Disconnected', 'Connecting') and h.type not in ('ExternalFirewall', 'ExternalLoadBalancer', 'TrafficMonitor', 'SecondaryStorage', 'LocalSecondaryStorage') and (h.cluster_id is null or c.managed_state = 'Managed') ;" ;
String sql = "select h.id from host h left join cluster c on h.cluster_id=c.id where h.mgmt_server_id is not null and h.last_ping < ? and h.status in ('Up', 'Updating', 'Disconnected', 'Connecting') and h.type not in ('ExternalFirewall', 'ExternalLoadBalancer', 'TrafficMonitor', 'SecondaryStorage', 'LocalSecondaryStorage', 'L2Networking') and (h.cluster_id is null or c.managed_state = 'Managed') ;" ;
pstmt = txn.prepareStatement(sql);
pstmt.setLong(1, timeout);
rs = pstmt.executeQuery();

View File

@ -28,12 +28,18 @@ import com.cloud.storage.dao.VMTemplateDetailsDao;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.Inject;
import com.cloud.vm.NicProfile;
import com.cloud.vm.NicVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.VMInstanceDao;
public abstract class HypervisorGuruBase extends AdapterBase implements HypervisorGuru {
@Inject VMTemplateDetailsDao _templateDetailsDao;
@Inject NicDao _nicDao;
@Inject VMInstanceDao _virtualMachineDao;
protected HypervisorGuruBase() {
super();
@ -55,6 +61,10 @@ public abstract class HypervisorGuruBase extends AdapterBase implements Hypervis
to.setIsolationuri(profile.getIsolationUri());
to.setNetworkRateMbps(profile.getNetworkRate());
to.setName(profile.getName());
// Workaround to make sure the TO has the UUID we need for Niciri integration
NicVO nicVO = _nicDao.findById(profile.getId());
to.setUuid(nicVO.getUuid());
return to;
}
@ -92,6 +102,11 @@ public abstract class HypervisorGuruBase extends AdapterBase implements Hypervis
details.putAll(detailsInVm);
}
to.setDetails(details);
// Workaround to make sure the TO has the UUID we need for Niciri integration
VMInstanceVO vmInstance = _virtualMachineDao.findById(to.getId());
to.setUuid(vmInstance.getUuid());
return to;
}

View File

@ -39,6 +39,8 @@ public interface ExternalNetworkDeviceManager extends Manager {
public static final NetworkDevice NetscalerSDXLoadBalancer = new NetworkDevice("NetscalerSDXLoadBalancer", Network.Provider.Netscaler.getName());
public static final NetworkDevice F5BigIpLoadBalancer = new NetworkDevice("F5BigIpLoadBalancer", Network.Provider.F5BigIp.getName());
public static final NetworkDevice JuniperSRXFirewall = new NetworkDevice("JuniperSRXFirewall", Network.Provider.JuniperSRX.getName());
public static final NetworkDevice NiciraNvp = new NetworkDevice("NiciraNvp", Network.Provider.NiciraNvp.getName());
public NetworkDevice(String deviceName, String ntwkServiceprovider) {
_name = deviceName;

View File

@ -1455,7 +1455,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
try {
if (predefined == null
|| (offering.getTrafficType() != TrafficType.Guest && predefined.getCidr() == null && predefined.getBroadcastUri() == null && predefined.getBroadcastDomainType() != BroadcastDomainType.Vlan)) {
|| (offering.getTrafficType() != TrafficType.Guest && predefined.getCidr() == null && predefined.getBroadcastUri() == null &&
!(predefined.getBroadcastDomainType() == BroadcastDomainType.Vlan || predefined.getBroadcastDomainType() == BroadcastDomainType.Lswitch))) {
List<NetworkVO> configs = _networksDao.listBy(owner.getId(), offering.getId(), plan.getDataCenterId());
if (configs.size() > 0) {
if (s_logger.isDebugEnabled()) {
@ -1721,6 +1722,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
Integer networkRate = getNetworkRate(config.getId(), null);
to.setNetworkRateMbps(networkRate);
to.setUuid(config.getUuid());
return to;
}

View File

@ -20,9 +20,12 @@ import java.util.List;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
@ -32,10 +35,13 @@ import com.cloud.event.EventVO;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
import com.cloud.network.Network;
import com.cloud.network.Network.GuestType;
import com.cloud.network.Network.State;
import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.PhysicalNetwork;
import com.cloud.network.PhysicalNetwork.IsolationMethod;
import com.cloud.network.PhysicalNetworkVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.PhysicalNetworkDao;
@ -58,7 +64,7 @@ import com.cloud.vm.VirtualMachineProfile;
@Local(value = NetworkGuru.class)
public class ExternalGuestNetworkGuru extends GuestNetworkGuru {
private static final Logger s_logger = Logger.getLogger(ExternalGuestNetworkGuru.class);
@Inject
NetworkManager _networkMgr;
@Inject
@ -68,7 +74,27 @@ public class ExternalGuestNetworkGuru extends GuestNetworkGuru {
@Inject
PortForwardingRulesDao _pfRulesDao;
//FIXME: why there is dependency on Ovs tunnel manager.
public ExternalGuestNetworkGuru() {
super();
_isolationMethods = new IsolationMethod[] { IsolationMethod.GRE, IsolationMethod.L3, IsolationMethod.VLAN };
}
protected boolean canHandle(NetworkOffering offering,
final NetworkType networkType, final PhysicalNetwork physicalNetwork) {
// This guru handles only Guest Isolated network that supports Source
// nat service
if (networkType == NetworkType.Advanced
&& isMyTrafficType(offering.getTrafficType())
&& offering.getGuestType() == Network.GuestType.Isolated
&& isMyIsolationMethod(physicalNetwork)) {
return true;
} else {
s_logger.trace("We only take care of Guest networks of type "
+ GuestType.Isolated + " in zone of type "
+ NetworkType.Advanced);
return false;
}
}
@Override
public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) {

View File

@ -16,6 +16,7 @@
// under the License.
package com.cloud.network.guru;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
@ -46,9 +47,12 @@ import com.cloud.network.Network.State;
import com.cloud.network.NetworkManager;
import com.cloud.network.NetworkProfile;
import com.cloud.network.NetworkVO;
import com.cloud.network.PhysicalNetwork;
import com.cloud.network.PhysicalNetwork.IsolationMethod;
import com.cloud.network.PhysicalNetworkVO;
import com.cloud.network.Networks.AddressFormat;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.IsolationType;
import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.IPAddressDao;
@ -72,7 +76,7 @@ import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.NicDao;
@Local(value = NetworkGuru.class)
public class GuestNetworkGuru extends AdapterBase implements NetworkGuru {
public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGuru {
private static final Logger s_logger = Logger.getLogger(GuestNetworkGuru.class);
@Inject
protected NetworkManager _networkMgr;
@ -93,12 +97,16 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru {
Random _rand = new Random(System.currentTimeMillis());
private static final TrafficType[] _trafficTypes = {TrafficType.Guest};
// Currently set to anything except STT for the Nicira integration.
protected IsolationMethod[] _isolationMethods;
String _defaultGateway;
String _defaultCidr;
protected GuestNetworkGuru() {
super();
_isolationMethods = null;
}
@Override
@ -115,21 +123,54 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru {
public TrafficType[] getSupportedTrafficType() {
return _trafficTypes;
}
public boolean isMyIsolationMethod(PhysicalNetwork physicalNetwork) {
if (physicalNetwork == null) {
// Can't tell if there is no physical network
return false;
}
List<String> methods = physicalNetwork.getIsolationMethods();
if (methods.isEmpty()) {
// The empty isolation method is assumed to be VLAN
s_logger.debug("Empty physical isolation type for physical network " + physicalNetwork.getUuid());
methods = new ArrayList<String>(1);
methods.add("VLAN");
}
for (IsolationMethod m : _isolationMethods) {
if (methods.contains(m.toString())) {
return true;
}
}
return false;
}
public IsolationMethod[] getIsolationMethods() {
return _isolationMethods;
}
protected boolean canHandle(NetworkOffering offering, DataCenter dc) {
protected abstract boolean canHandle(NetworkOffering offering, final NetworkType networkType, PhysicalNetwork physicalNetwork);
/* protected boolean canHandle(NetworkOffering offering, final NetworkType networkType, final List<String> isolationMethods) {
// This guru handles only Guest Isolated network that supports Source nat service
if (dc.getNetworkType() == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated) {
if (networkType == NetworkType.Advanced
&& isMyTrafficType(offering.getTrafficType())
&& offering.getGuestType() == Network.GuestType.Isolated
&& isMyIsolationMethod(isolationMethods)) {
return true;
} else {
s_logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced);
return false;
}
}
*/
@Override
public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) {
DataCenter dc = _dcDao.findById(plan.getDataCenterId());
if (!canHandle(offering, dc)) {
PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId());
if (!canHandle(offering, dc.getNetworkType(), physnet)) {
return null;
}

View File

@ -168,6 +168,7 @@ public class StatsCollector {
sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.SecondaryStorageVM.toString());
sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.ExternalFirewall.toString());
sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.ExternalLoadBalancer.toString());
sc.addAnd("type", SearchCriteria.Op.NEQ, Host.Type.L2Networking.toString());
ConcurrentHashMap<Long, HostStats> hostStats = new ConcurrentHashMap<Long, HostStats>();
List<HostVO> hosts = _hostDao.search(sc, null);
for (HostVO host : hosts)

View File

@ -137,6 +137,9 @@ DROP TABLE IF EXISTS `cloud`.`op_dc_storage_network_ip_address`;
DROP TABLE IF EXISTS `cloud`.`cluster_vsm_map`;
DROP TABLE IF EXISTS `cloud`.`virtual_supervisor_module`;
DROP TABLE IF EXISTS `cloud`.`port_profile`;
DROP TABLE IF EXISTS `cloud`,`external_nicira_nvp_devices`;
DROP TABLE IF EXISTS `cloud`,`nicira_nvp_nic_map`;
CREATE TABLE `cloud`.`version` (
`id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id',
@ -2152,4 +2155,24 @@ CREATE TABLE `cloud`.`resource_tags` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`external_nicira_nvp_devices` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`uuid` varchar(255) UNIQUE,
`physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network in to which nicira nvp device is added',
`provider_name` varchar(255) NOT NULL COMMENT 'Service Provider name corresponding to this nicira nvp device',
`device_name` varchar(255) NOT NULL COMMENT 'name of the nicira nvp device',
`host_id` bigint unsigned NOT NULL COMMENT 'host id coresponding to the external nicira nvp device',
PRIMARY KEY (`id`),
CONSTRAINT `fk_external_nicira_nvp_devices__host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE,
CONSTRAINT `fk_external_nicira_nvp_devices__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`nicira_nvp_nic_map` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`logicalswitch` varchar(255) NOT NULL COMMENT 'nicira uuid of logical switch this port is provisioned on',
`logicalswitchport` varchar(255) UNIQUE COMMENT 'nicira uuid of this logical switch port',
`nic` varchar(255) UNIQUE COMMENT 'cloudstack uuid of the nic connected to this logical switch port',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SET foreign_key_checks = 1;

View File

@ -596,7 +596,7 @@
}
});
//when OVS tunnel manager is used
if(ovsTunnelManager == true) {
//if(ovsTunnelManager == true) {
//Advanced zone supports 2 isolation method(VLAN, GRE), so show dropdown including the 2 options
if($wizard.find('.select-network-model input:radio[name=network-model]:checked').val() == 'Advanced') {
$nameField.append(
@ -614,15 +614,20 @@
}).html('VLAN'),
$('<option>').attr({
value: 'GRE'
}).html('GRE')
}).html('GRE'),
$('<option>').attr({
value: 'STT'
}).html('STT')
)
)
);
}
//Basic zone supports only 1 isolation method (L3), so there is no point showing dropdown.
}
//when OVS tunnel manager is not used, isolationmethods parameter in createPhysicalNetwork API is ignored. So no showing dropdown.
// }
//when OVS tunnel manager is not used, isolationmethods parameter in createPhysicalNetwork API is ignored. So no showing dropdown.
//isolationmethods parameter has not been used by network gurus so far. By default(i.e. when OVS tunnel manager is not used), networks are isolated with VLANs in Advanced zone, with L3 in basic zone.
//No longer the case, as the Nicira stuff also depends on this now
var $dropContainer = $('<div>').addClass('drop-container').append(

View File

@ -288,7 +288,7 @@ depsclasspath = [ in_javadir(_basename(x)) for x in _glob(_join(conf.srcdir,"dep
conf.env.DEPSCLASSPATH = pathsep.join(depsclasspath)
# the MS classpath points to JARs required to run the management server
msclasspath = [ in_javadir("%s-%s.jar"%(conf.env.PACKAGE,x)) for x in "utils api core server server-extras core-extras vmware-base ovm dp-user-concentrated-pod dp-user-dispersing host-allocator-random plugin-f5 plugin-netscaler plugin-ovs plugin-srx storage-allocator-random user-authenticator-ldap user-authenticator-md5 user-authenticator-plaintext vmware xen".split() ]
msclasspath = [ in_javadir("%s-%s.jar"%(conf.env.PACKAGE,x)) for x in "utils api core server server-extras core-extras vmware-base ovm dp-user-concentrated-pod dp-user-dispersing host-allocator-random plugin-f5 plugin-netscaler plugin-ovs plugin-srx storage-allocator-random user-authenticator-ldap user-authenticator-md5 user-authenticator-plaintext vmware xen plugin-nicira-nvp".split() ]
conf.env.MSCLASSPATH = pathsep.join(msclasspath)
# the agent and simulator classpaths point to JARs required to run these two applications