You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by hu...@apache.org on 2014/07/23 11:11:30 UTC
[3/4] CLOUDSTACK-6823 : First code drop for Brocade Network plugin to
orchestrate Brocade VDX switches for L2 connectivity
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/BrocadeVcsApi.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/BrocadeVcsApi.java b/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/BrocadeVcsApi.java
new file mode 100644
index 0000000..d5f06f8
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/BrocadeVcsApi.java
@@ -0,0 +1,521 @@
+// 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.brocade;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.nio.charset.Charset;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.http.HttpResponse;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPatch;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.log4j.Logger;
+
+import com.cloud.network.schema.interfacevlan.InterfaceVlan;
+import com.cloud.network.schema.interfacevlan.Interface;
+import com.cloud.network.schema.interfacevlan.Vlan;
+import com.cloud.network.schema.portprofile.PortProfile;
+import com.cloud.network.schema.portprofile.PortProfile.Activate;
+import com.cloud.network.schema.portprofile.PortProfile.Static;
+import com.cloud.network.schema.portprofile.PortProfileGlobal;
+import com.cloud.network.schema.portprofile.VlanProfile;
+import com.cloud.network.schema.portprofile.VlanProfile.Switchport;
+import com.cloud.network.schema.portprofile.VlanProfile.Switchport.Mode;
+import com.cloud.network.schema.portprofile.VlanProfile.Switchport.Trunk;
+import com.cloud.network.schema.portprofile.VlanProfile.Switchport.Trunk.Allowed;
+import com.cloud.network.schema.portprofile.VlanProfile.SwitchportBasic;
+import com.cloud.network.schema.portprofile.VlanProfile.SwitchportBasic.Basic;
+import com.cloud.network.schema.showvcs.Output;
+
+public class BrocadeVcsApi {
+ private static final Logger s_logger = Logger.getLogger(BrocadeVcsApi.class);
+
+ private String _host;
+ private String _adminuser;
+ private String _adminpass;
+
+ protected DefaultHttpClient _client;
+
+ protected HttpRequestBase createMethod(String type, String uri) throws BrocadeVcsApiException {
+ String url;
+ try {
+ url = new URL(Constants.PROTOCOL, _host, Constants.PORT, uri).toString();
+ } catch (MalformedURLException e) {
+ s_logger.error("Unable to build Brocade Switch API URL", e);
+ throw new BrocadeVcsApiException("Unable to build Brocade Switch API URL", e);
+ }
+
+ if ("post".equalsIgnoreCase(type)) {
+ return new HttpPost(url);
+ } else if ("get".equalsIgnoreCase(type)) {
+ return new HttpGet(url);
+ } else if ("delete".equalsIgnoreCase(type)) {
+ return new HttpDelete(url);
+ } else if ("patch".equalsIgnoreCase(type)) {
+ return new HttpPatch(url);
+ } else {
+ throw new BrocadeVcsApiException("Requesting unknown method type");
+ }
+ }
+
+ public BrocadeVcsApi(String address, String username, String password) {
+ _host = address;
+ _adminuser = username;
+ _adminpass = password;
+ _client = new DefaultHttpClient();
+ _client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(_adminuser, _adminpass));
+
+ }
+
+ /*
+ * Get Operational Status
+ */
+ public Output getSwitchStatus() throws BrocadeVcsApiException {
+ return executeRetreiveStatus(Constants.STATUS_URI);
+
+ }
+
+ /*
+ * Creates a new virtual network.
+ */
+ public boolean createNetwork(int vlanId, long networkId) throws BrocadeVcsApiException {
+
+ if (createInterfaceVlan(vlanId)) {
+
+ PortProfile portProfile = createPortProfile(vlanId, networkId);
+
+ if (portProfile != null) {
+ return activatePortProfile(portProfile);
+ }
+ }
+ return false;
+ }
+
+ /*
+ * Activates a port-profile.
+ */
+ private boolean activatePortProfile(PortProfile portProfile) throws BrocadeVcsApiException {
+ PortProfileGlobal portProfileGlobal = new PortProfileGlobal();
+ portProfile.setVlanProfile(null);
+ Activate activate = new Activate();
+ portProfile.setActivate(activate);
+ portProfileGlobal.setPortProfile(portProfile);
+
+ //activate port-profile
+ return executeUpdateObject(portProfileGlobal, Constants.URI);
+ }
+
+ /*
+ * Creates AMPP port-profile.
+ */
+ private PortProfile createPortProfile(int vlanId, long networkId) throws BrocadeVcsApiException {
+
+ PortProfile portProfile = new PortProfile();
+ portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId);
+ if (executeCreateObject(portProfile, Constants.URI)) {
+ if (createVlanSubProfile(vlanId, portProfile)) {
+ return portProfile;
+ }
+ }
+ return null;
+ }
+
+ /*
+ * Create vlan sub-profile for port-profile
+ */
+ private boolean createVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException {
+ VlanProfile vlanProfile = new VlanProfile();
+ portProfile.setVlanProfile(vlanProfile);
+ if (executeUpdateObject(portProfile, Constants.URI)) {
+ return configureVlanSubProfile(vlanId, portProfile);
+ }
+ return false;
+ }
+
+ /*
+ * Configures vlan sub-profile for port-profile.
+ * - configure L2 mode for vlan sub-profile
+ * - configure trunk mode for vlan sub-profile
+ * - configure allowed VLANs for vlan sub-profile
+ */
+ private boolean configureVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException {
+ SwitchportBasic switchPortBasic = new SwitchportBasic();
+ Basic basic = new Basic();
+ switchPortBasic.setBasic(basic);
+ portProfile.getVlanProfile().setSwitchportBasic(switchPortBasic);
+ // configure L2 mode for vlan sub-profile
+ if (executeUpdateObject(portProfile, Constants.URI)) {
+ VlanProfile vlanProfile = new VlanProfile();
+ Switchport switchPort = new Switchport();
+ Mode mode = new Mode();
+ mode.setVlanMode("trunk");
+ switchPort.setMode(mode);
+ vlanProfile.setSwitchport(switchPort);
+ portProfile.setVlanProfile(vlanProfile);
+
+ // configure trunk mode for vlan sub-profile
+ if (executeUpdateObject(portProfile, Constants.URI)) {
+ vlanProfile = new VlanProfile();
+ switchPort = new Switchport();
+ Trunk trunk = new Trunk();
+ Allowed allowed = new Allowed();
+ Allowed.Vlan allowedVlan = new Allowed.Vlan();
+ allowedVlan.setAdd(vlanId);
+ allowed.setVlan(allowedVlan);
+ trunk.setAllowed(allowed);
+ switchPort.setTrunk(trunk);
+ vlanProfile.setSwitchport(switchPort);
+ portProfile.setVlanProfile(vlanProfile);
+
+ //configure allowed VLANs for vlan sub-profile
+ return executeUpdateObject(portProfile, Constants.URI);
+ }
+ }
+
+ return false;
+
+ }
+
+ /*
+ * Creates a vlan interface.
+ */
+ private boolean createInterfaceVlan(int vlanId) throws BrocadeVcsApiException {
+ InterfaceVlan interfaceVlan = new InterfaceVlan();
+ Interface interfaceObj = new Interface();
+ Vlan vlan = new Vlan();
+ vlan.setName(vlanId);
+ interfaceObj.setVlan(vlan);
+ interfaceVlan.setInterface(interfaceObj);
+
+ return executeUpdateObject(interfaceVlan, Constants.URI);
+
+ }
+
+ /*
+ * Associates a MAC address to virtual network.
+ */
+ public boolean associateMacToNetwork(long networkId, String macAddress) throws BrocadeVcsApiException {
+
+ PortProfileGlobal portProfileGlobal = new PortProfileGlobal();
+ PortProfile portProfile = new PortProfile();
+ portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId);
+ Static staticObj = new Static();
+ staticObj.setMacAddress(macAddress);
+ portProfile.setStatic(staticObj);
+ portProfileGlobal.setPortProfile(portProfile);
+
+ //associates a mac address to a port-profile
+ return executeUpdateObject(portProfileGlobal, Constants.URI);
+ }
+
+ /*
+ * Disassociates a MAC address from virtual network.
+ */
+ public boolean disassociateMacFromNetwork(long networkId, String macAddress) throws BrocadeVcsApiException {
+
+ PortProfileGlobal portProfileGlobal = new PortProfileGlobal();
+ PortProfile portProfile = new PortProfile();
+ portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId);
+ Static staticObj = new Static();
+ staticObj.setOperation("delete");
+ staticObj.setMacAddress(macAddress);
+ portProfile.setStatic(staticObj);
+ portProfileGlobal.setPortProfile(portProfile);
+
+ //associates a mac address to a port-profile
+ return executeUpdateObject(portProfileGlobal, Constants.URI);
+ }
+
+ /*
+ * Deletes a new virtual network.
+ */
+ public boolean deleteNetwork(int vlanId, long networkId) throws BrocadeVcsApiException {
+
+ if (deactivatePortProfile(networkId)) {
+
+ if (deletePortProfile(networkId)) {
+ return deleteInterfaceVlan(vlanId);
+ }
+ }
+ return false;
+ }
+
+ /*
+ * Deletes a vlan interface.
+ */
+ private boolean deleteInterfaceVlan(int vlanId) throws BrocadeVcsApiException {
+ InterfaceVlan interfaceVlan = new InterfaceVlan();
+ Interface interfaceObj = new Interface();
+ Vlan vlan = new Vlan();
+ vlan.setOperation("delete");
+ vlan.setName(vlanId);
+ interfaceObj.setVlan(vlan);
+ interfaceVlan.setInterface(interfaceObj);
+
+ return executeUpdateObject(interfaceVlan, Constants.URI);
+
+ }
+
+ /*
+ * Deactivates a port-profile.
+ */
+ private boolean deactivatePortProfile(long networkId) throws BrocadeVcsApiException {
+ PortProfileGlobal portProfileGlobal = new PortProfileGlobal();
+ PortProfile portProfile = new PortProfile();
+ portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId);
+ Activate activate = new Activate();
+ activate.setOperation("delete");
+ portProfile.setActivate(activate);
+ portProfileGlobal.setPortProfile(portProfile);
+
+ //activate port-profile
+ return executeUpdateObject(portProfileGlobal, Constants.URI);
+ }
+
+ /*
+ * Deletes AMPP port-profile.
+ */
+ private boolean deletePortProfile(long networkId) throws BrocadeVcsApiException {
+
+ PortProfile portProfile = new PortProfile();
+ portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId);
+ portProfile.setOperation("delete");
+ //deletes port-profile
+ return executeUpdateObject(portProfile, Constants.URI);
+ }
+
+ protected <T> boolean executeUpdateObject(T newObject, String uri) throws BrocadeVcsApiException {
+
+ boolean result = true;
+
+ if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) {
+ throw new BrocadeVcsApiException("Hostname/credentials are null or empty");
+ }
+
+ HttpPatch pm = (HttpPatch)createMethod("patch", uri);
+ pm.setHeader("Accept", "application/vnd.configuration.resource+xml");
+
+ pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML));
+
+ HttpResponse response = executeMethod(pm);
+
+ if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
+ String errorMessage = responseToErrorMessage(response);
+ pm.releaseConnection();
+ s_logger.error("Failed to update object : " + errorMessage);
+ throw new BrocadeVcsApiException("Failed to update object : " + errorMessage);
+ }
+
+ pm.releaseConnection();
+
+ return result;
+ }
+
+ protected <T> String convertToString(T object) throws BrocadeVcsApiException {
+
+ final StringWriter stringWriter = new StringWriter();
+
+ try {
+ final JAXBContext context = JAXBContext.newInstance(object.getClass());
+ final Marshaller marshaller = context.createMarshaller();
+
+ marshaller.marshal(object, stringWriter);
+
+ } catch (JAXBException e) {
+ s_logger.error("Failed to convert object to string : " + e.getMessage());
+ throw new BrocadeVcsApiException("Failed to convert object to string : " + e.getMessage());
+ }
+
+ String str = stringWriter.toString();
+ s_logger.info(str);
+
+ return str;
+
+ }
+
+ protected Output convertToXML(String object) throws BrocadeVcsApiException {
+
+ Output output = null;
+ try {
+ JAXBContext context = JAXBContext.newInstance(Output.class);
+
+ StringReader reader = new StringReader(object);
+
+ final Unmarshaller unmarshaller = context.createUnmarshaller();
+ Object result = unmarshaller.unmarshal(reader);
+
+ if (result instanceof Output) {
+ output = (Output)result;
+ s_logger.info(output);
+ }
+
+ } catch (JAXBException e) {
+ s_logger.error("Failed to convert string to object : " + e.getMessage());
+ throw new BrocadeVcsApiException("Failed to convert string to object : " + e.getMessage());
+ }
+
+ return output;
+
+ }
+
+ protected <T> boolean executeCreateObject(T newObject, String uri) throws BrocadeVcsApiException {
+ if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) {
+ throw new BrocadeVcsApiException("Hostname/credentials are null or empty");
+ }
+
+ boolean result = true;
+ HttpPost pm = (HttpPost)createMethod("post", uri);
+ pm.setHeader("Accept", "application/vnd.configuration.resource+xml");
+ pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML));
+
+ HttpResponse response = executeMethod(pm);
+
+ if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
+ String errorMessage = responseToErrorMessage(response);
+ pm.releaseConnection();
+ s_logger.error("Failed to create object : " + errorMessage);
+ throw new BrocadeVcsApiException("Failed to create object : " + errorMessage);
+ }
+
+ pm.releaseConnection();
+
+ return result;
+ }
+
+ protected Output executeRetreiveStatus(String uri) throws BrocadeVcsApiException {
+ if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) {
+ throw new BrocadeVcsApiException("Hostname/credentials are null or empty");
+ }
+
+ BufferedReader br = null;
+ String readLine = null;
+ StringBuffer sb = null;
+
+ HttpPost pm = (HttpPost)createMethod("post", uri);
+ pm.setHeader("Accept", "application/vnd.operational-state.resource+xml");
+ pm.setEntity(new StringEntity("<show-vcs></show-vcs>", ContentType.APPLICATION_XML));
+
+ HttpResponse response = executeMethod(pm);
+
+ if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
+ String errorMessage = responseToErrorMessage(response);
+ pm.releaseConnection();
+ s_logger.error("Failed to retreive status : " + errorMessage);
+ throw new BrocadeVcsApiException("Failed to retreive status : " + errorMessage);
+ }
+
+ try {
+ br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")));
+ sb = new StringBuffer();
+
+ while (((readLine = br.readLine()) != null)) {
+ s_logger.debug(readLine);
+ sb.append(readLine);
+
+ }
+ } catch (Exception e) {
+ s_logger.error("Failed to get object : " + e.getMessage());
+ throw new BrocadeVcsApiException("Failed to get object : " + e.getMessage());
+ }
+
+ pm.releaseConnection();
+
+ return convertToXML(sb.toString());
+ }
+
+ protected void executeDeleteObject(String uri) throws BrocadeVcsApiException {
+ if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) {
+ throw new BrocadeVcsApiException("Hostname/credentials are null or empty");
+ }
+
+ HttpDelete dm = (HttpDelete)createMethod("delete", uri);
+ dm.setHeader("Accept", "application/vnd.configuration.resource+xml");
+
+ HttpResponse response = executeMethod(dm);
+
+ if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
+ String errorMessage = responseToErrorMessage(response);
+ dm.releaseConnection();
+ s_logger.error("Failed to delete object : " + errorMessage);
+ throw new BrocadeVcsApiException("Failed to delete object : " + errorMessage);
+ }
+ dm.releaseConnection();
+ }
+
+ protected HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException {
+ HttpResponse response = null;
+ try {
+ response = _client.execute(method);
+ if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
+ method.releaseConnection();
+ response = _client.execute(method);
+ }
+ } catch (HttpException e) {
+ s_logger.error("HttpException caught while trying to connect to the Brocade Switch", e);
+ method.releaseConnection();
+ throw new BrocadeVcsApiException("API call to Brocade Switch Failed", e);
+ } catch (IOException e) {
+ s_logger.error("IOException caught while trying to connect to the Brocade Switch", e);
+ method.releaseConnection();
+ throw new BrocadeVcsApiException("API call to Brocade Switch Failed", e);
+ }
+
+ return response;
+ }
+
+ private String responseToErrorMessage(HttpResponse response) {
+
+ if ("text/html".equals(response.getEntity().getContentType().getValue())) {
+ try {
+
+ BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")));
+
+ StringBuffer result = new StringBuffer();
+ String line = "";
+ while ((line = rd.readLine()) != null) {
+ result.append(line);
+ }
+
+ return result.toString();
+ } catch (IOException e) {
+ s_logger.debug("Error while loading response body", e);
+ }
+ }
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/BrocadeVcsApiException.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/BrocadeVcsApiException.java b/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/BrocadeVcsApiException.java
new file mode 100644
index 0000000..76f3079
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/BrocadeVcsApiException.java
@@ -0,0 +1,36 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.brocade;
+
+public class BrocadeVcsApiException extends Exception {
+
+ public BrocadeVcsApiException() {
+ }
+
+ public BrocadeVcsApiException(String message) {
+ super(message);
+ }
+
+ public BrocadeVcsApiException(Throwable cause) {
+ super(cause);
+ }
+
+ public BrocadeVcsApiException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/Constants.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/Constants.java b/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/Constants.java
new file mode 100644
index 0000000..5a9fa0a
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/src/com/cloud/network/brocade/Constants.java
@@ -0,0 +1,37 @@
+// 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.brocade;
+
+public class Constants {
+ public static final String PROTOCOL = "http";
+
+ public static final String URI = "/rest/config/running";
+
+ public static final String STATUS_URI = "/rest/operational-state/show-vcs";
+
+ public static final int PORT = 80;
+
+ public static final String PORT_PROFILE_NAME_PREFIX = "cloudstack-profile-";
+
+ public static final String BROCADE_VCS_DEVICE_ID = "vcsdeviceid";
+ public static final String BROCADE_VCS_DEVICE_NAME = "brocadedevicename";
+
+ public static final String EVENT_EXTERNAL_VCS_CONTROLLER_ADD = "PHYSICAL.VCSCONTROLLER.ADD";
+ public static final String EVENT_EXTERNAL_VCS_CONTROLLER_DELETE = "PHYSICAL.VCSCONTROLLER.DELETE";
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsDao.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsDao.java b/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsDao.java
new file mode 100644
index 0000000..76e36a1
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsDao.java
@@ -0,0 +1,35 @@
+//
+// 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.dao;
+
+import java.util.List;
+
+import com.cloud.network.BrocadeVcsDeviceVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface BrocadeVcsDao extends GenericDao<BrocadeVcsDeviceVO, Long> {
+ /**
+ * list all the brocade vcs devices added in to this physical network
+ * @param physicalNetworkId physical network Id
+ * @return list of BrocadevcsDeviceVO for this zone and pod.
+ */
+ List<BrocadeVcsDeviceVO> listByPhysicalNetwork(final long physicalNetworkId);
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsDaoImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsDaoImpl.java b/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsDaoImpl.java
new file mode 100644
index 0000000..ec5691a
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsDaoImpl.java
@@ -0,0 +1,53 @@
+//
+// 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.dao;
+
+import java.util.List;
+
+import javax.ejb.Local;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.network.BrocadeVcsDeviceVO;
+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;
+
+@Component
+@Local(value = BrocadeVcsDao.class)
+public class BrocadeVcsDaoImpl extends GenericDaoBase<BrocadeVcsDeviceVO, Long> implements BrocadeVcsDao {
+
+ protected final SearchBuilder<BrocadeVcsDeviceVO> physicalNetworkIdSearch;
+
+ public BrocadeVcsDaoImpl() {
+ physicalNetworkIdSearch = createSearchBuilder();
+ physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ);
+ physicalNetworkIdSearch.done();
+ }
+
+ @Override
+ public List<BrocadeVcsDeviceVO> listByPhysicalNetwork(final long physicalNetworkId) {
+ SearchCriteria<BrocadeVcsDeviceVO> sc = physicalNetworkIdSearch.create();
+ sc.setParameters("physicalNetworkId", physicalNetworkId);
+ return search(sc, null);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDao.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDao.java b/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDao.java
new file mode 100644
index 0000000..16d2986
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDao.java
@@ -0,0 +1,32 @@
+// 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.dao;
+
+import com.cloud.network.BrocadeVcsNetworkVlanMappingVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface BrocadeVcsNetworkVlanMappingDao extends GenericDao<BrocadeVcsNetworkVlanMappingVO, Long> {
+
+ /**
+ * find the mapping for a network
+ * @param networkId
+ * the network id
+ * @return BrocadeNetworkHostMapping for this network id or null if it does not
+ * exist
+ */
+ public BrocadeVcsNetworkVlanMappingVO findByNetworkId(long networkId);
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDaoImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDaoImpl.java b/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDaoImpl.java
new file mode 100644
index 0000000..88c52a6
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/src/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDaoImpl.java
@@ -0,0 +1,49 @@
+// 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.dao;
+
+import javax.ejb.Local;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.network.BrocadeVcsNetworkVlanMappingVO;
+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;
+
+@Component
+@Local(value = BrocadeVcsNetworkVlanMappingDao.class)
+public class BrocadeVcsNetworkVlanMappingDaoImpl extends GenericDaoBase<BrocadeVcsNetworkVlanMappingVO, Long> implements BrocadeVcsNetworkVlanMappingDao {
+
+ protected final SearchBuilder<BrocadeVcsNetworkVlanMappingVO> networkSearch;
+
+ public BrocadeVcsNetworkVlanMappingDaoImpl() {
+ networkSearch = createSearchBuilder();
+ networkSearch.and("network_id", networkSearch.entity().getNetworkId(), Op.EQ);
+ networkSearch.done();
+
+ }
+
+ @Override
+ public BrocadeVcsNetworkVlanMappingVO findByNetworkId(long networkId) {
+ SearchCriteria<BrocadeVcsNetworkVlanMappingVO> sc = networkSearch.create();
+ sc.setParameters("network_id", networkId);
+ return findOneBy(sc);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/src/com/cloud/network/element/BrocadeVcsElement.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/src/com/cloud/network/element/BrocadeVcsElement.java b/plugins/network-elements/brocade-vcs/src/com/cloud/network/element/BrocadeVcsElement.java
new file mode 100644
index 0000000..b551092
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/src/com/cloud/network/element/BrocadeVcsElement.java
@@ -0,0 +1,467 @@
+// 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.Set;
+import java.util.UUID;
+
+import javax.ejb.Local;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+
+import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
+import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.StartupBrocadeVcsCommand;
+import com.cloud.agent.api.StartupCommand;
+import com.cloud.api.ApiDBUtils;
+import com.cloud.api.commands.AddBrocadeVcsDeviceCmd;
+import com.cloud.api.commands.DeleteBrocadeVcsDeviceCmd;
+import com.cloud.api.commands.ListBrocadeVcsDeviceNetworksCmd;
+import com.cloud.api.commands.ListBrocadeVcsDevicesCmd;
+import com.cloud.api.response.BrocadeVcsDeviceResponse;
+import com.cloud.configuration.ConfigurationManager;
+import com.cloud.dc.dao.VlanDao;
+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.BrocadeVcsDeviceVO;
+import com.cloud.network.IpAddressManager;
+import com.cloud.network.Network;
+import com.cloud.network.Networks;
+import com.cloud.network.PhysicalNetwork;
+import com.cloud.network.Network.Capability;
+import com.cloud.network.Network.Provider;
+import com.cloud.network.Network.Service;
+import com.cloud.network.NetworkModel;
+import com.cloud.network.Networks.BroadcastDomainType;
+import com.cloud.network.PhysicalNetworkServiceProvider;
+import com.cloud.network.dao.BrocadeVcsDao;
+import com.cloud.network.dao.NetworkDao;
+import com.cloud.network.dao.NetworkServiceMapDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.PhysicalNetworkDao;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
+import com.cloud.network.dao.PhysicalNetworkVO;
+import com.cloud.network.resource.BrocadeVcsResource;
+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.db.DB;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.db.TransactionStatus;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.NicProfile;
+import com.cloud.vm.ReservationContext;
+import com.cloud.vm.VirtualMachineProfile;
+import com.cloud.vm.dao.NicDao;
+
+@Component
+@Local(value = {NetworkElement.class})
+public class BrocadeVcsElement extends AdapterBase implements NetworkElement, ResourceStateAdapter, BrocadeVcsElementService {
+ private static final Logger s_logger = Logger.getLogger(BrocadeVcsElement.class);
+
+ private static final Map<Service, Map<Capability, String>> capabilities = setCapabilities();
+
+ @Inject
+ NicDao _nicDao;
+ @Inject
+ ResourceManager _resourceMgr;
+ @Inject
+ PhysicalNetworkDao _physicalNetworkDao;
+ @Inject
+ PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao;
+ @Inject
+ protected BrocadeVcsDao _brocadeVcsDao;
+ @Inject
+ HostDetailsDao _hostDetailsDao;
+ @Inject
+ HostDao _hostDao;
+ @Inject
+ AgentManager _agentMgr;
+ @Inject
+ NetworkDao _networkDao;
+ @Inject
+ NetworkOrchestrationService _networkManager;
+ @Inject
+ NetworkModel _networkModel;
+ @Inject
+ ConfigurationManager _configMgr;
+ @Inject
+ NetworkServiceMapDao _ntwkSrvcDao;
+ @Inject
+ VlanDao _vlanDao;
+ @Inject
+ IpAddressManager _ipAddrMgr;
+
+ @Override
+ public Map<Service, Map<Capability, String>> getCapabilities() {
+ return capabilities;
+ }
+
+ @Override
+ public Provider getProvider() {
+ return Network.Provider.BrocadeVcs;
+ }
+
+ protected boolean canHandle(Network network, Service service) {
+ s_logger.debug("Checking if BrocadeVcsElement can handle service " + service.getName() + " on network " + network.getDisplayText());
+ if (network.getBroadcastDomainType() != BroadcastDomainType.Vcs) {
+ return false;
+ }
+
+ if (!_networkModel.isProviderForNetwork(getProvider(), network.getId())) {
+ s_logger.debug("BrocadeVcsElement is not a provider for network " + network.getDisplayText());
+ return false;
+ }
+
+ if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), service, Network.Provider.BrocadeVcs)) {
+ s_logger.debug("BrocadeVcsElement can't provide the " + service.getName() + " service on network " + network.getDisplayText());
+ 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 {
+ s_logger.debug("entering BrocadeVcsElement implement function for network " + network.getDisplayText() + " (state " + network.getState() + ")");
+
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
+ ResourceUnavailableException, InsufficientCapacityException {
+
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException {
+
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
+ if (!canHandle(network, Service.Connectivity)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException {
+ if (!canHandle(network, Service.Connectivity)) {
+ 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 true;
+ }
+
+ @Override
+ public boolean verifyServicesCombination(Set<Service> services) {
+
+ if (!services.contains(Service.Connectivity)) {
+ s_logger.warn("Unable to provide services without Connectivity service enabled for this element");
+ return false;
+ }
+ return true;
+ }
+
+ private static Map<Service, Map<Capability, String>> setCapabilities() {
+ Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
+
+ // L2 Support
+ capabilities.put(Service.Connectivity, null);
+
+ return capabilities;
+ }
+
+ @Override
+ public List<Class<?>> getCommands() {
+ List<Class<?>> cmdList = new ArrayList<Class<?>>();
+ cmdList.add(AddBrocadeVcsDeviceCmd.class);
+ cmdList.add(DeleteBrocadeVcsDeviceCmd.class);
+ cmdList.add(ListBrocadeVcsDeviceNetworksCmd.class);
+ cmdList.add(ListBrocadeVcsDevicesCmd.class);
+ return cmdList;
+ }
+
+ @Override
+ @DB
+ public BrocadeVcsDeviceVO addBrocadeVcsDevice(AddBrocadeVcsDeviceCmd cmd) {
+ ServerResource resource = new BrocadeVcsResource();
+ final String deviceName = Network.Provider.BrocadeVcs.getName();
+ NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName);
+ if (networkDevice == null) {
+ throw new CloudRuntimeException("No network device found for " + deviceName);
+ }
+ final Long physicalNetworkId = cmd.getPhysicalNetworkId();
+ PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
+ if (physicalNetwork == null) {
+ throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
+ }
+ long zoneId = physicalNetwork.getDataCenterId();
+
+ final 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");
+ }
+
+ 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", "Brocade VCS - " + cmd.getHost());
+ params.put("ip", cmd.getHost());
+ params.put("adminuser", cmd.getUsername());
+ params.put("adminpass", cmd.getPassword());
+
+ Map<String, Object> hostdetails = new HashMap<String, Object>();
+ hostdetails.putAll(params);
+
+ try {
+ resource.configure(cmd.getHost(), hostdetails);
+
+ final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params);
+ if (host != null) {
+ return Transaction.execute(new TransactionCallback<BrocadeVcsDeviceVO>() {
+ @Override
+ public BrocadeVcsDeviceVO doInTransaction(TransactionStatus status) {
+ BrocadeVcsDeviceVO brocadeVcsDevice = new BrocadeVcsDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName);
+ _brocadeVcsDao.persist(brocadeVcsDevice);
+
+ DetailVO detail = new DetailVO(host.getId(), "brocadevcsdeviceid", String.valueOf(brocadeVcsDevice.getId()));
+ _hostDetailsDao.persist(detail);
+
+ return brocadeVcsDevice;
+ }
+ });
+ } else {
+ throw new CloudRuntimeException("Failed to add Brocade VCS Switch due to internal error.");
+ }
+ } catch (ConfigurationException e) {
+ throw new CloudRuntimeException(e.getMessage());
+ }
+
+ }
+
+ @Override
+ public BrocadeVcsDeviceResponse createBrocadeVcsDeviceResponse(BrocadeVcsDeviceVO brocadeVcsDeviceVO) {
+ HostVO brocadeVcsHost = _hostDao.findById(brocadeVcsDeviceVO.getHostId());
+ _hostDao.loadDetails(brocadeVcsHost);
+
+ BrocadeVcsDeviceResponse response = new BrocadeVcsDeviceResponse();
+ response.setDeviceName(brocadeVcsDeviceVO.getDeviceName());
+ PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(brocadeVcsDeviceVO.getPhysicalNetworkId());
+ if (pnw != null) {
+ response.setPhysicalNetworkId(pnw.getUuid());
+ }
+ response.setId(brocadeVcsDeviceVO.getUuid());
+ response.setProviderName(brocadeVcsDeviceVO.getProviderName());
+ response.setHostName(brocadeVcsHost.getDetail("ip"));
+ response.setObjectName("brocadevcsdevice");
+ return response;
+ }
+
+ @Override
+ public boolean deleteBrocadeVcsDevice(DeleteBrocadeVcsDeviceCmd cmd) {
+ Long brocadeDeviceId = cmd.getBrocadeVcsDeviceId();
+ BrocadeVcsDeviceVO brocadeVcsDevice = _brocadeVcsDao.findById(brocadeDeviceId);
+ if (brocadeVcsDevice == null) {
+ throw new InvalidParameterValueException("Could not find a brocade vcs switch with id " + brocadeVcsDevice);
+ }
+
+ // Find the physical network we work for
+ Long physicalNetworkId = brocadeVcsDevice.getPhysicalNetworkId();
+ PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
+ if (physicalNetwork != null) {
+ // Lets see if there are networks that use us
+ // Find the brocade networks on this physical network
+ List<NetworkVO> networkList = _networkDao.listByPhysicalNetwork(physicalNetworkId);
+ if (networkList != null) {
+ // Networks with broadcast type vcs are ours
+ for (NetworkVO network : networkList) {
+ if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Vcs) {
+ if ((network.getState() != Network.State.Shutdown) && (network.getState() != Network.State.Destroy)) {
+ throw new CloudRuntimeException("This Brocade VCS Switch can not be deleted as there are one or more logical networks provisioned by cloudstack.");
+ }
+ }
+ }
+ }
+ }
+
+ HostVO brocadeHost = _hostDao.findById(brocadeVcsDevice.getHostId());
+ Long hostId = brocadeHost.getId();
+
+ brocadeHost.setResourceState(ResourceState.Maintenance);
+ _hostDao.update(hostId, brocadeHost);
+ _resourceMgr.deleteHost(hostId, false, false);
+
+ _brocadeVcsDao.remove(brocadeDeviceId);
+ return true;
+ }
+
+ @Override
+ public List<BrocadeVcsDeviceVO> listBrocadeVcsDevices(ListBrocadeVcsDevicesCmd cmd) {
+ Long physicalNetworkId = cmd.getPhysicalNetworkId();
+ Long brocadeVcsDeviceId = cmd.getBrocadeVcsDeviceId();
+ List<BrocadeVcsDeviceVO> responseList = new ArrayList<BrocadeVcsDeviceVO>();
+
+ if (physicalNetworkId == null && brocadeVcsDeviceId == null) {
+ throw new InvalidParameterValueException("Either physical network Id or brocade vcs switch Id must be specified");
+ }
+
+ if (brocadeVcsDeviceId != null) {
+ BrocadeVcsDeviceVO brocadeVcsDevice = _brocadeVcsDao.findById(brocadeVcsDeviceId);
+ if (brocadeVcsDevice == null) {
+ throw new InvalidParameterValueException("Could not find Brocade VCS Switch with id: " + brocadeVcsDeviceId);
+ }
+ responseList.add(brocadeVcsDevice);
+ } else {
+ PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
+ if (physicalNetwork == null) {
+ throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId);
+ }
+ responseList = _brocadeVcsDao.listByPhysicalNetwork(physicalNetworkId);
+ }
+
+ return responseList;
+ }
+
+ @Override
+ public List<? extends Network> listBrocadeVcsDeviceNetworks(ListBrocadeVcsDeviceNetworksCmd cmd) {
+ Long brocadeDeviceId = cmd.getBrocadeVcsDeviceId();
+ BrocadeVcsDeviceVO brocadeVcsDevice = _brocadeVcsDao.findById(brocadeDeviceId);
+ if (brocadeVcsDevice == null) {
+ throw new InvalidParameterValueException("Could not find a Brocade VCS Switch with id " + brocadeDeviceId);
+ }
+
+ // Find the physical network we work for
+ Long physicalNetworkId = brocadeVcsDevice.getPhysicalNetworkId();
+ PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
+ if (physicalNetwork == null) {
+ // No such physical network, so no provisioned networks
+ return Collections.emptyList();
+ }
+
+ // Find the brocade networks on this physical network
+ List<NetworkVO> networkList = _networkDao.listByPhysicalNetwork(physicalNetworkId);
+ if (networkList == null) {
+ return Collections.emptyList();
+ }
+
+ // Networks with broadcast type vcs are ours
+ List<NetworkVO> responseList = new ArrayList<NetworkVO>();
+ for (NetworkVO network : networkList) {
+ if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Vcs) {
+ 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 StartupBrocadeVcsCommand)) {
+ 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);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/src/com/cloud/network/element/BrocadeVcsElementService.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/src/com/cloud/network/element/BrocadeVcsElementService.java b/plugins/network-elements/brocade-vcs/src/com/cloud/network/element/BrocadeVcsElementService.java
new file mode 100644
index 0000000..b8db60c
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/src/com/cloud/network/element/BrocadeVcsElementService.java
@@ -0,0 +1,45 @@
+//
+// 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.List;
+
+import com.cloud.api.commands.AddBrocadeVcsDeviceCmd;
+import com.cloud.api.commands.DeleteBrocadeVcsDeviceCmd;
+import com.cloud.api.commands.ListBrocadeVcsDeviceNetworksCmd;
+import com.cloud.api.commands.ListBrocadeVcsDevicesCmd;
+import com.cloud.api.response.BrocadeVcsDeviceResponse;
+import com.cloud.network.Network;
+import com.cloud.network.BrocadeVcsDeviceVO;
+import com.cloud.utils.component.PluggableService;
+
+public interface BrocadeVcsElementService extends PluggableService {
+
+ public BrocadeVcsDeviceVO addBrocadeVcsDevice(AddBrocadeVcsDeviceCmd cmd);
+
+ public BrocadeVcsDeviceResponse createBrocadeVcsDeviceResponse(BrocadeVcsDeviceVO brocadeDeviceVO);
+
+ boolean deleteBrocadeVcsDevice(DeleteBrocadeVcsDeviceCmd cmd);
+
+ List<? extends Network> listBrocadeVcsDeviceNetworks(ListBrocadeVcsDeviceNetworksCmd cmd);
+
+ List<BrocadeVcsDeviceVO> listBrocadeVcsDevices(ListBrocadeVcsDevicesCmd cmd);
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/src/com/cloud/network/guru/BrocadeVcsGuestNetworkGuru.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/src/com/cloud/network/guru/BrocadeVcsGuestNetworkGuru.java b/plugins/network-elements/brocade-vcs/src/com/cloud/network/guru/BrocadeVcsGuestNetworkGuru.java
new file mode 100644
index 0000000..92bf113
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/src/com/cloud/network/guru/BrocadeVcsGuestNetworkGuru.java
@@ -0,0 +1,267 @@
+// 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.util.List;
+
+import javax.ejb.Local;
+import javax.inject.Inject;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.AssociateMacToNetworkAnswer;
+import com.cloud.agent.api.AssociateMacToNetworkCommand;
+import com.cloud.agent.api.CreateNetworkAnswer;
+import com.cloud.agent.api.CreateNetworkCommand;
+import com.cloud.agent.api.DeleteNetworkAnswer;
+import com.cloud.agent.api.DeleteNetworkCommand;
+import com.cloud.agent.api.DisassociateMacFromNetworkAnswer;
+import com.cloud.agent.api.DisassociateMacFromNetworkCommand;
+import com.cloud.dc.DataCenter;
+import com.cloud.dc.DataCenter.NetworkType;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.deploy.DeploymentPlan;
+import com.cloud.exception.InsufficientAddressCapacityException;
+import com.cloud.exception.InsufficientVirtualNetworkCapacityException;
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.network.BrocadeVcsDeviceVO;
+import com.cloud.network.BrocadeVcsNetworkVlanMappingVO;
+import com.cloud.network.Network;
+import com.cloud.network.Network.GuestType;
+import com.cloud.network.Network.Service;
+import com.cloud.network.Network.State;
+import com.cloud.network.NetworkProfile;
+import com.cloud.network.Networks.BroadcastDomainType;
+import com.cloud.network.PhysicalNetwork;
+import com.cloud.network.PhysicalNetwork.IsolationMethod;
+import com.cloud.network.dao.BrocadeVcsDao;
+import com.cloud.network.dao.BrocadeVcsNetworkVlanMappingDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
+import com.cloud.network.dao.PhysicalNetworkVO;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
+import com.cloud.resource.ResourceManager;
+import com.cloud.user.Account;
+import com.cloud.vm.NicProfile;
+import com.cloud.vm.ReservationContext;
+import com.cloud.vm.VirtualMachineProfile;
+
+@Local(value = NetworkGuru.class)
+public class BrocadeVcsGuestNetworkGuru extends GuestNetworkGuru {
+ private static final Logger s_logger = Logger.getLogger(BrocadeVcsGuestNetworkGuru.class);
+
+ @Inject
+ NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao;
+ @Inject
+ ResourceManager _resourceMgr;
+ @Inject
+ AgentManager _agentMgr;
+ @Inject
+ protected BrocadeVcsDao _brocadeVcsDao;
+ @Inject
+ protected BrocadeVcsNetworkVlanMappingDao _brocadeVcsNetworkVlanDao;
+ @Inject
+ PhysicalNetworkServiceProviderDao _pNSPDao;
+ @Inject
+ HostDao _hostDao;
+
+ public BrocadeVcsGuestNetworkGuru() {
+ super();
+ _isolationMethods = new IsolationMethod[] {IsolationMethod.VCS};
+ }
+
+ @Override
+ protected boolean canHandle(NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) {
+ // This guru handles only Guest Isolated network that supports L2 connectivity service
+ if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated
+ && isMyIsolationMethod(physicalNetwork) && _ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Connectivity)) {
+ 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 VLAN
+ PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId());
+ DataCenter dc = _dcDao.findById(plan.getDataCenterId());
+ if (!canHandle(offering, dc.getNetworkType(), physnet)) {
+ s_logger.debug("Refusing to design this network");
+ return null;
+ }
+ s_logger.debug("Physical isolation type is VCS, 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.Vcs);
+ networkObject.setState(State.Allocated);
+
+ return networkObject;
+ }
+
+ @Override
+ public Network implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws InsufficientVirtualNetworkCapacityException {
+ assert (network.getState() == State.Implementing) : "Why are we implementing " + network;
+
+ Network implemented = super.implement(network, offering, dest, context);
+
+ int vlanTag = Integer.parseInt(BroadcastDomainType.getValue(implemented.getBroadcastUri()));
+
+ //get physical network id
+ Long physicalNetworkId = network.getPhysicalNetworkId();
+
+ List<BrocadeVcsDeviceVO> devices = _brocadeVcsDao.listByPhysicalNetwork(physicalNetworkId);
+ if (devices.isEmpty()) {
+ s_logger.error("No Brocade VCS Switch on physical network " + physicalNetworkId);
+ return null;
+ }
+
+ for (BrocadeVcsDeviceVO brocadeVcsDevice : devices) {
+ HostVO brocadeVcsHost = _hostDao.findById(brocadeVcsDevice.getHostId());
+
+ // create createNetworkCmd instance and agentMgr execute it.
+ CreateNetworkCommand cmd = new CreateNetworkCommand(vlanTag, network.getId(), context.getDomain().getName() + "-" + context.getAccount().getAccountName());
+ CreateNetworkAnswer answer = (CreateNetworkAnswer)_agentMgr.easySend(brocadeVcsHost.getId(), cmd);
+
+ if (answer == null || !answer.getResult()) {
+ s_logger.error("CreateNetworkCommand failed");
+ s_logger.error("Unable to create network " + network.getId());
+ return null;
+ }
+
+ }
+
+ // Persist the network-vlan mapping from db
+ BrocadeVcsNetworkVlanMappingVO brocadeVcsNetworkVlanMapping = new BrocadeVcsNetworkVlanMappingVO(network.getId(), vlanTag);
+ _brocadeVcsNetworkVlanDao.persist(brocadeVcsNetworkVlanMapping);
+
+ return implemented;
+ }
+
+ @Override
+ public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context)
+ throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
+ super.reserve(nic, network, vm, dest, context);
+
+ DataCenter dc = _dcDao.findById(network.getDataCenterId());
+
+ String interfaceMac = nic.getMacAddress();
+
+ List<BrocadeVcsDeviceVO> devices = _brocadeVcsDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ s_logger.error("No Brocade VCS Switch on physical network " + network.getPhysicalNetworkId());
+ return;
+ }
+ for (BrocadeVcsDeviceVO brocadeVcsDevice : devices) {
+ HostVO brocadeVcsHost = _hostDao.findById(brocadeVcsDevice.getHostId());
+
+ // create AssociateMacToNetworkCmd instance and agentMgr execute it.
+ AssociateMacToNetworkCommand cmd = new AssociateMacToNetworkCommand(network.getId(), interfaceMac, context.getDomain().getName() + "-"
+ + context.getAccount().getAccountName());
+ AssociateMacToNetworkAnswer answer = (AssociateMacToNetworkAnswer)_agentMgr.easySend(brocadeVcsHost.getId(), cmd);
+
+ if (answer == null || !answer.getResult()) {
+ s_logger.error("AssociateMacToNetworkCommand failed");
+ throw new InsufficientVirtualNetworkCapacityException("Unable to associate mac " + interfaceMac + " to network " + network.getId(), DataCenter.class, dc.getId());
+ }
+ }
+
+ }
+
+ @Override
+ public void deallocate(Network network, NicProfile nic, VirtualMachineProfile vm) {
+
+ String interfaceMac = nic.getMacAddress();
+
+ List<BrocadeVcsDeviceVO> devices = _brocadeVcsDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ s_logger.error("No Brocade VCS Switch on physical network " + network.getPhysicalNetworkId());
+ return;
+ }
+ for (BrocadeVcsDeviceVO brocadeVcsDevice : devices) {
+ HostVO brocadeVcsHost = _hostDao.findById(brocadeVcsDevice.getHostId());
+
+ // create DisassociateMacFromNetworkCmd instance and agentMgr execute it.
+ DisassociateMacFromNetworkCommand cmd = new DisassociateMacFromNetworkCommand(network.getId(), interfaceMac);
+ DisassociateMacFromNetworkAnswer answer = (DisassociateMacFromNetworkAnswer)_agentMgr.easySend(brocadeVcsHost.getId(), cmd);
+
+ if (answer == null || !answer.getResult()) {
+ s_logger.error("DisassociateMacFromNetworkCommand failed");
+ s_logger.error("Unable to disassociate mac " + interfaceMac + " from network " + network.getId());
+ return;
+ }
+ }
+ super.deallocate(network, nic, vm);
+ }
+
+ @Override
+ public boolean release(NicProfile nic, VirtualMachineProfile vm, String reservationId) {
+ return super.release(nic, vm, reservationId);
+ }
+
+ @Override
+ public void shutdown(NetworkProfile profile, NetworkOffering offering) {
+
+ super.shutdown(profile, offering);
+ }
+
+ @Override
+ public boolean trash(Network network, NetworkOffering offering) {
+
+ int vlanTag = 0;
+ // Get the network-vlan mapping from db
+ BrocadeVcsNetworkVlanMappingVO brocadeVcsNetworkVlanMapping = _brocadeVcsNetworkVlanDao.findByNetworkId(network.getId());
+
+ if (brocadeVcsNetworkVlanMapping != null) {
+ vlanTag = brocadeVcsNetworkVlanMapping.getVlanId();
+ } else {
+ s_logger.error("Not able to find vlanId for network " + network.getId());
+ return false;
+ }
+
+ List<BrocadeVcsDeviceVO> devices = _brocadeVcsDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
+ if (devices.isEmpty()) {
+ s_logger.error("No Brocade VCS Switch on physical network " + network.getPhysicalNetworkId());
+ return false;
+ }
+ for (BrocadeVcsDeviceVO brocadeVcsDevice : devices) {
+ HostVO brocadeVcsHost = _hostDao.findById(brocadeVcsDevice.getHostId());
+
+ // create deleteNetworkCmd instance and agentMgr execute it.
+ DeleteNetworkCommand cmd = new DeleteNetworkCommand(vlanTag, network.getId());
+ DeleteNetworkAnswer answer = (DeleteNetworkAnswer)_agentMgr.easySend(brocadeVcsHost.getId(), cmd);
+
+ if (answer == null || !answer.getResult()) {
+ s_logger.error("DeleteNetworkCommand failed");
+ s_logger.error("Unable to delete network " + network.getId());
+ return false;
+ }
+ }
+
+ // Remove the network-vlan mapping from db
+ _brocadeVcsNetworkVlanDao.remove(brocadeVcsNetworkVlanMapping.getId());
+ return super.trash(network, offering);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/src/com/cloud/network/resource/BrocadeVcsResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/src/com/cloud/network/resource/BrocadeVcsResource.java b/plugins/network-elements/brocade-vcs/src/com/cloud/network/resource/BrocadeVcsResource.java
new file mode 100644
index 0000000..0a32399
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/src/com/cloud/network/resource/BrocadeVcsResource.java
@@ -0,0 +1,310 @@
+// 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.resource;
+
+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.AssociateMacToNetworkAnswer;
+import com.cloud.agent.api.AssociateMacToNetworkCommand;
+import com.cloud.agent.api.Command;
+import com.cloud.agent.api.CreateNetworkAnswer;
+import com.cloud.agent.api.CreateNetworkCommand;
+import com.cloud.agent.api.DeleteNetworkAnswer;
+import com.cloud.agent.api.DeleteNetworkCommand;
+import com.cloud.agent.api.DisassociateMacFromNetworkAnswer;
+import com.cloud.agent.api.DisassociateMacFromNetworkCommand;
+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.StartupBrocadeVcsCommand;
+import com.cloud.agent.api.StartupCommand;
+import com.cloud.host.Host;
+import com.cloud.host.Host.Type;
+import com.cloud.network.brocade.BrocadeVcsApi;
+import com.cloud.network.brocade.BrocadeVcsApiException;
+import com.cloud.network.schema.showvcs.Output;
+import com.cloud.network.schema.showvcs.VcsNodeInfo;
+import com.cloud.resource.ServerResource;
+
+public class BrocadeVcsResource implements ServerResource {
+ private static final Logger s_logger = Logger.getLogger(BrocadeVcsResource.class);
+
+ private String _name;
+ private String _guid;
+ private String _zoneId;
+ private int _numRetries;
+
+ private BrocadeVcsApi _brocadeVcsApi;
+
+ protected BrocadeVcsApi createBrocadeVcsApi(String ip, String username, String password) {
+
+ return new BrocadeVcsApi(ip, username, password);
+ }
+
+ @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");
+ }
+
+ _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");
+ }
+
+ _numRetries = 2;
+
+ String ip = (String)params.get("ip");
+ if (ip == null) {
+ throw new ConfigurationException("Unable to find IP");
+ }
+
+ String adminuser = (String)params.get("adminuser");
+ if (adminuser == null) {
+ throw new ConfigurationException("Unable to find admin username");
+ }
+
+ String adminpass = (String)params.get("adminpass");
+ if (adminpass == null) {
+ throw new ConfigurationException("Unable to find admin password");
+ }
+
+ _brocadeVcsApi = createBrocadeVcsApi(ip, adminuser, adminpass);
+
+ return true;
+ }
+
+ @Override
+ public boolean start() {
+ return true;
+ }
+
+ @Override
+ public boolean stop() {
+ return true;
+ }
+
+ @Override
+ public String getName() {
+ return _name;
+ }
+
+ @Override
+ public Type getType() {
+ return Host.Type.L2Networking;
+ }
+
+ @Override
+ public StartupCommand[] initialize() {
+ StartupBrocadeVcsCommand sc = new StartupBrocadeVcsCommand();
+ sc.setGuid(_guid);
+ sc.setName(_name);
+ sc.setDataCenter(_zoneId);
+ sc.setPrivateIpAddress("");
+ sc.setStorageIpAddress("");
+ sc.setVersion(BrocadeVcsResource.class.getPackage().getImplementationVersion());
+ return new StartupCommand[] {sc};
+ }
+
+ @Override
+ public PingCommand getCurrentStatus(long id) {
+
+ Output output;
+ try {
+ output = _brocadeVcsApi.getSwitchStatus();
+ } catch (BrocadeVcsApiException e) {
+ s_logger.error("getSwitchStatus failed", e);
+ return null;
+ }
+
+ List<VcsNodeInfo> vcsNodes = output.getVcsNodes().getVcsNodeInfo();
+ if (vcsNodes != null && !vcsNodes.isEmpty()) {
+ for (VcsNodeInfo vcsNodeInfo : vcsNodes) {
+ if (!"Online".equals(vcsNodeInfo.getNodeState())) {
+ s_logger.error("Brocade Switch is not ready: " + id);
+ return null;
+ }
+ }
+ }
+ return new PingCommand(Host.Type.L2Networking, id);
+
+ }
+
+ @Override
+ public Answer executeRequest(Command cmd) {
+ return executeRequest(cmd, _numRetries);
+ }
+
+ public Answer executeRequest(Command cmd, int numRetries) {
+ if (cmd instanceof ReadyCommand) {
+ return executeRequest((ReadyCommand)cmd);
+ } else if (cmd instanceof MaintainCommand) {
+ return executeRequest((MaintainCommand)cmd);
+ } else if (cmd instanceof CreateNetworkCommand) {
+ return executeRequest((CreateNetworkCommand)cmd, numRetries);
+ } else if (cmd instanceof AssociateMacToNetworkCommand) {
+ return executeRequest((AssociateMacToNetworkCommand)cmd, numRetries);
+ } else if (cmd instanceof DisassociateMacFromNetworkCommand) {
+ return executeRequest((DisassociateMacFromNetworkCommand)cmd, numRetries);
+ } else if (cmd instanceof DeleteNetworkCommand) {
+ return executeRequest((DeleteNetworkCommand)cmd, numRetries);
+ }
+ 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(CreateNetworkCommand cmd, int numRetries) {
+
+ try {
+ boolean result = _brocadeVcsApi.createNetwork(cmd.getVlanId(), cmd.getNetworkId());
+ return new CreateNetworkAnswer(cmd, result, "Port Profile " + cmd.getNetworkId() + " created");
+ } catch (BrocadeVcsApiException e) {
+ if (numRetries > 0) {
+ return retry(cmd, --numRetries);
+ } else {
+ return new CreateNetworkAnswer(cmd, e);
+ }
+ }
+
+ }
+
+ private Answer executeRequest(AssociateMacToNetworkCommand cmd, int numRetries) {
+
+ try {
+
+ String mac = macReformat64To32(cmd.getInterfaceMac());
+ boolean result = _brocadeVcsApi.associateMacToNetwork(cmd.getNetworkId(), mac);
+ return new AssociateMacToNetworkAnswer(cmd, result, "Association of mac " + cmd.getInterfaceMac() + " to network " + cmd.getNetworkId() + " done");
+ } catch (BrocadeVcsApiException e) {
+ if (numRetries > 0) {
+ return retry(cmd, --numRetries);
+ } else {
+ return new AssociateMacToNetworkAnswer(cmd, e);
+ }
+ }
+
+ }
+
+ private Answer executeRequest(DisassociateMacFromNetworkCommand cmd, int numRetries) {
+
+ try {
+
+ String mac = macReformat64To32(cmd.getInterfaceMac());
+ boolean result = _brocadeVcsApi.disassociateMacFromNetwork(cmd.getNetworkId(), mac);
+ return new DisassociateMacFromNetworkAnswer(cmd, result, "Disassociation of mac " + cmd.getInterfaceMac() + " from network " + cmd.getNetworkId() + " done");
+ } catch (BrocadeVcsApiException e) {
+ if (numRetries > 0) {
+ return retry(cmd, --numRetries);
+ } else {
+ return new DisassociateMacFromNetworkAnswer(cmd, e);
+ }
+ }
+
+ }
+
+ private Answer executeRequest(DeleteNetworkCommand cmd, int numRetries) {
+
+ try {
+ boolean result = _brocadeVcsApi.deleteNetwork(cmd.getVlanId(), cmd.getNetworkId());
+ return new DeleteNetworkAnswer(cmd, result, "Port Profile " + cmd.getNetworkId() + " deleted");
+ } catch (BrocadeVcsApiException e) {
+ if (numRetries > 0) {
+ return retry(cmd, --numRetries);
+ } else {
+ return new DeleteNetworkAnswer(cmd, e);
+ }
+ }
+
+ }
+
+ private String macReformat64To32(String interfaceMac) {
+ String mac = interfaceMac.replace(":", "");
+ mac = mac.substring(0, 4) + "." + mac.substring(4, 8) + "." + mac.subSequence(8, 12);
+ return mac;
+
+ }
+
+ private Answer executeRequest(ReadyCommand cmd) {
+ return new ReadyAnswer(cmd);
+ }
+
+ private Answer executeRequest(MaintainCommand cmd) {
+ return new MaintainAnswer(cmd);
+ }
+
+ private Answer retry(Command cmd, int numRetries) {
+ s_logger.warn("Retrying " + cmd.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries);
+ return executeRequest(cmd, numRetries);
+ }
+
+ @Override
+ public void setName(String name) {
+
+ }
+
+ @Override
+ public void setConfigParams(Map<String, Object> params) {
+
+ }
+
+ @Override
+ public Map<String, Object> getConfigParams() {
+
+ return null;
+ }
+
+ @Override
+ public int getRunLevel() {
+
+ return 0;
+ }
+
+ @Override
+ public void setRunLevel(int level) {
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/628d8e66/plugins/network-elements/brocade-vcs/test/com/cloud/network/brocade/BrocadeVcsApiTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/brocade-vcs/test/com/cloud/network/brocade/BrocadeVcsApiTest.java b/plugins/network-elements/brocade-vcs/test/com/cloud/network/brocade/BrocadeVcsApiTest.java
new file mode 100644
index 0000000..4223d4c
--- /dev/null
+++ b/plugins/network-elements/brocade-vcs/test/com/cloud/network/brocade/BrocadeVcsApiTest.java
@@ -0,0 +1,185 @@
+//
+// 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.brocade;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import java.io.IOException;
+
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.http.StatusLine;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpPatch;
+import org.apache.http.client.methods.HttpPost;
+
+import com.cloud.network.schema.showvcs.Output;
+
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.junit.Before;
+import org.junit.Test;
+
+public class BrocadeVcsApiTest {
+ protected static final long NETWORK_ID = 42L;
+ protected static final int VLAN_ID = 14;
+ private static final String MAC_ADDRESS_32 = "0050.56bf.0002";
+ protected static final String OUTPUT_XML_RESPONSE = "<output xmlns='urn:brocade.com:mgmt:brocade-vcs'> <vcs-nodes> <vcs-node-info> <node-state>Online</node-state> </vcs-node-info> </vcs-nodes> </output>";
+ BrocadeVcsApi api;
+ DefaultHttpClient client = mock(DefaultHttpClient.class);
+ HttpRequestBase method;
+ HttpResponse response;
+ HttpResponse postResponse;
+ String type;
+ String uri;
+
+ @Before
+ public void setUp() {
+ api = new BrocadeVcsApi("localhost", "admin", "password") {
+
+ @Override
+ public HttpRequestBase createMethod(final String newType, final String newUri) {
+ type = newType;
+ uri = newUri;
+ return method;
+ }
+
+ @Override
+ public HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException {
+ return response;
+ }
+
+ @Override
+ protected <T> boolean executeCreateObject(T newObject, String uri) throws BrocadeVcsApiException {
+
+ return true;
+ }
+ };
+
+ api._client = client;
+
+ }
+
+ @Test
+ public void testGetSwitchStatus() throws BrocadeVcsApiException, IOException {
+ // Prepare
+
+ method = mock(HttpPost.class);
+
+ response = mock(HttpResponse.class);
+ final StatusLine statusLine = mock(StatusLine.class);
+ when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);
+ when(response.getStatusLine()).thenReturn(statusLine);
+ when(response.getEntity()).thenReturn(new StringEntity(OUTPUT_XML_RESPONSE));
+
+ // Execute
+ Output result = api.getSwitchStatus();
+
+ // Assert
+ verify(method, times(1)).releaseConnection();
+ assertEquals("Wrong URI for get SwitchStatus REST service", Constants.STATUS_URI, uri);
+ assertEquals("Wrong HTTP method for get SwitchStatus REST service", "post", type);
+ assertEquals("Wrong state for get SwitchStatus REST service", "Online", result.getVcsNodes().getVcsNodeInfo().get(0).getNodeState());
+ }
+
+ @Test
+ public void testCreateNetwork() throws BrocadeVcsApiException, IOException {
+ // Prepare
+
+ method = mock(HttpPatch.class);
+
+ response = mock(HttpResponse.class);
+ final StatusLine statusLine = mock(StatusLine.class);
+ when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
+ when(response.getStatusLine()).thenReturn(statusLine);
+
+ // Execute
+ api.createNetwork(VLAN_ID, NETWORK_ID);
+
+ // Assert
+ verify(method, times(6)).releaseConnection();
+ assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri);
+ assertEquals("Wrong HTTP method for Network creation REST service", "patch", type);
+ }
+
+ @Test
+ public void testDeleteNetwork() throws BrocadeVcsApiException, IOException {
+ // Prepare
+
+ method = mock(HttpPatch.class);
+
+ response = mock(HttpResponse.class);
+ final StatusLine statusLine = mock(StatusLine.class);
+ when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
+ when(response.getStatusLine()).thenReturn(statusLine);
+
+ // Execute
+ api.deleteNetwork(VLAN_ID, NETWORK_ID);
+
+ // Assert
+ verify(method, times(3)).releaseConnection();
+ assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri);
+ assertEquals("Wrong HTTP method for Network creation REST service", "patch", type);
+ }
+
+ @Test
+ public void testAssociateMacToNetwork() throws BrocadeVcsApiException, IOException {
+ // Prepare
+
+ method = mock(HttpPatch.class);
+
+ response = mock(HttpResponse.class);
+ final StatusLine statusLine = mock(StatusLine.class);
+ when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
+ when(response.getStatusLine()).thenReturn(statusLine);
+
+ // Execute
+ api.associateMacToNetwork(NETWORK_ID, MAC_ADDRESS_32);
+
+ // Assert
+ verify(method, times(1)).releaseConnection();
+ assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri);
+ assertEquals("Wrong HTTP method for Network creation REST service", "patch", type);
+ }
+
+ @Test
+ public void testDisassociateMacFromNetwork() throws BrocadeVcsApiException, IOException {
+ // Prepare
+
+ method = mock(HttpPatch.class);
+
+ response = mock(HttpResponse.class);
+ final StatusLine statusLine = mock(StatusLine.class);
+ when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT);
+ when(response.getStatusLine()).thenReturn(statusLine);
+
+ // Execute
+ api.disassociateMacFromNetwork(NETWORK_ID, MAC_ADDRESS_32);
+
+ // Assert
+ verify(method, times(1)).releaseConnection();
+ assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri);
+ assertEquals("Wrong HTTP method for Network creation REST service", "patch", type);
+ }
+
+}
\ No newline at end of file