cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From r...@apache.org
Subject [3/7] git commit: updated refs/heads/master to 95ae796
Date Wed, 18 Nov 2015 11:11:17 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/645f8758/plugins/network-elements/nuage-vsp/src/com/cloud/network/manager/NuageVspManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nuage-vsp/src/com/cloud/network/manager/NuageVspManagerImpl.java b/plugins/network-elements/nuage-vsp/src/com/cloud/network/manager/NuageVspManagerImpl.java
index fed970e..dc53310 100644
--- a/plugins/network-elements/nuage-vsp/src/com/cloud/network/manager/NuageVspManagerImpl.java
+++ b/plugins/network-elements/nuage-vsp/src/com/cloud/network/manager/NuageVspManagerImpl.java
@@ -19,45 +19,49 @@
 
 package com.cloud.network.manager;
 
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-
-import javax.ejb.Local;
-import javax.inject.Inject;
-import javax.naming.ConfigurationException;
-
-import org.apache.cloudstack.framework.config.ConfigKey;
-import org.apache.cloudstack.framework.config.Configurable;
-import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
-import org.apache.cloudstack.network.ExternalNetworkDeviceManager;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
-
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.Listener;
+import com.cloud.agent.api.AgentControlAnswer;
+import com.cloud.agent.api.AgentControlCommand;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.agent.api.PingNuageVspCommand;
+import com.cloud.agent.api.StartupCommand;
+import com.cloud.agent.api.manager.GetClientDefaultsAnswer;
+import com.cloud.agent.api.manager.GetClientDefaultsCommand;
+import com.cloud.agent.api.manager.SupportedApiVersionCommand;
+import com.cloud.agent.api.sync.SyncDomainAnswer;
+import com.cloud.agent.api.sync.SyncDomainCommand;
+import com.cloud.agent.api.sync.SyncNuageVspCmsIdAnswer;
+import com.cloud.agent.api.sync.SyncNuageVspCmsIdCommand;
 import com.cloud.api.ApiDBUtils;
 import com.cloud.api.commands.AddNuageVspDeviceCmd;
 import com.cloud.api.commands.DeleteNuageVspDeviceCmd;
 import com.cloud.api.commands.IssueNuageVspResourceRequestCmd;
 import com.cloud.api.commands.ListNuageVspDevicesCmd;
+import com.cloud.api.commands.UpdateNuageVspDeviceCmd;
 import com.cloud.api.response.NuageVspDeviceResponse;
+import com.cloud.dc.DataCenterVO;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.domain.Domain;
+import com.cloud.domain.DomainVO;
+import com.cloud.domain.dao.DomainDao;
+import com.cloud.exception.ConnectionException;
 import com.cloud.exception.InvalidParameterValueException;
 import com.cloud.host.DetailVO;
 import com.cloud.host.Host;
 import com.cloud.host.HostVO;
+import com.cloud.host.Status;
 import com.cloud.host.dao.HostDao;
 import com.cloud.host.dao.HostDetailsDao;
 import com.cloud.network.Network;
+import com.cloud.network.NetworkModel;
 import com.cloud.network.Networks;
 import com.cloud.network.NuageVspDeviceVO;
 import com.cloud.network.PhysicalNetwork;
 import com.cloud.network.PhysicalNetworkServiceProvider;
+import com.cloud.network.dao.FirewallRulesDao;
+import com.cloud.network.dao.IPAddressDao;
 import com.cloud.network.dao.NetworkDao;
 import com.cloud.network.dao.NetworkVO;
 import com.cloud.network.dao.NuageVspDao;
@@ -67,25 +71,79 @@ import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
 import com.cloud.network.dao.PhysicalNetworkVO;
 import com.cloud.network.resource.NuageVspResource;
 import com.cloud.network.sync.NuageVspSync;
+import com.cloud.network.vpc.VpcManager;
+import com.cloud.network.vpc.VpcOffering;
+import com.cloud.network.vpc.VpcOfferingServiceMapVO;
+import com.cloud.network.vpc.VpcOfferingVO;
 import com.cloud.network.vpc.dao.VpcDao;
 import com.cloud.network.vpc.dao.VpcOfferingDao;
 import com.cloud.network.vpc.dao.VpcOfferingServiceMapDao;
+import com.cloud.network.vpc.dao.VpcServiceMapDao;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.offerings.NetworkOfferingServiceMapVO;
+import com.cloud.offerings.NetworkOfferingVO;
+import com.cloud.offerings.dao.NetworkOfferingDao;
+import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
 import com.cloud.resource.ResourceManager;
 import com.cloud.resource.ResourceState;
-import com.cloud.resource.ServerResource;
+import com.cloud.user.AccountManager;
+import com.cloud.user.DomainManager;
 import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.db.DB;
 import com.cloud.utils.db.Transaction;
 import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.db.TransactionCallbackNoReturn;
 import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.fsm.StateListener;
+import com.cloud.utils.fsm.StateMachine2;
+import com.google.common.base.Joiner;
+import com.google.common.base.MoreObjects;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import net.nuage.vsp.acs.NuageVspPluginClientLoader;
+import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.cloudstack.framework.config.Configurable;
+import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
+import org.apache.cloudstack.framework.config.impl.ConfigurationVO;
+import org.apache.cloudstack.framework.messagebus.MessageBus;
+import org.apache.cloudstack.framework.messagebus.MessageSubscriber;
+import org.apache.cloudstack.network.ExternalNetworkDeviceManager;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.log4j.Logger;
+
+import javax.ejb.Local;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+import java.util.ArrayList;
+import java.util.Arrays;
+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 java.util.concurrent.ExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+
+import static com.cloud.agent.api.sync.SyncNuageVspCmsIdCommand.SyncType;
 
 @Local(value = {NuageVspManager.class})
-public class NuageVspManagerImpl extends ManagerBase implements NuageVspManager, Configurable {
+public class NuageVspManagerImpl extends ManagerBase implements NuageVspManager, Configurable, StateListener<Status, Status.Event, Host> {
 
     private static final Logger s_logger = Logger.getLogger(NuageVspManagerImpl.class);
 
     private static final int ONE_MINUTE_MULTIPLIER = 60 * 1000;
 
+    private static final Set<Network.Provider> NUAGE_VSP_PROVIDERS;
+    private static final Map<Network.Service, Set<Network.Provider>> NUAGE_VSP_VPC_SERVICE_MAP;
+    private static final ConfigKey[] NUAGE_VSP_CONFIG_KEYS = new ConfigKey<?>[] { NuageVspConfigDns, NuageVspDnsExternal, NuageVspConfigGateway,
+            NuageVspSharedNetworkDomainTemplateName, NuageVspVpcDomainTemplateName, NuageVspIsolatedNetworkDomainTemplateName };
+
     @Inject
     ResourceManager _resourceMgr;
     @Inject
@@ -97,10 +155,6 @@ public class NuageVspManagerImpl extends ManagerBase implements NuageVspManager,
     @Inject
     PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao;
     @Inject
-    ConfigurationDao _configDao;
-    @Inject
-    NuageVspDao _nuageVspDao;
-    @Inject
     NetworkDao _networkDao;
     @Inject
     VpcOfferingDao _vpcOffDao;
@@ -109,26 +163,59 @@ public class NuageVspManagerImpl extends ManagerBase implements NuageVspManager,
     @Inject
     VpcDao _vpcDao;
     @Inject
-    NuageVspDao nuageVspDao;
+    VpcManager _vpcManager;
+    @Inject
+    NuageVspDao _nuageVspDao;
+    @Inject
+    NuageVspSync _nuageVspSync;
+    @Inject
+    DataCenterDao _dataCenterDao;
+    @Inject
+    ConfigurationDao _configDao;
+    @Inject
+    NetworkModel _ntwkModel;
+    @Inject
+    AccountManager _accountMgr;
+    @Inject
+    IPAddressDao _ipAddressDao;
+    @Inject
+    FirewallRulesDao _firewallDao;
+    @Inject
+    VpcServiceMapDao _vpcSrvcDao;
+    @Inject
+    AgentManager _agentMgr;
+    @Inject
+    private DomainDao _domainDao;
+    @Inject
+    NetworkOfferingDao _networkOfferingDao;
     @Inject
-    NuageVspSync nuageVspSync;
+    NetworkOfferingServiceMapDao _networkOfferingServiceMapDao;
 
     private ScheduledExecutorService scheduler;
 
+    @Inject
+    MessageBus _messageBus;
+
+    static {
+        NUAGE_VSP_PROVIDERS = ImmutableSet.of(Network.Provider.NuageVsp);
+        NUAGE_VSP_VPC_SERVICE_MAP = ImmutableMap.<Network.Service, Set<Network.Provider>>builder()
+                .put(Network.Service.Connectivity, NUAGE_VSP_PROVIDERS)
+                .put(Network.Service.Dhcp, NUAGE_VSP_PROVIDERS)
+                .put(Network.Service.StaticNat, NUAGE_VSP_PROVIDERS)
+                .put(Network.Service.SourceNat, NUAGE_VSP_PROVIDERS)
+                .put(Network.Service.NetworkACL, NUAGE_VSP_PROVIDERS)
+                .build();
+    }
+
     @Override
     public List<Class<?>> getCommands() {
-        List<Class<?>> cmdList = new ArrayList<Class<?>>();
-        cmdList.add(AddNuageVspDeviceCmd.class);
-        cmdList.add(DeleteNuageVspDeviceCmd.class);
-        cmdList.add(ListNuageVspDevicesCmd.class);
-        cmdList.add(IssueNuageVspResourceRequestCmd.class);
-
-        return cmdList;
+        return Lists.<Class<?>>newArrayList(AddNuageVspDeviceCmd.class, DeleteNuageVspDeviceCmd.class, ListNuageVspDevicesCmd.class,
+                IssueNuageVspResourceRequestCmd.class, UpdateNuageVspDeviceCmd.class);
     }
 
     @Override
     public NuageVspDeviceVO addNuageVspDevice(AddNuageVspDeviceCmd cmd) {
-        ServerResource resource = new NuageVspResource();
+        final NuageVspResource resource = new NuageVspResource();
         final String deviceName = Network.Provider.NuageVsp.getName();
         ExternalNetworkDeviceManager.NetworkDevice networkDevice = ExternalNetworkDeviceManager.NetworkDevice.getNetworkDevice(deviceName);
         final Long physicalNetworkId = cmd.getPhysicalNetworkId();
@@ -141,8 +228,8 @@ public class NuageVspManagerImpl extends ManagerBase implements NuageVspManager,
         final PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(),
                 networkDevice.getNetworkServiceProvder());
         if (ntwkSvcProvider == null) {
-            throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() + " is not added in the physical network: " + physicalNetworkId
-                    + "to add this device");
+            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");
@@ -152,53 +239,189 @@ public class NuageVspManagerImpl extends ManagerBase implements NuageVspManager,
             throw new CloudRuntimeException("A NuageVsp 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", "Nuage VSD - " + cmd.getHostName());
-        params.put("hostname", cmd.getHostName());
-        params.put("cmsuser", cmd.getUserName());
-        String cmsUserPasswordBase64 = org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64.encodeBase64(cmd.getPassword().getBytes(Charset.forName("UTF-8"))));
-        params.put("cmsuserpass", cmsUserPasswordBase64);
-        int port = cmd.getPort();
-        if (0 == port) {
-            port = 443;
-        }
-        params.put("port", String.valueOf(port));
-        params.put("apirelativepath", "/nuage/api/" + cmd.getApiVersion());
-        params.put("retrycount", String.valueOf(cmd.getApiRetryCount()));
-        params.put("retryinterval", String.valueOf(cmd.getApiRetryInterval()));
+        try {
+            NuageVspPluginClientLoader clientLoader = NuageVspPluginClientLoader.getClientLoader(null, null, 1, 1, null);
 
-        Map<String, Object> hostdetails = new HashMap<String, Object>();
-        hostdetails.putAll(params);
+            Map<String, Object> clientDefaults = clientLoader.getNuageVspManagerClient().getClientDefaults();
+            String apiVersion = MoreObjects.firstNonNull(cmd.getApiVersion(), (String) clientDefaults.get("CURRENT_API_VERSION"));
+            if (!clientLoader.getNuageVspManagerClient().isSupportedApiVersion(apiVersion)) {
+                throw new CloudRuntimeException("Unsupported API version : " + apiVersion);
+            }
 
-        try {
-            resource.configure(cmd.getHostName(), hostdetails);
+            int port = cmd.getPort();
+            if (0 == port) {
+                port = 8443;
+            }
+            String cmsUserPasswordBase64 = org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64.encodeBase64(cmd.getPassword().getBytes()));
+            String retryCount = String.valueOf(MoreObjects.firstNonNull(cmd.getApiRetryCount(), clientDefaults.get("DEFAULT_API_RETRY_COUNT")));
+            String retryInterval = String.valueOf(MoreObjects.firstNonNull(cmd.getApiRetryInterval(), clientDefaults.get("DEFAULT_API_RETRY_INTERVAL")));
+            NuageVspResource.Configuration resourceConfiguration = new NuageVspResource.Configuration()
+                    .name("Nuage VSD - " + cmd.getHostName())
+                    .guid(UUID.randomUUID().toString())
+                    .zoneId(String.valueOf(physicalNetwork.getDataCenterId()))
+                    .hostName(cmd.getHostName())
+                    .cmsUser(cmd.getUserName())
+                    .cmsUserPassword(cmsUserPasswordBase64)
+                    .port(String.valueOf(port))
+                    .apiVersion(apiVersion)
+                    .apiRelativePath("/nuage/api/" + apiVersion)
+                    .retryCount(retryCount)
+                    .retryInterval(retryInterval);
+
+            Map<String, String> hostDetails = resourceConfiguration.build();
+            resource.configure(cmd.getHostName(), Maps.<String, Object>newHashMap(hostDetails));
+            Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, hostDetails);
+            if (host == null) {
+                throw new CloudRuntimeException("Failed to add Nuage Vsp Device due to internal error.");
+            }
 
-            final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params);
-            if (host != null) {
-                return Transaction.execute(new TransactionCallback<NuageVspDeviceVO>() {
-                    @Override
-                    public NuageVspDeviceVO doInTransaction(TransactionStatus status) {
-                        NuageVspDeviceVO nuageVspDevice = new NuageVspDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName);
-                        _nuageVspDao.persist(nuageVspDevice);
+            NuageVspDeviceVO nuageVspDevice = new NuageVspDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName);
+            _nuageVspDao.persist(nuageVspDevice);
 
-                        DetailVO detail = new DetailVO(host.getId(), "nuagevspdeviceid", String.valueOf(nuageVspDevice.getId()));
-                        _hostDetailsDao.persist(detail);
+            DetailVO detail = new DetailVO(host.getId(), "nuagevspdeviceid", String.valueOf(nuageVspDevice.getId()));
+            _hostDetailsDao.persist(detail);
 
-                        return nuageVspDevice;
-                    }
-                });
+            ConfigurationVO cmsIdConfig = _configDao.findByName("nuagevsp.cms.id");
+            host = findNuageVspHost(nuageVspDevice.getHostId());
+            SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(SyncType.REGISTER, null);
+            SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd);
+            if (answer != null && answer.getSuccess()) {
+                registerNewNuageVspDevice(cmsIdConfig, nuageVspDevice.getId() + ":" + answer.getNuageVspCmsId());
+
+                detail = new DetailVO(host.getId(), "nuagevspcmsid", answer.getNuageVspCmsId());
+                _hostDetailsDao.persist(detail);
+
+                resourceConfiguration.nuageVspCmsId(answer.getNuageVspCmsId());
+                resource.configure(cmd.getHostName(), Maps.<String, Object>newHashMap(resourceConfiguration.build()));
+
+                auditDomainsOnVsp((HostVO) host, true, false);
             } else {
-                throw new CloudRuntimeException("Failed to add Nuage Vsp Device due to internal error.");
+                throw new CloudRuntimeException("Failed to register CMS ID");
             }
+            return nuageVspDevice;
         } catch (ConfigurationException e) {
-            throw new CloudRuntimeException(e.getMessage());
+            s_logger.error("Failed to configure Nuage VSD resource " + cmd.getHostName(), e);
+            throw new CloudRuntimeException("Failed to configure Nuage VSD resource " + cmd.getHostName(), e);
+        } catch (ExecutionException ee) {
+            s_logger.error("Failed to add Nuage VSP device " + cmd.getHostName(), ee);
+            throw new CloudRuntimeException("Failed to add Nuage VSP device " + cmd.getHostName(), ee);
         }
     }
 
     @Override
+    public NuageVspDeviceVO updateNuageVspDevice(UpdateNuageVspDeviceCmd command) {
+        NuageVspResource resource = new NuageVspResource();
+        final String deviceName = Network.Provider.NuageVsp.getName();
+        ExternalNetworkDeviceManager.NetworkDevice networkDevice = ExternalNetworkDeviceManager.NetworkDevice.getNetworkDevice(deviceName);
+        final Long physicalNetworkId = command.getPhysicalNetworkId();
+        PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
+        if (physicalNetwork == null) {
+            throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
+        }
+
+        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");
+        }
+        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");
+        }
+
+        HostVO nuageVspHost = null;
+        NuageVspDeviceVO nuageVspDevice = null;
+        List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listByPhysicalNetwork(physicalNetworkId);
+        if (nuageVspDevices == null || nuageVspDevices.isEmpty()) {
+            throw new CloudRuntimeException("Nuage VSD is not configured on physical network " + physicalNetworkId);
+        } else {
+            nuageVspDevice = nuageVspDevices.iterator().next();
+            nuageVspHost = _hostDao.findById(nuageVspDevice.getHostId());
+            _hostDao.loadDetails(nuageVspHost);
+        }
+
+        boolean updateRequired = false;
+        NuageVspResource.Configuration resourceConfiguration = NuageVspResource.Configuration.fromConfiguration(nuageVspHost.getDetails());
+        if (!Strings.isNullOrEmpty(command.getHostName()) &&
+                !command.getHostName().equals(resourceConfiguration.hostName())) {
+            resourceConfiguration.name("Nuage VSD - " + command.getHostName());
+            resourceConfiguration.hostName(command.getHostName());
+            updateRequired = true;
+        }
+
+        if (!Strings.isNullOrEmpty(command.getUserName()) &&
+                !command.getUserName().equals(resourceConfiguration.cmsUser())) {
+            resourceConfiguration.cmsUser(command.getUserName());
+            updateRequired = true;
+        }
+
+        if (!Strings.isNullOrEmpty(command.getPassword())) {
+            String encodedNewPassword = org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64.encodeBase64(command.getPassword().getBytes()));
+            if (!encodedNewPassword.equals(resourceConfiguration.cmsUserPassword())) {
+                resourceConfiguration.cmsUserPassword(encodedNewPassword);
+                updateRequired = true;
+            }
+        }
+
+        if (command.getPort() != null &&
+                command.getPort() != Integer.parseInt(resourceConfiguration.port())) {
+            resourceConfiguration.port(String.valueOf(command.getPort()));
+            updateRequired = true;
+        }
+
+        GetClientDefaultsCommand getClientDefaultsCmd = new GetClientDefaultsCommand();
+        GetClientDefaultsAnswer getClientDefaultsAnswer = (GetClientDefaultsAnswer) _agentMgr.easySend(nuageVspHost.getId(), getClientDefaultsCmd);
+        String apiVersion = MoreObjects.firstNonNull(command.getApiVersion(), resourceConfiguration.apiVersion());
+        SupportedApiVersionCommand supportedApiVersionCmd = new SupportedApiVersionCommand(apiVersion);
+        Answer supportedApiVersionAnswer = _agentMgr.easySend(nuageVspHost.getId(), supportedApiVersionCmd);
+        if (!supportedApiVersionAnswer.getResult()) {
+            throw new CloudRuntimeException("Incorrect API version: Nuage plugin only supports " + getClientDefaultsAnswer.getCurrentApiVersion());
+        }
+
+        String apiRelativePath = "/nuage/api/" + apiVersion;
+        if (!apiRelativePath.equals(resourceConfiguration.apiRelativePath())) {
+            resourceConfiguration.apiVersion(apiVersion);
+            resourceConfiguration.apiRelativePath(apiRelativePath);
+            updateRequired = true;
+        }
+
+        if (command.getApiRetryCount() != null && resourceConfiguration.retryCount() != null) {
+            final int retryCount = Integer.parseInt(resourceConfiguration.retryCount());
+            if (command.getApiRetryCount() != retryCount) {
+                resourceConfiguration.retryCount(String.valueOf(command.getApiRetryCount()));
+                updateRequired = true;
+            }
+        }
+
+        if (command.getApiRetryInterval() != null && resourceConfiguration.retryInterval() != null) {
+            final int apiRetryInterval = Integer.parseInt(resourceConfiguration.retryInterval());
+            if (command.getApiRetryInterval() != apiRetryInterval) {
+                resourceConfiguration.retryInterval(String.valueOf(command.getApiRetryInterval()));
+                updateRequired = true;
+            }
+        }
+
+        if (!updateRequired) {
+            if (s_logger.isDebugEnabled()) {
+                s_logger.debug("No change in the NuageVsp device parameters. None of the NuageVsp device parameters are modified");
+            }
+            return nuageVspDevice;
+        }
+
+        Map<String, String> config = resourceConfiguration.build();
+        String updateParameters = "{" + Joiner.on(", ").withKeyValueSeparator(": ").join(config) + "}";
+        Map<String, Object> hostDetails = Maps.<String, Object>newHashMap(config);
+        try {
+            resource.configure(resourceConfiguration.hostName(), hostDetails);
+            _hostDetailsDao.persist(nuageVspDevice.getHostId(), config);
+        } catch (ConfigurationException e) {
+            throw new CloudRuntimeException("Failed to update Nuage VSP device " + nuageVspDevice.getId() + " with parameters " + updateParameters, e);
+        }
+        return nuageVspDevice;
+    }
+
+    @Override
     public NuageVspDeviceResponse createNuageVspDeviceResponse(NuageVspDeviceVO nuageVspDeviceVO) {
         HostVO nuageVspHost = _hostDao.findById(nuageVspDeviceVO.getHostId());
         _hostDao.loadDetails(nuageVspHost);
@@ -234,7 +457,7 @@ public class NuageVspManagerImpl extends ManagerBase implements NuageVspManager,
         PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
         if (physicalNetwork != null) {
             // Lets see if there are networks that use us
-            // Find the NuageVsp on this physical network
+            // Find the nuage networks on this physical network
             List<NetworkVO> networkList = _networkDao.listByPhysicalNetwork(physicalNetworkId);
 
             // Networks with broadcast type lswitch are ours
@@ -247,6 +470,26 @@ public class NuageVspManagerImpl extends ManagerBase implements NuageVspManager,
             }
         }
 
+        ConfigurationVO cmsIdConfig = _configDao.findByName("nuagevsp.cms.id");
+        HostVO host = findNuageVspHost(nuageVspDevice.getHostId());
+        if (!auditDomainsOnVsp(host, false, true)) {
+            return false;
+        }
+
+        String nuageVspCmsId = findNuageVspCmsIdForDevice(nuageVspDevice.getId(), cmsIdConfig);
+        SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(SyncType.UNREGISTER, nuageVspCmsId);
+        SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd);
+        if (answer != null && answer.getSuccess()) {
+            String currentValue = cmsIdConfig.getValue();
+            String newValue = currentValue.replace(nuageVspDevice.getId() + ":" + answer.getNuageVspCmsId(), "");
+            if (!Strings.isNullOrEmpty(newValue) && newValue.startsWith(";")) {
+                newValue = newValue.substring(1);
+            }
+            _configDao.update("nuagevsp.cms.id", newValue);
+        } else {
+            return false;
+        }
+
         HostVO nuageHost = _hostDao.findById(nuageVspDevice.getHostId());
         Long hostId = nuageHost.getId();
 
@@ -285,60 +528,331 @@ public class NuageVspManagerImpl extends ManagerBase implements NuageVspManager,
         return responseList;
     }
 
-    @Override
-    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
-        try {
-            initNuageScheduledTasks();
-        } catch (Exception ce) {
-            s_logger.warn("Failed to load NuageVsp configuration properties. Check if the NuageVsp properties are configured correctly");
+    private void registerNewNuageVspDevice(ConfigurationVO currentConfig, String registeredNuageVspDevice) {
+        if (currentConfig == null) {
+            ConfigKey<String> configKey = new ConfigKey<String>("Advanced", String.class, "nuagevsp.cms.id", registeredNuageVspDevice,
+                    "<ACS Nuage VSP Device ID>:<Allocated VSD CMS ID> - Do not edit", false);
+            ConfigurationVO configuration = new ConfigurationVO("management-server", configKey);
+            _configDao.persist(configuration);
+        } else {
+            String newValue;
+            String currentValue = currentConfig.getValue();
+            if (!Strings.isNullOrEmpty(currentValue)) {
+                newValue = currentValue + ";" + registeredNuageVspDevice;
+            } else {
+                newValue = registeredNuageVspDevice;
+            }
+            _configDao.update("nuagevsp.cms.id", newValue);
         }
-        return true;
     }
 
-    private void initNuageScheduledTasks() {
-        Integer numOfSyncThreads = Integer.valueOf(_configDao.getValue(NuageVspManager.NuageVspSyncWorkers.key()));
-        Integer syncUpIntervalInMinutes = Integer.valueOf(_configDao.getValue(NuageVspManager.NuageVspSyncInterval.key()));
-
-        if (numOfSyncThreads != null && syncUpIntervalInMinutes != null) {
-            ThreadFactory threadFactory = new ThreadFactory() {
-                public Thread newThread(Runnable runnable) {
-                    Thread thread = new Thread(runnable, "Nuage Vsp sync task");
-                    if (thread.isDaemon())
-                        thread.setDaemon(false);
-                    if (thread.getPriority() != Thread.NORM_PRIORITY)
-                        thread.setPriority(Thread.NORM_PRIORITY);
-                    return thread;
+    private void auditHost(HostVO host) {
+        _hostDao.loadDetails(host);
+
+        boolean validateDomains = true;
+        List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listByHost(host.getId());
+        if (!CollectionUtils.isEmpty(nuageVspDevices)) {
+            for (NuageVspDeviceVO nuageVspDevice : nuageVspDevices) {
+                ConfigurationVO cmsIdConfig = _configDao.findByName("nuagevsp.cms.id");
+                String nuageVspCmsId = findNuageVspCmsIdForDevice(nuageVspDevice.getId(), cmsIdConfig);
+                SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(SyncType.AUDIT, nuageVspCmsId);
+                SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd);
+
+                if (answer != null && !answer.getSuccess()) {
+                    s_logger.error("Nuage VSP Device with ID " + nuageVspDevice.getId() + " is configured with an unknown CMS ID!");
+                    validateDomains = false;
+                } else if (answer != null && answer.getSyncType() == SyncType.REGISTER) {
+                    registerNewNuageVspDevice(cmsIdConfig, nuageVspDevice.getId() + ":" + answer.getNuageVspCmsId());
                 }
-            };
-            scheduler = Executors.newScheduledThreadPool(numOfSyncThreads, threadFactory);
-            scheduler.scheduleWithFixedDelay(new NuageVspSyncTask("FLOATING_IP"), ONE_MINUTE_MULTIPLIER * 15, ONE_MINUTE_MULTIPLIER * syncUpIntervalInMinutes,
-                    TimeUnit.MILLISECONDS);
-            scheduler.scheduleWithFixedDelay(new NuageVspSyncTask("ENTERPRISE_NTWK_MACRO"), ONE_MINUTE_MULTIPLIER * 15, ONE_MINUTE_MULTIPLIER * syncUpIntervalInMinutes,
-                    TimeUnit.MILLISECONDS);
-            scheduler
-                    .scheduleWithFixedDelay(new NuageVspSyncTask("ENTERPRISE"), ONE_MINUTE_MULTIPLIER * 15, ONE_MINUTE_MULTIPLIER * syncUpIntervalInMinutes, TimeUnit.MILLISECONDS);
-        } else {
-            s_logger.warn("NuageVsp configuration for syncWorkers=" + numOfSyncThreads + " syncInterval=" + syncUpIntervalInMinutes
-                    + " could not be read properly. So, check if the properties are configured properly in global properties");
+            }
+        }
+
+        if (validateDomains) {
+            auditDomainsOnVsp(host, true, false);
         }
     }
 
-    public class NuageVspSyncTask implements Runnable {
+    private boolean auditDomainsOnVsp(HostVO host, boolean add, boolean remove) {
+        List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listByHost(host.getId());
+        if (CollectionUtils.isEmpty(nuageVspDevices)) {
+            return true;
+        }
 
-        private String nuageVspEntity;
+        _hostDao.loadDetails(host);
+        List<DomainVO> allDomains = _domainDao.listAll();
+        for (DomainVO domain : allDomains) {
+            SyncDomainCommand cmd = new SyncDomainCommand(domain.getUuid(), domain.getName(), domain.getPath(), add, remove);
+            SyncDomainAnswer answer = (SyncDomainAnswer) _agentMgr.easySend(host.getId(), cmd);
+            return answer.getSuccess();
+        }
+        return true;
+    }
+
+    private String findNuageVspCmsIdForDevice(long deviceId, ConfigurationVO cmsIdConfig) {
+        String configValue = cmsIdConfig.getValue();
+        if (!Strings.isNullOrEmpty(configValue)) {
+            String[] configuredNuageVspDevices = configValue.split(";");
+            for (String configuredNuageVspDevice : configuredNuageVspDevices) {
+                if (configuredNuageVspDevice.startsWith(deviceId + ":")) {
+                    String[] split = configuredNuageVspDevice.split(":");
+                    if (split.length != 2 || (split.length > 1 && Strings.isNullOrEmpty(split[1]))) {
+                        throw new IllegalArgumentException("The configured CMS ID for Nuage VSP device " + deviceId + " is in an incorrect format");
+                    }
+                    return split[1];
+                }
+            }
+        }
+        return null;
+    }
+
+    public List<String> getDnsDetails(Network network) {
+        Boolean configureDns = Boolean.valueOf(_configDao.getValue(NuageVspManager.NuageVspConfigDns.key()));
+        if (!configureDns) {
+            return Lists.newArrayList();
+        }
 
-        public NuageVspSyncTask(String nuageVspEntity) {
-            this.nuageVspEntity = nuageVspEntity;
+        Boolean configureExternalDns = Boolean.valueOf(_configDao.getValue(NuageVspManager.NuageVspDnsExternal.key()));
+        DataCenterVO dc = _dataCenterDao.findById(network.getDataCenterId());
+        List<String> dnsServers = new ArrayList<String>();
+        if (configureExternalDns) {
+            if (!Strings.isNullOrEmpty(dc.getDns1())) {
+                dnsServers.add(dc.getDns1());
+            }
+            if (!Strings.isNullOrEmpty(dc.getDns2())) {
+                dnsServers.add(dc.getDns2());
+            }
+        } else {
+            if (!Strings.isNullOrEmpty(dc.getInternalDns1())) {
+                dnsServers.add(dc.getInternalDns1());
+            }
+            if (!Strings.isNullOrEmpty(dc.getInternalDns2())) {
+                dnsServers.add(dc.getInternalDns2());
+            }
         }
+        return dnsServers;
+    }
 
-        public String getNuageVspEntity() {
-            return nuageVspEntity;
+    public List<String> getGatewaySystemIds() {
+        String gatewaySystemIds = String.valueOf(_configDao.getValue(NuageVspManager.NuageVspConfigGateway.key()));
+        if (!Strings.isNullOrEmpty(gatewaySystemIds)) {
+            return Lists.newArrayList(gatewaySystemIds.split(","));
         }
+        return Lists.newArrayList();
+    }
 
-        @Override
-        public void run() {
-            nuageVspSync.syncWithNuageVsp(nuageVspEntity);
+    @Override
+    public boolean preStateTransitionEvent(Status oldState, Status.Event event, Status newState, Host host, boolean status, Object opaque) {
+        return true;
+    }
+
+    @Override
+    public boolean postStateTransitionEvent(StateMachine2.Transition<Status, Status.Event> transition, Host vo, boolean status, Object opaque) {
+        // Whenever a Nuage VSP Host comes up, check if all CS domains are present and check if the CMS ID is valid
+        if (transition.getToState() == Status.Up && vo instanceof HostVO) {
+            auditHost((HostVO) vo);
         }
+        return true;
+    }
+
+    @Override
+    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
+        initMessageBusListeners();
+        initNuageVspResourceListeners();
+        initNuageNetworkOffering();
+        initNuageVspVpcOffering();
+        Status.getStateMachine().registerListener(this);
+        return true;
+    }
+
+    @DB
+    private void initMessageBusListeners() {
+        // Create corresponding enterprise and profile in VSP when creating a CS Domain
+        _messageBus.subscribe(DomainManager.MESSAGE_ADD_DOMAIN_EVENT, new MessageSubscriber() {
+            @Override
+            public void onPublishMessage(String senderAddress, String subject, Object args) {
+                Long domainId = (Long) args;
+                Domain domain = _domainDao.findById(domainId);
+
+                try {
+                    _domainDao.acquireInLockTable(domain.getId());
+
+                    List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listAll();
+                    for (NuageVspDeviceVO nuageVspDevice : nuageVspDevices) {
+                        HostVO host = findNuageVspHost(nuageVspDevice.getHostId());
+                        SyncDomainCommand cmd = new SyncDomainCommand(domain.getUuid(), domain.getName(), domain.getPath(), true, false);
+                        _agentMgr.easySend(host.getId(), cmd);
+                    }
+                } finally {
+                    _domainDao.releaseFromLockTable(domain.getId());
+                }
+            }
+        });
+
+        // Delete corresponding enterprise and profile in VSP when deleting a CS Domain
+        _messageBus.subscribe(DomainManager.MESSAGE_REMOVE_DOMAIN_EVENT, new MessageSubscriber() {
+            @Override
+            public void onPublishMessage(String senderAddress, String subject, Object args) {
+                DomainVO domain = (DomainVO) args;
+                List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listAll();
+                for (NuageVspDeviceVO nuageVspDevice : nuageVspDevices) {
+                    HostVO host = findNuageVspHost(nuageVspDevice.getHostId());
+                    SyncDomainCommand cmd = new SyncDomainCommand(domain.getUuid(), domain.getName(), domain.getPath(), false, true);
+                    _agentMgr.easySend(host.getId(), cmd);
+                }
+            }
+        });
+    }
+
+    @DB
+    private void initNuageVspResourceListeners() {
+        _agentMgr.registerForHostEvents(new Listener() {
+            @Override
+            public boolean processAnswers(long agentId, long seq, Answer[] answers) {
+                return true;
+            }
+
+            @Override
+            public boolean processCommands(long agentId, long seq, Command[] commands) {
+                if (commands != null && commands.length == 1) {
+                    Command command = commands[0];
+                    if (command instanceof PingNuageVspCommand) {
+                        PingNuageVspCommand pingNuageVspCommand = (PingNuageVspCommand) command;
+                        if (pingNuageVspCommand.shouldAudit()) {
+                            Host host = _hostDao.findById(pingNuageVspCommand.getHostId());
+                            auditHost((HostVO) host);
+                        }
+                    }
+                }
+                return true;
+            }
+
+            @Override
+            public AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd) {
+                return null;
+            }
+
+            @Override
+            public void processConnect(Host host, StartupCommand cmd, boolean forRebalance) throws ConnectionException {
+
+            }
+
+            @Override
+            public boolean processDisconnect(long agentId, Status state) {
+                return true;
+            }
+
+            @Override
+            public boolean isRecurring() {
+                return false;
+            }
+
+            @Override
+            public int getTimeout() {
+                return 0;
+            }
+
+            @Override
+            public boolean processTimeout(long agentId, long seq) {
+                return true;
+            }
+        }, false, true, false);
+    }
+
+    @DB
+    private void initNuageNetworkOffering() {
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                NetworkOffering sharedNetworkOfferingWithSG = _networkOfferingDao.findByUniqueName(nuageVspSharedNetworkOfferingWithSGServiceName);
+                if (sharedNetworkOfferingWithSG == null) {
+                    NetworkOfferingVO defaultNuageVspSharedSGNetworkOffering =
+                            new NetworkOfferingVO(nuageVspSharedNetworkOfferingWithSGServiceName, "Offering for NuageVsp Shared Security group enabled networks",
+                                    Networks.TrafficType.Guest, false, false, null, null, true, NetworkOffering.Availability.Optional, null, Network.GuestType.Shared, true, true, false, false, false);
+
+                    defaultNuageVspSharedSGNetworkOffering.setState(NetworkOffering.State.Enabled);
+                    defaultNuageVspSharedSGNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultNuageVspSharedSGNetworkOffering);
+
+                    Map<Network.Service, Network.Provider> defaultNuageVspSharedSGNetworkOfferingProviders = new HashMap<>();
+                    defaultNuageVspSharedSGNetworkOfferingProviders.put(Network.Service.Dhcp, Network.Provider.NuageVsp);
+                    defaultNuageVspSharedSGNetworkOfferingProviders.put(Network.Service.SecurityGroup, Network.Provider.NuageVsp);
+                    defaultNuageVspSharedSGNetworkOfferingProviders.put(Network.Service.Connectivity, Network.Provider.NuageVsp);
+
+                    for (Network.Service service : defaultNuageVspSharedSGNetworkOfferingProviders.keySet()) {
+                        NetworkOfferingServiceMapVO offService =
+                                new NetworkOfferingServiceMapVO(defaultNuageVspSharedSGNetworkOffering.getId(), service, defaultNuageVspSharedSGNetworkOfferingProviders.get(service));
+                        _networkOfferingServiceMapDao.persist(offService);
+                        if (s_logger.isTraceEnabled()) {
+                            s_logger.trace("Added service for the NuageVsp network offering: " + offService);
+                        }
+                    }
+                }
+            }
+        });
+    }
+
+    @DB
+    private void initNuageVspVpcOffering() {
+        //configure default Nuage VSP vpc offering
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                if (_vpcOffDao.findByUniqueName(nuageVPCOfferingName) == null) {
+                    if (s_logger.isDebugEnabled()) {
+                        s_logger.debug("Creating default Nuage VPC offering " + nuageVPCOfferingName);
+                    }
+
+                    Map<Network.Service, Set<Network.Provider>> svcProviderMap = Maps.newHashMap(NUAGE_VSP_VPC_SERVICE_MAP);
+                    Set<Network.Provider> userDataProviders = Collections.singleton(Network.Provider.VPCVirtualRouter);
+                    svcProviderMap.put(Network.Service.UserData, userDataProviders);
+
+                    createVpcOffering(nuageVPCOfferingName, nuageVPCOfferingDisplayText, svcProviderMap, true, VpcOffering.State.Enabled, null);
+                }
+            }
+        });
+    }
+
+    @DB
+    protected VpcOffering createVpcOffering(final String name, final String displayText, final Map<Network.Service, Set<Network.Provider>> svcProviderMap, final boolean isDefault,
+                                            final VpcOffering.State state, final Long serviceOfferingId) {
+        return Transaction.execute(new TransactionCallback<VpcOffering>() {
+            @Override
+            public VpcOffering doInTransaction(TransactionStatus status) {
+                // create vpc offering object
+                VpcOfferingVO offering = new VpcOfferingVO(name, displayText, isDefault, serviceOfferingId, false, false);
+
+                if (state != null) {
+                    offering.setState(state);
+                }
+                if (s_logger.isDebugEnabled()) {
+                    s_logger.debug("Adding vpc offering " + offering);
+                }
+                offering = _vpcOffDao.persist(offering);
+                // populate services and providers
+                if (svcProviderMap != null) {
+                    for (Network.Service service : svcProviderMap.keySet()) {
+                        Set<Network.Provider> providers = svcProviderMap.get(service);
+                        if (providers != null && !providers.isEmpty()) {
+                            for (Network.Provider provider : providers) {
+                                VpcOfferingServiceMapVO offService = new VpcOfferingServiceMapVO(offering.getId(), service, provider);
+                                _vpcOffSvcMapDao.persist(offService);
+                                if (s_logger.isTraceEnabled()) {
+                                    s_logger.trace("Added service for the vpc offering: " + offService + " with provider " + provider.getName());
+                                }
+                            }
+                        } else {
+                            throw new InvalidParameterValueException("Provider is missing for the VPC offering service " + service.getName());
+                        }
+                    }
+                }
+                return offering;
+            }
+        });
+    }
+
+    private HostVO findNuageVspHost(long hostId) {
+        HostVO host = _hostDao.findById(hostId);
+        _hostDao.loadDetails(host);
+        return host;
     }
 
     @Override
@@ -348,6 +862,6 @@ public class NuageVspManagerImpl extends ManagerBase implements NuageVspManager,
 
     @Override
     public ConfigKey<?>[] getConfigKeys() {
-        return new ConfigKey<?>[] {NuageVspSyncWorkers, NuageVspSyncInterval};
+        return Arrays.copyOf(NUAGE_VSP_CONFIG_KEYS, NUAGE_VSP_CONFIG_KEYS.length);
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/645f8758/plugins/network-elements/nuage-vsp/src/com/cloud/network/resource/NuageVspResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nuage-vsp/src/com/cloud/network/resource/NuageVspResource.java b/plugins/network-elements/nuage-vsp/src/com/cloud/network/resource/NuageVspResource.java
index 65c8ae9..c89ea15 100644
--- a/plugins/network-elements/nuage-vsp/src/com/cloud/network/resource/NuageVspResource.java
+++ b/plugins/network-elements/nuage-vsp/src/com/cloud/network/resource/NuageVspResource.java
@@ -19,131 +19,148 @@
 
 package com.cloud.network.resource;
 
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-import javax.naming.ConfigurationException;
-
-import net.nuage.vsp.acs.NuageVspPluginClientLoader;
-import net.nuage.vsp.acs.client.NuageVspApiClient;
-import net.nuage.vsp.acs.client.NuageVspElementClient;
-import net.nuage.vsp.acs.client.NuageVspGuruClient;
-import net.nuage.vsp.acs.client.NuageVspSyncClient;
-
-import org.apache.commons.codec.binary.Base64;
-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.MaintainAnswer;
 import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.PingCommand;
+import com.cloud.agent.api.PingNuageVspCommand;
 import com.cloud.agent.api.ReadyAnswer;
 import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupVspCommand;
 import com.cloud.agent.api.VspResourceAnswer;
 import com.cloud.agent.api.VspResourceCommand;
-import com.cloud.agent.api.element.ApplyAclRuleVspAnswer;
 import com.cloud.agent.api.element.ApplyAclRuleVspCommand;
-import com.cloud.agent.api.element.ApplyStaticNatVspAnswer;
 import com.cloud.agent.api.element.ApplyStaticNatVspCommand;
-import com.cloud.agent.api.element.ShutDownVpcVspAnswer;
+import com.cloud.agent.api.element.ImplementVspCommand;
 import com.cloud.agent.api.element.ShutDownVpcVspCommand;
-import com.cloud.agent.api.guru.DeallocateVmVspAnswer;
 import com.cloud.agent.api.guru.DeallocateVmVspCommand;
-import com.cloud.agent.api.guru.ImplementNetworkVspAnswer;
 import com.cloud.agent.api.guru.ImplementNetworkVspCommand;
-import com.cloud.agent.api.guru.ReleaseVmVspAnswer;
-import com.cloud.agent.api.guru.ReleaseVmVspCommand;
-import com.cloud.agent.api.guru.ReserveVmInterfaceVspAnswer;
 import com.cloud.agent.api.guru.ReserveVmInterfaceVspCommand;
-import com.cloud.agent.api.guru.TrashNetworkVspAnswer;
 import com.cloud.agent.api.guru.TrashNetworkVspCommand;
-import com.cloud.agent.api.sync.SyncVspAnswer;
+import com.cloud.agent.api.manager.GetClientDefaultsAnswer;
+import com.cloud.agent.api.manager.GetClientDefaultsCommand;
+import com.cloud.agent.api.manager.SupportedApiVersionCommand;
+import com.cloud.agent.api.sync.SyncDomainAnswer;
+import com.cloud.agent.api.sync.SyncDomainCommand;
+import com.cloud.agent.api.sync.SyncNuageVspCmsIdAnswer;
+import com.cloud.agent.api.sync.SyncNuageVspCmsIdCommand;
 import com.cloud.agent.api.sync.SyncVspCommand;
 import com.cloud.host.Host;
 import com.cloud.resource.ServerResource;
+import com.cloud.utils.StringUtils;
 import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.exception.CloudRuntimeException;
+import com.google.common.base.Strings;
+import net.nuage.vsp.acs.NuageVspPluginClientLoader;
+import net.nuage.vsp.acs.client.NuageVspApiClient;
+import net.nuage.vsp.acs.client.NuageVspElementClient;
+import net.nuage.vsp.acs.client.NuageVspGuruClient;
+import net.nuage.vsp.acs.client.NuageVspManagerClient;
+import net.nuage.vsp.acs.client.NuageVspSyncClient;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.log4j.Logger;
+
+import javax.naming.ConfigurationException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ExecutionException;
+import java.util.regex.Pattern;
+
+import static com.cloud.agent.api.sync.SyncNuageVspCmsIdCommand.SyncType;
 
 public class NuageVspResource extends ManagerBase implements ServerResource {
     private static final Logger s_logger = Logger.getLogger(NuageVspResource.class);
 
+    private static final String NAME = "name";
+    private static final String GUID = "guid";
+    private static final String ZONE_ID = "zoneid";
+    private static final String HOST_NAME = "hostname";
+    private static final String CMS_USER = "cmsuser";
+    private static final String CMS_USER_PASSWORD = "cmsuserpass";
+    private static final String PORT = "port";
+    private static final String API_VERSION = "apiversion";
+    private static final String API_RELATIVE_PATH = "apirelativepath";
+    private static final String RETRY_COUNT = "retrycount";
+    private static final String RETRY_INTERVAL = "retryinterval";
+    private static final String NUAGE_VSP_CMS_ID = "nuagevspcmsid";
+
     private String _name;
     private String _guid;
     private String _zoneId;
     private String[] _cmsUserInfo;
+    private String _hostName;
     private String _relativePath;
     private int _numRetries;
     private int _retryInterval;
+    private String _nuageVspCmsId;
+    private boolean _shouldAudit = true;
 
     protected NuageVspApiClient _nuageVspApiClient;
     protected NuageVspGuruClient _nuageVspGuruClient;
     protected NuageVspElementClient _nuageVspElementClient;
     protected NuageVspSyncClient _nuageVspSyncClient;
+    protected NuageVspManagerClient _nuageVspManagerClient;
     protected boolean _isNuageVspClientLoaded;
 
     private static final String CMS_USER_ENTEPRISE_NAME = "CSP";
     private static final String NUAGE_VSP_PLUGIN_ERROR_MESSAGE = "Nuage Vsp plugin client is not installed";
-    private static final String NUAGE_PLUGIN_CLIENT_JAR_FILE = "/usr/share/nuagevsp/lib/nuage-vsp-acs-client.jar";
-    private static final String NUAGE_VSP_API_CLIENT_IMPL = "net.nuage.vsp.acs.client.impl.NuageVspApiClientImpl";
-    private static final String NUAGE_VSP_SYNC_CLIENT_IMPL = "net.nuage.vsp.acs.client.impl.NuageVspSyncClientImpl";
-    private static final String NUAGE_VSP_ELEMENT_CLIENT_IMPL = "net.nuage.vsp.acs.client.impl.NuageVspElementClientImpl";
-    private static final String NUAGE_VSP_GURU_CLIENT_IMPL = "net.nuage.vsp.acs.client.impl.NuageVspGuruClientImpl";
 
     @Override
     public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
 
-        _name = (String)params.get("name");
+        _name = (String)params.get(NAME);
         if (_name == null) {
             throw new ConfigurationException("Unable to find name");
         }
 
-        _guid = (String)params.get("guid");
+        _guid = (String)params.get(GUID);
         if (_guid == null) {
             throw new ConfigurationException("Unable to find the guid");
         }
 
-        _zoneId = (String)params.get("zoneId");
+        _zoneId = (String)params.get(ZONE_ID);
         if (_zoneId == null) {
             throw new ConfigurationException("Unable to find zone");
         }
 
-        String hostname = (String)params.get("hostname");
-        if (hostname == null) {
+        _hostName = (String)params.get(HOST_NAME);
+        if (Strings.isNullOrEmpty(_hostName)) {
             throw new ConfigurationException("Unable to find hostname");
         }
 
-        String cmsUser = (String)params.get("cmsuser");
-        if (cmsUser == null) {
+        String cmsUser = (String)params.get(CMS_USER);
+        if (Strings.isNullOrEmpty(cmsUser)) {
             throw new ConfigurationException("Unable to find CMS username");
         }
 
-        String cmsUserPassBase64 = (String)params.get("cmsuserpass");
-        if (cmsUserPassBase64 == null) {
+        String cmsUserPassBase64 = (String)params.get(CMS_USER_PASSWORD);
+        if (Strings.isNullOrEmpty(cmsUserPassBase64)) {
             throw new ConfigurationException("Unable to find CMS password");
         }
 
-        String port = (String)params.get("port");
-        if (port == null) {
+        String port = (String)params.get(PORT);
+        if (Strings.isNullOrEmpty(port)) {
             throw new ConfigurationException("Unable to find port");
         }
 
-        String apiRelativePath = (String)params.get("apirelativepath");
-        if ((apiRelativePath != null) && (!apiRelativePath.isEmpty())) {
-            String apiVersion = apiRelativePath.substring(apiRelativePath.lastIndexOf('/') + 1);
-            if (!Pattern.matches("v\\d+_\\d+", apiVersion)) {
-                throw new ConfigurationException("Incorrect API version");
-            }
-        } else {
+        String apiVersion = (String)params.get(API_VERSION);
+        if (Strings.isNullOrEmpty(apiVersion)) {
             throw new ConfigurationException("Unable to find API version");
+        } else if (!Pattern.matches("v\\d+_\\d+", apiVersion)) {
+            throw new ConfigurationException("Incorrect API version");
+        }
+
+        String apiRelativePath = (String)params.get(API_RELATIVE_PATH);
+        if (Strings.isNullOrEmpty(apiRelativePath) || !apiRelativePath.contains(apiVersion)) {
+            throw new ConfigurationException("Unable to find API version in relative path");
         }
 
-        String retryCount = (String)params.get("retrycount");
-        if ((retryCount != null) && (!retryCount.isEmpty())) {
+        String retryCount = (String)params.get(RETRY_COUNT);
+        if (!Strings.isNullOrEmpty(retryCount)) {
             try {
                 _numRetries = Integer.parseInt(retryCount);
             } catch (NumberFormatException ex) {
@@ -156,8 +173,8 @@ public class NuageVspResource extends ManagerBase implements ServerResource {
             throw new ConfigurationException("Unable to find number of retries");
         }
 
-        String retryInterval = (String)params.get("retryinterval");
-        if ((retryInterval != null) && (!retryInterval.isEmpty())) {
+        String retryInterval = (String)params.get(RETRY_INTERVAL);
+        if (!Strings.isNullOrEmpty(retryInterval)) {
             try {
                 _retryInterval = Integer.parseInt(retryInterval);
             } catch (NumberFormatException ex) {
@@ -170,57 +187,45 @@ public class NuageVspResource extends ManagerBase implements ServerResource {
             throw new ConfigurationException("Unable to find retry interval");
         }
 
-        _relativePath = new StringBuffer().append("https://").append(hostname).append(":").append(port).append(apiRelativePath).toString();
+        _relativePath = new StringBuffer().append("https://").append(_hostName).append(":").append(port).append(apiRelativePath).toString();
 
         String cmsUserPass = org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64.decodeBase64(cmsUserPassBase64));
         _cmsUserInfo = new String[] {CMS_USER_ENTEPRISE_NAME, cmsUser, cmsUserPass};
 
-        try {
-            loadNuageClient();
-        } catch (Exception e) {
-            throw new CloudRuntimeException("Failed to login to Nuage VSD on " + name + " as user " + cmsUser, e);
-        }
+        _nuageVspCmsId = (String)params.get(NUAGE_VSP_CMS_ID);
+
+        loadNuageClient();
 
         try {
             login();
-        } catch (Exception e) {
-            s_logger.error("Failed to login to Nuage VSD on " + name + " as user " + cmsUser + " Exception " + e.getMessage());
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failed to login to Nuage VSD on " + name + " as user " + cmsUser, e);
             throw new CloudRuntimeException("Failed to login to Nuage VSD on " + name + " as user " + cmsUser, e);
         }
 
         return true;
     }
 
-    protected void login() throws Exception {
+    protected void login() throws ConfigurationException, ExecutionException {
         isNuageVspApiLoaded();
         _nuageVspApiClient.login();
     }
 
-    protected <A extends NuageVspApiClient, B extends NuageVspElementClient, C extends NuageVspSyncClient, D extends NuageVspGuruClient> void loadNuageClient() throws Exception {
+    protected <A extends NuageVspApiClient, B extends NuageVspElementClient, C extends NuageVspSyncClient, D extends NuageVspGuruClient> void loadNuageClient() {
 
         try {
-            ClassLoader loader = NuageVspPluginClientLoader.getClassLoader(NUAGE_PLUGIN_CLIENT_JAR_FILE);
-
-            Class<?> nuageVspApiClientClass = Class.forName(NUAGE_VSP_API_CLIENT_IMPL, true, loader);
-            Class<?> nuageVspSyncClientClass = Class.forName(NUAGE_VSP_SYNC_CLIENT_IMPL, true, loader);
-            Class<?> nuageVspGuruClientClass = Class.forName(NUAGE_VSP_GURU_CLIENT_IMPL, true, loader);
-            Class<?> nuageVspElementClientClass = Class.forName(NUAGE_VSP_ELEMENT_CLIENT_IMPL, true, loader);
-
-            //Instantiate the instances
-            _nuageVspApiClient = (NuageVspApiClient)nuageVspApiClientClass.newInstance();
-            _nuageVspApiClient.setNuageVspHost(_relativePath, _cmsUserInfo, _numRetries, _retryInterval);
-            _nuageVspSyncClient = (NuageVspSyncClient)nuageVspSyncClientClass.newInstance();
-            _nuageVspSyncClient.setNuageVspApiClient(_nuageVspApiClient);
-            _nuageVspGuruClient = (NuageVspGuruClient)nuageVspGuruClientClass.newInstance();
-            _nuageVspGuruClient.setNuageVspApiClient(_nuageVspApiClient);
-            _nuageVspElementClient = (NuageVspElementClient)nuageVspElementClientClass.newInstance();
-            _nuageVspElementClient.setNuageVspApiClient(_nuageVspApiClient);
+            NuageVspPluginClientLoader clientLoader = NuageVspPluginClientLoader.getClientLoader(_relativePath, _cmsUserInfo, _numRetries, _retryInterval, _nuageVspCmsId);
+            _nuageVspApiClient = clientLoader.getNuageVspApiClient();
+            _nuageVspSyncClient = clientLoader.getNuageVspSyncClient();
+            _nuageVspGuruClient = clientLoader.getNuageVspGuruClient();
+            _nuageVspElementClient = clientLoader.getNuageVspElementClient();
+            _nuageVspManagerClient = clientLoader.getNuageVspManagerClient();
             _isNuageVspClientLoaded = true;
-        } catch (Exception e) {
+        } catch (ConfigurationException e) {
             _isNuageVspClientLoaded = false;
             String errorMessage = "Nuage Vsp Plugin client is not yet installed. Please install NuageVsp plugin client to use NuageVsp plugin in Cloudstack. ";
-            s_logger.warn(errorMessage + e.getMessage());
-            throw new Exception(errorMessage);
+            s_logger.error(errorMessage, e);
+            throw new CloudRuntimeException(errorMessage, e);
         }
 
     }
@@ -260,17 +265,26 @@ public class NuageVspResource extends ManagerBase implements ServerResource {
 
     @Override
     public PingCommand getCurrentStatus(long id) {
-        if ((_relativePath == null) || (_relativePath.isEmpty()) || (_cmsUserInfo == null) || (_cmsUserInfo.length == 0)) {
-            s_logger.error("Failed to ping to Nuage VSD");
+        if (_relativePath == null || _relativePath.isEmpty()) {
+            s_logger.error("Refusing to ping Nuage VSD because the resource configuration is missing the relative path information");
+            _shouldAudit = true;
+            return null;
+        }
+        if (_cmsUserInfo == null || _cmsUserInfo.length < 2) {
+            s_logger.error("Refusing to ping Nuage VSD because the resource configuration is missing the CMS user information");
+            _shouldAudit = true;
             return null;
         }
         try {
             login();
-        } catch (Exception e) {
-            s_logger.error("Failed to ping to Nuage VSD on " + _name + " as user " + _cmsUserInfo[1] + " Exception " + e.getMessage());
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failed to ping to Nuage VSD on " + _name + " as user " + _cmsUserInfo[1], e);
+            _shouldAudit = true;
             return null;
         }
-        return new PingCommand(Host.Type.L2Networking, id);
+        PingNuageVspCommand pingNuageVspCommand = new PingNuageVspCommand(Host.Type.L2Networking, id, _shouldAudit);
+        _shouldAudit = false;
+        return pingNuageVspCommand;
     }
 
     @Override
@@ -287,15 +301,15 @@ public class NuageVspResource extends ManagerBase implements ServerResource {
             return executeRequest((ImplementNetworkVspCommand)cmd);
         } else if (cmd instanceof ReserveVmInterfaceVspCommand) {
             return executeRequest((ReserveVmInterfaceVspCommand)cmd);
-        } else if (cmd instanceof ReleaseVmVspCommand) {
-            return executeRequest((ReleaseVmVspCommand)cmd);
         } else if (cmd instanceof DeallocateVmVspCommand) {
             return executeRequest((DeallocateVmVspCommand)cmd);
         } else if (cmd instanceof TrashNetworkVspCommand) {
             return executeRequest((TrashNetworkVspCommand)cmd);
         }
         //Element commands
-        else if (cmd instanceof ApplyAclRuleVspCommand) {
+        else if (cmd instanceof ImplementVspCommand) {
+            return executeRequest((ImplementVspCommand)cmd);
+        } else if (cmd instanceof ApplyAclRuleVspCommand) {
             return executeRequest((ApplyAclRuleVspCommand)cmd);
         } else if (cmd instanceof ApplyStaticNatVspCommand) {
             return executeRequest((ApplyStaticNatVspCommand)cmd);
@@ -305,8 +319,20 @@ public class NuageVspResource extends ManagerBase implements ServerResource {
         //Sync Commands
         else if (cmd instanceof SyncVspCommand) {
             return executeRequest((SyncVspCommand)cmd);
+        } else if (cmd instanceof SyncNuageVspCmsIdCommand) {
+            return executeRequest((SyncNuageVspCmsIdCommand)cmd);
+        } else if (cmd instanceof SyncDomainCommand) {
+            return executeRequest((SyncDomainCommand)cmd);
+        }
+        //Other commands
+        else if (cmd instanceof GetClientDefaultsCommand) {
+            return executeRequest((GetClientDefaultsCommand)cmd);
+        } else if (cmd instanceof SupportedApiVersionCommand) {
+            return executeRequest((SupportedApiVersionCommand)cmd);
+        }
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("Received unsupported command " + cmd.toString());
         }
-        s_logger.debug("Received unsupported command " + cmd.toString());
         return Answer.createUnsupportedCommandAnswer(cmd);
     }
 
@@ -340,7 +366,8 @@ public class NuageVspResource extends ManagerBase implements ServerResource {
                 return new VspResourceAnswer(cmd, resourceInfo, "Executed Issue Resource command");
             }
             return new VspResourceAnswer(cmd, false, cmd.getRequestType() + " is not yet supported");
-        } catch (Exception e) {
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
             return new VspResourceAnswer(cmd, e);
         }
     }
@@ -349,85 +376,98 @@ public class NuageVspResource extends ManagerBase implements ServerResource {
         try {
             isNuageVspGuruLoaded();
             _nuageVspGuruClient.implement(cmd.getNetworkDomainName(), cmd.getNetworkDomainPath(), cmd.getNetworkDomainUuid(), cmd.getNetworkAccountName(),
-                    cmd.getNetworkAccountUuid(), cmd.getNetworkName(), cmd.getNetworkCidr(), cmd.getNetworkGateway(), cmd.getNetworkUuid(), cmd.isL3Network(), cmd.getVpcName(),
-                    cmd.getVpcUuid(), cmd.isDefaultEgressPolicy(), cmd.getIpAddressRange());
-            return new ImplementNetworkVspAnswer(cmd, true, "Created Nuage VSP network mapping to " + cmd.getNetworkName());
-        } catch (Exception e) {
-            return new ImplementNetworkVspAnswer(cmd, e);
+                    cmd.getNetworkAccountUuid(), cmd.getNetworkName(), cmd.getNetworkCidr(), cmd.getNetworkGateway(), cmd.getNetworkAclId(), cmd.getDnsServers(),
+                    cmd.getGatewaySystemIds(), cmd.isL3Network(), cmd.isVpc(), cmd.isSharedNetwork(), cmd.getNetworkUuid(), cmd.getVpcName(), cmd.getVpcUuid(),
+                    cmd.isDefaultEgressPolicy(), cmd.getIpAddressRange(), cmd.getDomainTemplateName());
+            return new Answer(cmd, true, "Created network mapping to " + cmd.getNetworkName() + " on Nuage VSD " + _hostName);
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new Answer(cmd, e);
         }
     }
 
     private Answer executeRequest(ReserveVmInterfaceVspCommand cmd) {
         try {
             isNuageVspGuruLoaded();
-            List<Map<String, String>> vmInterfaceInfo = _nuageVspGuruClient.reserve(cmd.getNicUuid(), cmd.getNicMacAddress(), cmd.getNetworkUuid(), cmd.isL3Network(),
-                    cmd.getVpcUuid(), cmd.getNetworkDomainUuid(), cmd.getNetworksAccountUuid(), cmd.isDomainRouter(), cmd._getDomainRouterIp(), cmd._getVmInstanceName(),
-                    cmd._getVmUuid());
-            return new ReserveVmInterfaceVspAnswer(cmd, vmInterfaceInfo, "Created NIC in VSP that maps to nicUuid" + cmd.getNicUuid());
-        } catch (Exception e) {
-            return new ReserveVmInterfaceVspAnswer(cmd, e);
+            _nuageVspGuruClient.reserve(cmd.getNicUuid(), cmd.getNicMacAddress(), cmd.getNetworkUuid(), cmd.isL3Network(),
+                    cmd.isSharedNetwork(), cmd.getVpcUuid(), cmd.getNetworkDomainUuid(), cmd.getNetworksAccountUuid(), cmd.isDomainRouter(), cmd.getDomainRouterIp(),
+                    cmd.getVmInstanceName(), cmd.getVmUuid(), cmd.useStaticIp(), cmd.getStaticIp(), cmd.getStaticNatIpUuid(), cmd.getStaticNatIpAddress(), cmd.isStaticNatIpAllocated(),
+                    cmd.isOneToOneNat(), cmd.getStaticNatVlanUuid(), cmd.getStaticNatVlanGateway(), cmd.getStaticNatVlanNetmask());
+            return new Answer(cmd, true, "Created NIC that maps to nicUuid" + cmd.getNicUuid() + " on Nuage VSD " + _hostName);
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new Answer(cmd, e);
         }
     }
 
-    private Answer executeRequest(ReleaseVmVspCommand cmd) {
+    private Answer executeRequest(DeallocateVmVspCommand cmd) {
         try {
             isNuageVspGuruLoaded();
-            _nuageVspGuruClient.release(cmd.getNetworkUuid(), cmd.getVmUuid(), cmd.getVmInstanceName());
-            return new ReleaseVmVspAnswer(cmd, true, "VM has been deleted from VSP.");
-        } catch (Exception e) {
-            return new ReleaseVmVspAnswer(cmd, e);
+            _nuageVspGuruClient.deallocate(cmd.getNetworkUuid(), cmd.getNicFromDdUuid(), cmd.getNicMacAddress(), cmd.getNicIp4Address(), cmd.isL3Network(), cmd.isSharedNetwork(),
+                    cmd.getVpcUuid(), cmd.getNetworksDomainUuid(), cmd.getVmInstanceName(), cmd.getVmUuid(), cmd.isExpungingState());
+            return new Answer(cmd, true, "Deallocated VM " + cmd.getVmInstanceName() + " on Nuage VSD " + _hostName);
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new Answer(cmd, e);
         }
     }
 
-    private Answer executeRequest(DeallocateVmVspCommand cmd) {
+    private Answer executeRequest(TrashNetworkVspCommand cmd) {
         try {
             isNuageVspGuruLoaded();
-            _nuageVspGuruClient.deallocate(cmd.getNetworkUuid(), cmd.getNicFrmDdUuid(), cmd.getNicMacAddress(), cmd.getNicIp4Address(), cmd.isL3Network(), cmd.getVpcUuid(),
-                    cmd.getNetworksDomainUuid(), cmd.getVmInstanceName(), cmd.getVmUuid());
-            return new DeallocateVmVspAnswer(cmd, true, "Deallocated VM from Nuage VSP.");
-        } catch (Exception e) {
-            return new DeallocateVmVspAnswer(cmd, e);
+            _nuageVspGuruClient.trash(cmd.getDomainUuid(), cmd.getNetworkUuid(), cmd.isL3Network(), cmd.isSharedNetwork(), cmd.getVpcUuid(), cmd.getDomainTemplateName());
+            return new Answer(cmd, true, "Deleted network mapping to " + cmd.getNetworkUuid() + " on Nuage VSD " + _hostName);
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new Answer(cmd, e);
         }
     }
 
-    private Answer executeRequest(TrashNetworkVspCommand cmd) {
+    private Answer executeRequest(ApplyStaticNatVspCommand cmd) {
         try {
-            isNuageVspGuruLoaded();
-            _nuageVspGuruClient.trash(cmd.getDomainUuid(), cmd.getNetworkUuid(), cmd.isL3Network(), cmd.getVpcUuid());
-            return new TrashNetworkVspAnswer(cmd, true, "Deleted Nuage VSP network mapping to " + cmd.getNetworkUuid());
-        } catch (Exception e) {
-            return new TrashNetworkVspAnswer(cmd, e);
+            isNuageVspElementLoaded();
+            _nuageVspElementClient.applyStaticNats(cmd.getNetworkDomainUuid(), cmd.getNetworkUuid(), cmd.getVpcOrSubnetUuid(), cmd.isL3Network(),
+                    cmd.isVpc(), cmd.getStaticNatDetails());
+            return new Answer(cmd, true, "Applied Static NAT to network mapping " + cmd.getVpcOrSubnetUuid() + " on Nuage VSD " + _hostName);
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new Answer(cmd, e);
         }
     }
 
-    private Answer executeRequest(ApplyStaticNatVspCommand cmd) {
+    private Answer executeRequest(ImplementVspCommand cmd) {
         try {
             isNuageVspElementLoaded();
-            _nuageVspElementClient.applyStaticNats(cmd.getNetworkDomainUuid(), cmd.getVpcOrSubnetUuid(), cmd.isL3Network(), cmd.getStaticNatDetails());
-            return new ApplyStaticNatVspAnswer(cmd, true, "Applied Static NAT to VSP network mapping to " + cmd.getVpcOrSubnetUuid());
-        } catch (Exception e) {
-            return new ApplyStaticNatVspAnswer(cmd, e);
+            boolean success = _nuageVspElementClient.implement(cmd.getNetworkId(), cmd.getNetworkDomainUuid(), cmd.getNetworkUuid(), cmd.getNetworkName(), cmd.getVpcOrSubnetUuid(), cmd.isL2Network(),
+                    cmd.isL3Network(), cmd.isVpc(), cmd.isShared(), cmd.getDomainTemplateName(), cmd.isFirewallServiceSupported(), cmd.getDnsServers(), cmd.getIngressFirewallRules(),
+                    cmd.getEgressFirewallRules(), cmd.getAcsFipUuid(), cmd.isEgressDefaultPolicy());
+            return new Answer(cmd, success, "Implemented network " + cmd.getNetworkUuid() + " on Nuage VSD " + _hostName);
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new Answer(cmd, e);
         }
     }
 
     private Answer executeRequest(ApplyAclRuleVspCommand cmd) {
         try {
             isNuageVspElementLoaded();
-            _nuageVspElementClient.applyAclRules(cmd.getNetworkUuid(), cmd.getNetworkDomainUuid(), cmd.getVpcOrSubnetUuid(), cmd.isL3Network(), cmd.getAclRules(), cmd.isVpc(),
-                    cmd.getNetworkId());
-            return new ApplyAclRuleVspAnswer(cmd, true, "Applied ACL Rule to VSP network mapping to " + cmd.getVpcOrSubnetUuid());
-        } catch (Exception e) {
-            return new ApplyAclRuleVspAnswer(cmd, e);
+            _nuageVspElementClient.applyAclRules(cmd.isNetworkAcl(), cmd.getNetworkUuid(), cmd.getNetworkDomainUuid(), cmd.getVpcOrSubnetUuid(), cmd.getNetworkName(),
+                    cmd.isL2Network(), cmd.getAclRules(), cmd.getNetworkId(), cmd.isEgressDefaultPolicy(), cmd.getAcsIngressAcl(), cmd.isNetworkReset(), cmd.getDomainTemplateName());
+            return new Answer(cmd, true, "Applied ACL Rule to network mapping " + cmd.getVpcOrSubnetUuid() + " on Nuage VSD " + _hostName);
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new Answer(cmd, e);
         }
     }
 
     private Answer executeRequest(ShutDownVpcVspCommand cmd) {
         try {
             isNuageVspElementLoaded();
-            _nuageVspElementClient.shutDownVpc(cmd.getDomainUuid(), cmd.getVpcUuid());
-            return new ShutDownVpcVspAnswer(cmd, true, "Shutdown VPC " + cmd.getVpcUuid());
-        } catch (Exception e) {
-            return new ShutDownVpcVspAnswer(cmd, e);
+            _nuageVspElementClient.shutdownVpc(cmd.getDomainUuid(), cmd.getVpcUuid(), cmd.getDomainTemplateName());
+            return new Answer(cmd, true, "Shutdown VPC " + cmd.getVpcUuid() + " on Nuage VSD " + _hostName);
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new Answer(cmd, e);
         }
     }
 
@@ -435,33 +475,248 @@ public class NuageVspResource extends ManagerBase implements ServerResource {
         try {
             isNuageVspSyncLoaded();
             _nuageVspSyncClient.syncWithNuageVsp(cmd.getNuageVspEntity());
-            return new SyncVspAnswer(cmd, true, "Synced " + cmd.getNuageVspEntity() + " in VSP");
-        } catch (Exception e) {
-            return new SyncVspAnswer(cmd, e);
+            return new Answer(cmd, true, "Synced " + cmd.getNuageVspEntity() + " on Nuage VSD " + _hostName);
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new Answer(cmd, e);
+        }
+    }
+
+    private Answer executeRequest(SyncNuageVspCmsIdCommand cmd) {
+        try {
+            isNuageVspManagerLoaded();
+            if (cmd.getSyncType() == SyncType.AUDIT || cmd.getSyncType() == SyncType.AUDIT_ONLY) {
+                Pair<Boolean, String> answer = _nuageVspManagerClient.auditNuageVspCmsId(cmd.getNuageVspCmsId(), cmd.getSyncType() == SyncType.AUDIT_ONLY);
+                return new SyncNuageVspCmsIdAnswer(answer.getLeft(), answer.getRight(), cmd.getSyncType());
+            } else if (cmd.getSyncType() == SyncType.REGISTER) {
+                String registeredNuageVspCmsId = _nuageVspManagerClient.registerNuageVspCmsId();
+                return new SyncNuageVspCmsIdAnswer(StringUtils.isNotBlank(registeredNuageVspCmsId), registeredNuageVspCmsId, cmd.getSyncType());
+            } else {
+                boolean success = _nuageVspManagerClient.unregisterNuageVspCmsId(cmd.getNuageVspCmsId());
+                return new SyncNuageVspCmsIdAnswer(success, cmd.getNuageVspCmsId(), cmd.getSyncType());
+            }
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new SyncNuageVspCmsIdAnswer(false, null, cmd.getSyncType());
         }
     }
 
-    protected void isNuageVspApiLoaded() throws Exception {
+    private Answer executeRequest(SyncDomainCommand cmd) {
+        try {
+            isNuageVspManagerLoaded();
+            boolean success = _nuageVspManagerClient.syncDomainWithNuageVsp(cmd.getDomainUuid(), cmd.getDomainName(), cmd.getDomainPath(), cmd.isToAdd(), cmd.isToRemove());
+            return new SyncDomainAnswer(success);
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new SyncDomainAnswer(false);
+        }
+    }
+
+    private Answer executeRequest(GetClientDefaultsCommand cmd) {
+        try {
+            isNuageVspManagerLoaded();
+            Map<String, Object> clientDefaults = _nuageVspManagerClient.getClientDefaults();
+            return new GetClientDefaultsAnswer(cmd, clientDefaults);
+        } catch (ExecutionException | ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new GetClientDefaultsAnswer(cmd, e);
+        }
+    }
+
+    private Answer executeRequest(SupportedApiVersionCommand cmd) {
+        try {
+            isNuageVspManagerLoaded();
+            boolean supported = _nuageVspManagerClient.isSupportedApiVersion(cmd.getApiVersion());
+            return new Answer(cmd, supported, "Check if API version " + cmd.getApiVersion() + " is supported");
+        } catch (ConfigurationException e) {
+            s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e);
+            return new Answer(cmd, e);
+        }
+    }
+
+    protected void isNuageVspApiLoaded() throws ConfigurationException {
         if (!_isNuageVspClientLoaded || _nuageVspApiClient == null) {
-            throw new Exception(NUAGE_VSP_PLUGIN_ERROR_MESSAGE);
+            throw new ConfigurationException(NUAGE_VSP_PLUGIN_ERROR_MESSAGE);
         }
     }
 
-    protected void isNuageVspGuruLoaded() throws Exception {
+    protected void isNuageVspGuruLoaded() throws ConfigurationException {
         if (!_isNuageVspClientLoaded || _nuageVspGuruClient == null) {
-            throw new Exception(NUAGE_VSP_PLUGIN_ERROR_MESSAGE);
+            throw new ConfigurationException(NUAGE_VSP_PLUGIN_ERROR_MESSAGE);
         }
     }
 
-    protected void isNuageVspElementLoaded() throws Exception {
+    protected void isNuageVspElementLoaded() throws ConfigurationException {
         if (!_isNuageVspClientLoaded || _nuageVspElementClient == null) {
-            throw new Exception(NUAGE_VSP_PLUGIN_ERROR_MESSAGE);
+            throw new ConfigurationException(NUAGE_VSP_PLUGIN_ERROR_MESSAGE);
         }
     }
 
-    protected void isNuageVspSyncLoaded() throws Exception {
+    protected void isNuageVspSyncLoaded() throws ConfigurationException {
         if (!_isNuageVspClientLoaded || _nuageVspSyncClient == null) {
-            throw new Exception(NUAGE_VSP_PLUGIN_ERROR_MESSAGE);
+            throw new ConfigurationException(NUAGE_VSP_PLUGIN_ERROR_MESSAGE);
+        }
+    }
+
+    protected void isNuageVspManagerLoaded() throws ConfigurationException {
+        if (!_isNuageVspClientLoaded || _nuageVspManagerClient == null) {
+            throw new ConfigurationException(NUAGE_VSP_PLUGIN_ERROR_MESSAGE);
+        }
+    }
+
+    public static class Configuration {
+        private String _name;
+        private String _guid;
+        private String _zoneId;
+        private String _hostName;
+        private String _cmsUser;
+        private String _cmsUserPassword;
+        private String _port;
+        private String _apiVersion;
+        private String _apiRelativePath;
+        private String _retryCount;
+        private String _retryInterval;
+        private String _nuageVspCmsId;
+
+        public String name() {
+            return this._name;
+        }
+
+        public Configuration name(String name) {
+            this._name = name;
+            return this;
+        }
+
+        public String guid() {
+            return this._guid;
+        }
+
+        public Configuration guid(String guid) {
+            this._guid = guid;
+            return this;
+        }
+
+        public String zoneId() {
+            return this._zoneId;
+        }
+
+        public Configuration zoneId(String zoneId) {
+            this._zoneId = zoneId;
+            return this;
+        }
+
+        public String hostName() {
+            return this._hostName;
+        }
+
+        public Configuration hostName(String hostName) {
+            this._hostName = hostName;
+            return this;
+        }
+
+        public String cmsUser() {
+            return this._cmsUser;
+        }
+
+        public Configuration cmsUser(String cmsUser) {
+            this._cmsUser = cmsUser;
+            return this;
+        }
+
+        public String cmsUserPassword() {
+            return this._cmsUserPassword;
+        }
+
+        public Configuration cmsUserPassword(String cmsUserPassword) {
+            this._cmsUserPassword = cmsUserPassword;
+            return this;
+        }
+
+        public String port() {
+            return this._port;
+        }
+
+        public Configuration port(String port) {
+            this._port = port;
+            return this;
+        }
+
+        public String apiVersion() {
+            return this._apiVersion;
+        }
+
+        public Configuration apiVersion(String apiVersion) {
+            this._apiVersion = apiVersion;
+            return this;
+        }
+
+        public String apiRelativePath() {
+            return this._apiRelativePath;
+        }
+
+        public Configuration apiRelativePath(String apiRelativePath) {
+            this._apiRelativePath = apiRelativePath;
+            return this;
+        }
+
+        public String retryCount() {
+            return this._retryCount;
+        }
+
+        public Configuration retryCount(String retryCount) {
+            this._retryCount = retryCount;
+            return this;
+        }
+
+        public String retryInterval() {
+            return this._retryInterval;
+        }
+
+        public Configuration retryInterval(String retryInterval) {
+            this._retryInterval = retryInterval;
+            return this;
+        }
+
+        public String nuageVspCmsId() {
+            return this._nuageVspCmsId;
+        }
+
+        public Configuration nuageVspCmsId(String nuageVspCmsId) {
+            this._nuageVspCmsId = nuageVspCmsId;
+            return this;
+        }
+
+        public Map<String, String> build() {
+            return new HashMap<String, String>() {{
+                if (_name != null) put(NAME, _name);
+                if (_guid != null) put(GUID, _guid);
+                if (_zoneId != null) put(ZONE_ID, _zoneId);
+                if (_hostName != null) put(HOST_NAME, _hostName);
+                if (_cmsUser != null) put(CMS_USER, _cmsUser);
+                if (_cmsUserPassword != null) put(CMS_USER_PASSWORD, _cmsUserPassword);
+                if (_port != null) put(PORT, _port);
+                if (_apiVersion != null) put(API_VERSION, _apiVersion);
+                if (_apiRelativePath != null) put(API_RELATIVE_PATH, _apiRelativePath);
+                if (_retryCount != null) put(RETRY_COUNT, _retryCount);
+                if (_retryInterval != null) put(RETRY_INTERVAL, _retryInterval);
+                if (_nuageVspCmsId != null) put(NUAGE_VSP_CMS_ID, _nuageVspCmsId);
+            }};
+        }
+
+        public static Configuration fromConfiguration(Map<String, String> configuration) {
+            return new Configuration()
+                    .name(configuration.get(NAME))
+                    .guid(configuration.get(GUID))
+                    .zoneId(configuration.get(ZONE_ID))
+                    .hostName(configuration.get(HOST_NAME))
+                    .cmsUser(configuration.get(CMS_USER))
+                    .cmsUserPassword(configuration.get(CMS_USER_PASSWORD))
+                    .port(configuration.get(PORT))
+                    .apiVersion(configuration.get(API_VERSION))
+                    .apiRelativePath(configuration.get(API_RELATIVE_PATH))
+                    .retryCount(configuration.get(RETRY_COUNT))
+                    .retryInterval(configuration.get(RETRY_INTERVAL))
+                    .nuageVspCmsId(configuration.get(NUAGE_VSP_CMS_ID));
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/645f8758/plugins/network-elements/nuage-vsp/src/com/cloud/network/sync/NuageVspSyncImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nuage-vsp/src/com/cloud/network/sync/NuageVspSyncImpl.java b/plugins/network-elements/nuage-vsp/src/com/cloud/network/sync/NuageVspSyncImpl.java
index f3d19c1..9180c17 100644
--- a/plugins/network-elements/nuage-vsp/src/com/cloud/network/sync/NuageVspSyncImpl.java
+++ b/plugins/network-elements/nuage-vsp/src/com/cloud/network/sync/NuageVspSyncImpl.java
@@ -19,20 +19,18 @@
 
 package com.cloud.network.sync;
 
-import java.util.List;
-
-import javax.inject.Inject;
-
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
-
 import com.cloud.agent.AgentManager;
-import com.cloud.agent.api.sync.SyncVspAnswer;
+import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.sync.SyncVspCommand;
 import com.cloud.host.HostVO;
 import com.cloud.host.dao.HostDao;
 import com.cloud.network.NuageVspDeviceVO;
 import com.cloud.network.dao.NuageVspDao;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import javax.inject.Inject;
+import java.util.List;
 
 @Component
 public class NuageVspSyncImpl implements NuageVspSync {
@@ -52,20 +50,15 @@ public class NuageVspSyncImpl implements NuageVspSync {
         //entities
         List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listAll();
         for (NuageVspDeviceVO nuageVspDevice : nuageVspDevices) {
-
-            try {
-                HostVO nuageVspHost = _hostDao.findById(nuageVspDevice.getHostId());
-                _hostDao.loadDetails(nuageVspHost);
-                SyncVspCommand cmd = new SyncVspCommand(nuageVspEntity);
-                SyncVspAnswer answer = (SyncVspAnswer)_agentMgr.easySend(nuageVspHost.getId(), cmd);
-                if (answer == null || !answer.getResult()) {
-                    s_logger.error("SyncNuageVspCommand for Nuage VSP Host " + nuageVspHost.getUuid() + " failed");
-                    if ((null != answer) && (null != answer.getDetails())) {
-                        s_logger.error(answer.getDetails());
-                    }
+            HostVO nuageVspHost = _hostDao.findById(nuageVspDevice.getHostId());
+            _hostDao.loadDetails(nuageVspHost);
+            SyncVspCommand cmd = new SyncVspCommand(nuageVspEntity);
+            Answer answer = _agentMgr.easySend(nuageVspHost.getId(), cmd);
+            if (answer == null || !answer.getResult()) {
+                s_logger.error("SyncNuageVspCommand for Nuage VSP Host " + nuageVspHost.getUuid() + " failed");
+                if ((null != answer) && (null != answer.getDetails())) {
+                    s_logger.error(answer.getDetails());
                 }
-            } catch (Exception e) {
-                s_logger.warn("Failed to clean up " + nuageVspEntity + " in Vsp " + e.getMessage());
             }
         }
     }


Mime
View raw message