cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From yas...@apache.org
Subject [2/2] git commit: updated refs/heads/master to cc2b1c4
Date Wed, 15 Jan 2014 22:26:03 GMT
Contrail plugin fixes -master branch, single commit, no transaction wrappers

Signed-off-by: Sheng Yang <sheng.yang@citrix.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/cc2b1c49
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/cc2b1c49
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/cc2b1c49

Branch: refs/heads/master
Commit: cc2b1c4961244d9c3d8b452f1dcaa6614e56d11a
Parents: 7164fc6
Author: sbalineni <sbalineni@contrailsystems.com>
Authored: Sun Jan 5 23:53:41 2014 +0000
Committer: Sheng Yang <sheng.yang@citrix.com>
Committed: Wed Jan 15 14:11:49 2014 -0800

----------------------------------------------------------------------
 api/src/com/cloud/network/Network.java          |   2 +-
 .../management/ContrailElementImpl.java         |  75 ++++-
 .../contrail/management/ContrailGuru.java       |  27 +-
 .../contrail/management/ContrailManager.java    |  25 +-
 .../management/ContrailManagerImpl.java         | 254 ++++++++++-----
 .../contrail/management/ModelDatabase.java      |  22 +-
 .../contrail/management/ServerDBSyncImpl.java   | 214 ++++++++++++-
 .../management/ServerEventHandlerImpl.java      |  10 -
 .../contrail/management/ServiceManagerImpl.java |  24 +-
 .../contrail/model/NetworkPolicyModel.java      | 305 +++++++++++++++++++
 .../contrail/model/ServiceInstanceModel.java    | 116 +++----
 .../contrail/model/VirtualMachineModel.java     |  38 ++-
 .../contrail/model/VirtualNetworkModel.java     |  84 ++++-
 .../management/ManagementServerMock.java        |   8 +-
 .../management/NetworkProviderTest.java         |   2 +-
 15 files changed, 995 insertions(+), 211 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cc2b1c49/api/src/com/cloud/network/Network.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java
index 2197c2b..62151a4 100644
--- a/api/src/com/cloud/network/Network.java
+++ b/api/src/com/cloud/network/Network.java
@@ -112,7 +112,7 @@ public interface Network extends ControlledEntity, StateObject<Network.State>, I
         private static List<Provider> supportedProviders = new ArrayList<Provider>();
 
         public static final Provider VirtualRouter = new Provider("VirtualRouter", false);
-        public static final Provider JuniperContrail = new Provider("JuniperContrail", false);
+        public static final Provider JuniperContrailRouter = new Provider("JuniperContrailRouter", false);
         public static final Provider JuniperSRX = new Provider("JuniperSRX", true);
         public static final Provider PaloAlto = new Provider("PaloAlto", true);
         public static final Provider F5BigIp = new Provider("F5BigIp", true);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cc2b1c49/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java
index 5adbacd..092e4bc 100644
--- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java
+++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java
@@ -42,6 +42,10 @@ import com.cloud.exception.ConcurrentOperationException;
 import com.cloud.exception.InsufficientCapacityException;
 import com.cloud.exception.ResourceUnavailableException;
 import com.cloud.network.IpAddress;
+import com.cloud.network.dao.NetworkDao;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.resource.ResourceManager;
+
 import com.cloud.network.Network;
 import com.cloud.network.Network.Capability;
 import com.cloud.network.Network.Provider;
@@ -51,6 +55,8 @@ import com.cloud.network.PhysicalNetworkServiceProvider;
 import com.cloud.network.PublicIpAddress;
 import com.cloud.network.element.IpDeployer;
 import com.cloud.network.element.StaticNatServiceProvider;
+import com.cloud.network.element.SourceNatServiceProvider;
+import com.cloud.network.element.DhcpServiceProvider;
 import com.cloud.network.rules.StaticNat;
 import com.cloud.offering.NetworkOffering;
 import com.cloud.utils.component.AdapterBase;
@@ -60,14 +66,23 @@ import com.cloud.vm.ReservationContext;
 import com.cloud.vm.VMInstanceVO;
 import com.cloud.vm.VirtualMachineProfile;
 import com.cloud.vm.dao.NicDao;
+import com.cloud.server.ConfigurationServer;
+import com.cloud.server.ConfigurationServerImpl;
 
 @Component
-@Local(value = {ContrailElement.class, StaticNatServiceProvider.class})
-public class ContrailElementImpl extends AdapterBase implements ContrailElement, IpDeployer, StaticNatServiceProvider {
+@Local(value = {ContrailElement.class, StaticNatServiceProvider.class, IpDeployer.class, SourceNatServiceProvider.class})
 
+public class ContrailElementImpl extends AdapterBase
+    implements ContrailElement, StaticNatServiceProvider, IpDeployer, SourceNatServiceProvider, DhcpServiceProvider {
     private final Map<Service, Map<Capability, String>> _capabilities = InitCapabilities();
 
     @Inject
+    ResourceManager _resourceMgr;
+    @Inject
+    ConfigurationServer _configServer;
+    @Inject
+    NetworkDao _networksDao;
+    @Inject
     ContrailManager _manager;
     @Inject
     NicDao _nicDao;
@@ -92,7 +107,7 @@ public class ContrailElementImpl extends AdapterBase implements ContrailElement,
     // NetworkElement API
     @Override
     public Provider getProvider() {
-        return Provider.JuniperContrail;
+        return Provider.JuniperContrailRouter;
     }
 
     private static Map<Service, Map<Capability, String>> InitCapabilities() {
@@ -261,8 +276,34 @@ public class ContrailElementImpl extends AdapterBase implements ContrailElement,
 
     @Override
     public boolean isReady(PhysicalNetworkServiceProvider provider) {
-        return true;
-    }
+                Map<String, String> serviceMap = ((ConfigurationServerImpl)_configServer).getServicesAndProvidersForNetwork( _manager.getRouterOffering().getId());
+                List<TrafficType> types = new ArrayList<TrafficType>();
+                types.add(TrafficType.Control);
+                types.add(TrafficType.Management);
+                types.add(TrafficType.Storage);
+                List<NetworkVO> systemNets = _manager.findSystemNetworks(types);
+                if (systemNets != null && !systemNets.isEmpty()) {
+                    for (NetworkVO net: systemNets) {
+                        s_logger.debug("update system network service: " + net.getName() + "; service provider: " + serviceMap);
+                        _networksDao.update(net.getId(), net, serviceMap);
+                    }
+                } else {
+                    s_logger.debug("no system networks created yet");
+                }
+                serviceMap = ((ConfigurationServerImpl)_configServer).getServicesAndProvidersForNetwork( _manager.getPublicRouterOffering().getId());
+                types = new ArrayList<TrafficType>();
+                types.add(TrafficType.Public);
+                systemNets = _manager.findSystemNetworks(types);
+                if (systemNets != null && !systemNets.isEmpty()) {
+                    for (NetworkVO net: systemNets) {
+                        s_logger.debug("update system network service: " + net.getName() + "; service provider: " + serviceMap);
+                        _networksDao.update(net.getId(), net, serviceMap);
+                    }
+                } else {
+                    s_logger.debug("no system networks created yet");
+                }
+                return true;
+       }
 
     @Override
     public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
@@ -320,4 +361,28 @@ public class ContrailElementImpl extends AdapterBase implements ContrailElement,
         }
         return false;
     }
+
+    @Override
+    public boolean addDhcpEntry(Network network, NicProfile nic,
+               VirtualMachineProfile vm,
+               DeployDestination dest, ReservationContext context)
+                               throws ConcurrentOperationException, InsufficientCapacityException,
+                               ResourceUnavailableException {
+       return false;
+    }
+
+    @Override
+    public boolean configDhcpSupportForSubnet(Network network, NicProfile nic,
+               VirtualMachineProfile vm,
+               DeployDestination dest, ReservationContext context)
+                               throws ConcurrentOperationException, InsufficientCapacityException,
+                               ResourceUnavailableException {
+       return false;
+    }
+
+    @Override
+    public boolean removeDhcpSupportForSubnet(Network network)
+               throws ResourceUnavailableException {
+       return false;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cc2b1c49/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java
index 3bc66d1..704dedd 100644
--- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java
+++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailGuru.java
@@ -18,14 +18,15 @@
 package org.apache.cloudstack.network.contrail.management;
 
 import java.io.IOException;
+import java.net.URI;
 
 import javax.inject.Inject;
+import javax.ejb.Local;
 
 import net.juniper.contrail.api.types.MacAddressesType;
 import net.juniper.contrail.api.types.VirtualMachineInterface;
 
 import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
 
 import org.apache.cloudstack.network.contrail.model.InstanceIpModel;
 import org.apache.cloudstack.network.contrail.model.VMInterfaceModel;
@@ -61,12 +62,15 @@ import com.cloud.utils.net.NetUtils;
 import com.cloud.vm.Nic.ReservationStrategy;
 import com.cloud.vm.NicProfile;
 import com.cloud.vm.NicVO;
+import com.cloud.network.dao.IPAddressDao;
+import com.cloud.user.AccountManager;
+import com.cloud.network.IpAddressManager;
 import com.cloud.vm.ReservationContext;
 import com.cloud.vm.VMInstanceVO;
 import com.cloud.vm.VirtualMachineProfile;
 import com.cloud.vm.dao.NicDao;
 
-@Component
+@Local(value = {NetworkGuru.class})
 public class ContrailGuru extends AdapterBase implements NetworkGuru {
     @Inject
     NetworkDao _networkDao;
@@ -75,6 +79,12 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru {
     @Inject
     NicDao _nicDao;
     @Inject
+    IPAddressDao _ipAddressDao;
+    @Inject
+    AccountManager _accountMgr;
+    @Inject
+    IpAddressManager _ipAddrMgr;
+    @Inject
     PhysicalNetworkDao _physicalNetworkDao;
     @Inject
     DataCenterDao _dcDao;
@@ -84,6 +94,7 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru {
 
     private boolean canHandle(NetworkOffering offering, NetworkType networkType, PhysicalNetwork physicalNetwork) {
         if (networkType == NetworkType.Advanced
+                && offering.getId() == _manager.getRouterOffering().getId()
                 && isMyTrafficType(offering.getTrafficType())
                 && offering.getGuestType() == Network.GuestType.Isolated
                 && physicalNetwork.getIsolationMethods().contains("L3VPN"))
@@ -158,6 +169,13 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru {
         }
 
         profile.setStrategy(ReservationStrategy.Start);
+        URI broadcastUri = null;
+        try {
+            broadcastUri = new URI("vlan://untagged");
+        } catch (Exception e) {
+            s_logger.warn("unable to instantiate broadcast URI: " + e);
+        }
+        profile.setBroadcastUri(broadcastUri);
 
         return profile;
     }
@@ -235,7 +253,9 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru {
         if (nic.getIp4Address() == null) {
             s_logger.debug("Allocated IP address " + ipModel.getAddress());
             nic.setIp4Address(ipModel.getAddress());
-            nic.setNetmask(NetUtils.cidr2Netmask(network.getCidr()));
+            if (network.getCidr() != null) {
+                nic.setNetmask(NetUtils.cidr2Netmask(network.getCidr()));
+            }
             nic.setGateway(network.getGateway());
             nic.setFormat(AddressFormat.Ip4);
         }
@@ -302,6 +322,7 @@ public class ContrailGuru extends AdapterBase implements NetworkGuru {
             return;
         }
         try {
+            _manager.getDatabase().getVirtualNetworks().remove(vnModel);
             vnModel.delete(_manager.getModelController());
         } catch (IOException e) {
             s_logger.warn("virtual-network delete", e);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cc2b1c49/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java
index 335299e..6853d1e 100644
--- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java
+++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManager.java
@@ -22,6 +22,7 @@ import java.util.List;
 
 import net.juniper.contrail.api.ApiConnector;
 import net.juniper.contrail.api.types.FloatingIp;
+import net.juniper.contrail.api.types.NetworkPolicy;
 import net.juniper.contrail.api.types.VirtualNetwork;
 
 import org.apache.cloudstack.network.contrail.model.ModelController;
@@ -36,16 +37,20 @@ import com.cloud.network.dao.NetworkVO;
 import com.cloud.network.dao.PhysicalNetworkVO;
 import com.cloud.offering.NetworkOffering;
 import com.cloud.projects.ProjectVO;
+import com.cloud.network.vpc.NetworkACLVO;
 
 public interface ContrailManager {
-    public static final String offeringName = "Juniper Contrail offering";
-    public static final String offeringDisplayText = "Juniper Contrail network offering";
+    public static final String routerOfferingName = "Juniper Contrail Network Offering";
+    public static final String routerOfferingDisplayText = "Juniper Contrail Network Offering";
+    public static final String routerPublicOfferingName = "Juniper Contrail Public Network Offering";
+    public static final String routerPublicOfferingDisplayText = "Juniper Contrail Public Network Offering";
     public static final int DB_SYNC_INTERVAL_DEFAULT = 600000;
     public static final String VNC_ROOT_DOMAIN = "default-domain";
     public static final String VNC_DEFAULT_PROJECT = "default-project";
     public static final String managementNetworkName = "ip-fabric";
 
-    public NetworkOffering getOffering();
+    public NetworkOffering getRouterOffering();
+    public NetworkOffering getPublicRouterOffering();
 
     public void syncNetworkDB(short syncMode) throws IOException;
 
@@ -81,6 +86,8 @@ public interface ContrailManager {
 
     public net.juniper.contrail.api.types.Project getVncProject(long domainId, long accountId) throws IOException;
 
+    public net.juniper.contrail.api.types.Project  getDefaultVncProject() throws IOException;
+
     public boolean isSystemRootDomain(net.juniper.contrail.api.types.Domain vnc);
 
     public boolean isSystemRootDomain(DomainVO domain);
@@ -103,9 +110,13 @@ public interface ContrailManager {
 
     public ModelController getModelController();
 
-    public List<NetworkVO> findJuniperManagedNetworks(List<TrafficType> types);
+    public List<NetworkVO> findManagedNetworks(List<TrafficType> types);
+
+    public List<NetworkVO> findSystemNetworks(List<TrafficType> types);
+
+    public List<IPAddressVO> findManagedPublicIps();
 
-    public List<IPAddressVO> findJuniperManagedPublicIps();
+    public List<NetworkACLVO> findManagedACLs();
 
     public VirtualNetwork findDefaultVirtualNetwork(TrafficType trafficType) throws IOException;
 
@@ -113,9 +124,9 @@ public interface ContrailManager {
 
     public VirtualNetworkModel lookupPublicNetworkModel();
 
-    public void createPublicNetworks();
-
     public boolean createFloatingIp(PublicIpAddress ip);
 
     public boolean deleteFloatingIp(PublicIpAddress ip);
+
+    public boolean isSystemDefaultNetworkPolicy(NetworkPolicy policy);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cc2b1c49/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java
index ed58594..ef76e4c 100644
--- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java
+++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java
@@ -21,7 +21,6 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -34,6 +33,7 @@ import java.util.TimerTask;
 
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
+import javax.ejb.Local;
 
 import net.juniper.contrail.api.ApiConnector;
 import net.juniper.contrail.api.ApiConnectorFactory;
@@ -41,11 +41,11 @@ import net.juniper.contrail.api.ApiPropertyBase;
 import net.juniper.contrail.api.ObjectReference;
 import net.juniper.contrail.api.types.FloatingIp;
 import net.juniper.contrail.api.types.FloatingIpPool;
+import net.juniper.contrail.api.types.NetworkPolicy;
 import net.juniper.contrail.api.types.VirtualNetwork;
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
 
 import com.google.common.collect.ImmutableList;
 
@@ -56,13 +56,13 @@ import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel;
 
 import com.cloud.configuration.ConfigurationManager;
 import com.cloud.configuration.ConfigurationService;
+import com.cloud.server.ConfigurationServer;
 import com.cloud.dc.DataCenter;
 import com.cloud.dc.dao.DataCenterDao;
 import com.cloud.dc.dao.VlanDao;
 import com.cloud.domain.Domain;
 import com.cloud.domain.DomainVO;
 import com.cloud.domain.dao.DomainDao;
-import com.cloud.exception.InternalErrorException;
 import com.cloud.network.Network;
 import com.cloud.network.Network.Provider;
 import com.cloud.network.Network.Service;
@@ -75,17 +75,17 @@ import com.cloud.network.dao.NetworkVO;
 import com.cloud.network.dao.PhysicalNetworkDao;
 import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
 import com.cloud.network.dao.PhysicalNetworkVO;
-import com.cloud.offering.NetworkOffering;
 import com.cloud.offering.NetworkOffering.Availability;
-import com.cloud.offering.NetworkOffering.State;
+import com.cloud.offering.NetworkOffering;
 import com.cloud.offerings.NetworkOfferingVO;
 import com.cloud.offerings.dao.NetworkOfferingDao;
 import com.cloud.projects.ProjectVO;
+import com.cloud.network.vpc.dao.NetworkACLDao;
+import com.cloud.network.vpc.NetworkACLVO;
 import com.cloud.projects.dao.ProjectDao;
 import com.cloud.user.Account;
 import com.cloud.user.dao.AccountDao;
 import com.cloud.utils.PropertiesUtil;
-import com.cloud.utils.component.ComponentLifecycle;
 import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
@@ -95,13 +95,14 @@ import com.cloud.vm.dao.NicDao;
 import com.cloud.vm.dao.UserVmDao;
 import com.cloud.vm.dao.VMInstanceDao;
 
-@Component
+@Local(value = { ContrailManager.class})
 public class ContrailManagerImpl extends ManagerBase implements ContrailManager {
     @Inject
     public ConfigurationService _configService;
     @Inject
+    ConfigurationServer _configServer;
+    @Inject
     NetworkOfferingDao _networkOfferingDao;
-
     @Inject
     DomainDao _domainDao;
     @Inject
@@ -130,12 +131,16 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
     VlanDao _vlanDao;
     @Inject
     UserVmDao _vmDao;
+    @Inject
+    NetworkACLDao _networkAclDao;
 
     private static final Logger s_logger = Logger.getLogger(ContrailManager.class);
 
     private ApiConnector _api;
 
     private NetworkOffering _offering;
+    private NetworkOffering _routerOffering;
+    private NetworkOffering _routerPublicOffering;
     private Timer _dbSyncTimer;
     private int _dbSyncInterval = DB_SYNC_INTERVAL_DEFAULT;
     private final String configuration = "contrail.properties";
@@ -143,7 +148,6 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
     private ModelController _controller;
 
     ContrailManagerImpl() {
-        setRunLevel(ComponentLifecycle.RUN_LEVEL_COMPONENT);
         _database = new ModelDatabase();
     }
 
@@ -171,20 +175,55 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
         return _database;
     }
 
-    private NetworkOffering LocateOffering() {
+    private NetworkOffering LocatePublicNetworkOffering(String offeringName,
+                                           String offeringDisplayText, Provider provider) {
+        List<? extends NetworkOffering> offerList = _configService.listNetworkOfferings(TrafficType.Public, false);
+        for (NetworkOffering offer: offerList) {
+            if (offer.getName().equals(offeringName)) {
+                if (offer.getState() != NetworkOffering.State.Enabled) {
+                    return EnableNetworkOffering(offer.getId());
+                }
+                return offer;
+            }
+        }
+        Map<Service, Set<Provider>> serviceProviderMap = new HashMap<Service, Set<Provider>>();
+        Set<Provider> providerSet = new HashSet<Provider>();
+        providerSet.add(provider);
+        final Service[] services = {
+                Service.Connectivity,
+                Service.Dhcp,
+                Service.NetworkACL,
+                Service.StaticNat,
+                Service.SourceNat
+        };
+        for (Service svc: services) {
+            serviceProviderMap.put(svc, providerSet);
+        }
+        ConfigurationManager configMgr = (ConfigurationManager) _configService;
+        NetworkOfferingVO voffer = configMgr.createNetworkOffering(offeringName, offeringDisplayText,
+                TrafficType.Public, null, true, Availability.Optional, null, serviceProviderMap, true,
+                Network.GuestType.Shared, false, null, false, null, true, false, null, true, null, false);
+
+        voffer.setState(NetworkOffering.State.Enabled);
+        long id = voffer.getId();
+        _networkOfferingDao.update(id, voffer);
+        return _networkOfferingDao.findById(id);
+    }
+
+    private NetworkOffering LocateNetworkOffering(String offeringName,
+                                           String offeringDisplayText, Provider provider) {
         List<? extends NetworkOffering> offerList = _configService.listNetworkOfferings(TrafficType.Guest, false);
         for (NetworkOffering offer : offerList) {
             if (offer.getName().equals(offeringName)) {
-                if (offer.getState() != State.Enabled) {
+                if (offer.getState() != NetworkOffering.State.Enabled) {
                     return EnableNetworkOffering(offer.getId());
                 }
                 return offer;
             }
         }
         Map<Service, Set<Provider>> serviceProviderMap = new HashMap<Service, Set<Provider>>();
-        // Map<Service, Map<Capability, String>> serviceCapabilityMap = new HashMap<Service, Map<Capability, String>>();
         Set<Provider> providerSet = new HashSet<Provider>();
-        providerSet.add(Provider.JuniperContrail);
+        providerSet.add(provider);
         final Service[] services = {Service.Connectivity, Service.Dhcp, Service.NetworkACL, Service.StaticNat, Service.SourceNat};
         for (Service svc : services) {
             serviceProviderMap.put(svc, providerSet);
@@ -194,7 +233,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
             configMgr.createNetworkOffering(offeringName, offeringDisplayText, TrafficType.Guest, null, false, Availability.Optional, null, serviceProviderMap, true,
                 Network.GuestType.Isolated, false, null, false, null, false, true, null, true, null, false);
 
-        voffer.setState(State.Enabled);
+        voffer.setState(NetworkOffering.State.Enabled);
         long id = voffer.getId();
         _networkOfferingDao.update(id, voffer);
         return _networkOfferingDao.findById(id);
@@ -202,7 +241,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
 
     private NetworkOffering EnableNetworkOffering(long id) {
         NetworkOfferingVO offering = _networkOfferingDao.createForUpdate(id);
-        offering.setState(State.Enabled);
+        offering.setState(NetworkOffering.State.Enabled);
         _networkOfferingDao.update(id, offering);
         return _networkOfferingDao.findById(id);
     }
@@ -211,29 +250,41 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
     public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
 
         File configFile = PropertiesUtil.findConfigFile(configuration);
-        final Properties configProps = new Properties();
         try {
-            configProps.load(new FileInputStream(configFile));
-            String value = configProps.getProperty("management.db_sync_interval");
-            if (value != null) {
-                _dbSyncInterval = Integer.valueOf(value);
-            }
-
-            String hostname = configProps.getProperty("api.hostname");
-            String portStr = configProps.getProperty("api.port");
+            String hostname = null;
             int port = 0;
-            if (portStr != null && portStr.length() > 0) {
-                port = Integer.parseInt(portStr);
+            if (configFile == null) {
+                hostname = "localhost";
+                port = 8082;
+            } else {
+                final Properties configProps = new Properties();
+                configProps.load(new FileInputStream(configFile));
+                String value = configProps.getProperty("management.db_sync_interval");
+                if (value != null) {
+                    _dbSyncInterval = Integer.valueOf(value);
+                }
+                hostname = configProps.getProperty("api.hostname");
+                String portStr = configProps.getProperty("api.port");
+                if (portStr != null && portStr.length() > 0) {
+                    port = Integer.parseInt(portStr);
+                }
             }
             _api = ApiConnectorFactory.build(hostname, port);
         } catch (IOException ex) {
             s_logger.warn("Unable to read " + configuration, ex);
             throw new ConfigurationException();
+        } catch (Exception ex) {
+            s_logger.debug("Exception in configure: " + ex);
+            ex.printStackTrace();
+            throw new ConfigurationException();
         }
 
         _controller = new ModelController(this, _api, _vmDao, _networksDao, _nicDao, _vlanDao, _ipAddressDao);
 
-        _offering = LocateOffering();
+        _routerOffering = LocateNetworkOffering(routerOfferingName, routerOfferingDisplayText,
+                                                                  Provider.JuniperContrailRouter);
+        _routerPublicOffering = LocatePublicNetworkOffering(routerPublicOfferingName, routerPublicOfferingDisplayText,
+                                                                  Provider.JuniperContrailRouter);
 
         _eventHandler.subscribe();
 
@@ -243,8 +294,13 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
     }
 
     @Override
-    public NetworkOffering getOffering() {
-        return _offering;
+    public NetworkOffering getPublicRouterOffering() {
+        return _routerPublicOffering;
+    }
+
+    @Override
+    public NetworkOffering getRouterOffering() {
+        return _routerOffering;
     }
 
     @Override
@@ -340,12 +396,19 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
     public net.juniper.contrail.api.types.Project getVncProject(long domainId, long accountId) throws IOException {
         String projectId = getProjectId(domainId, accountId);
         if (projectId == null) {
-            return null;
+            return getDefaultVncProject();
         }
         return (net.juniper.contrail.api.types.Project)_api.findById(net.juniper.contrail.api.types.Project.class, projectId);
     }
 
     @Override
+    public net.juniper.contrail.api.types.Project getDefaultVncProject() throws IOException {
+        net.juniper.contrail.api.types.Project project = null;
+        project = (net.juniper.contrail.api.types.Project)_api.findByFQN(net.juniper.contrail.api.types.Project.class, VNC_ROOT_DOMAIN + ":" + VNC_DEFAULT_PROJECT);
+        return project;
+    }
+
+    @Override
     public String getFQN(Network net) {
         // domain, project, name
         String fqname = getDomainName(net.getDomainId());
@@ -402,7 +465,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
     public boolean isManagedPhysicalNetwork(Network network) {
         List<PhysicalNetworkVO> net_list = _physicalNetworkDao.listByZone(network.getDataCenterId());
         for (PhysicalNetworkVO phys : net_list) {
-            if (_physProviderDao.findByServiceProvider(phys.getId(), Network.Provider.JuniperContrail.getName()) != null) {
+            if (_physProviderDao.findByServiceProvider(phys.getId(), Network.Provider.JuniperContrailRouter.getName()) != null) {
                 return true;
             }
         }
@@ -428,6 +491,53 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
     }
 
     @Override
+    public List<NetworkVO> findSystemNetworks(List<TrafficType> types) {
+        SearchBuilder<NetworkVO> searchBuilder = _networksDao.createSearchBuilder();
+        searchBuilder.and("trafficType", searchBuilder.entity().getTrafficType(), Op.IN);
+        SearchCriteria<NetworkVO> sc = searchBuilder.create();
+        if (types == null || types.isEmpty()) {
+            types = new ArrayList<TrafficType>();
+            types.add(TrafficType.Control);
+            types.add(TrafficType.Management);
+            types.add(TrafficType.Public);
+            types.add(TrafficType.Storage);
+        }
+        sc.setParameters("trafficType", types.toArray());
+        List<NetworkVO> dbNets = _networksDao.search(sc, null);
+        if (dbNets == null) {
+            s_logger.debug("no system networks for the given traffic types: " + types.toString());
+            dbNets = new ArrayList<NetworkVO>();
+        }
+
+        List<PhysicalNetworkVO> phys_list = _physicalNetworkDao.listAll();
+        final String provider = Provider.JuniperContrailRouter.getName();
+        for (Iterator<PhysicalNetworkVO> iter = phys_list.iterator(); iter.hasNext(); ) {
+            PhysicalNetworkVO phys = iter.next();
+            if (_physProviderDao.findByServiceProvider(phys.getId(), provider) != null) {
+                List<NetworkVO> infraNets = new ArrayList<NetworkVO>();
+                findInfrastructureNetworks(phys, infraNets);
+                for (NetworkVO net:infraNets) {
+                    if (types == null || types.isEmpty()) {
+                        if (!dbNets.contains(net)) {
+                            dbNets.add(net);
+                        }
+                        continue;
+                    }
+                    for(TrafficType type:types) {
+                        if (net.getTrafficType() == type) {
+                            if (!dbNets.contains(net)) {
+                                dbNets.add(net);
+                            }
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+        return dbNets;
+    }
+
+    @Override
     public VirtualNetwork findDefaultVirtualNetwork(TrafficType trafficType) throws IOException {
         if (trafficType == TrafficType.Guest || trafficType == TrafficType.Public) {
             return null;
@@ -445,14 +555,17 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
      * Returns list of networks managed by Juniper VRouter filtered by traffic types
      */
     @Override
-    public List<NetworkVO> findJuniperManagedNetworks(List<TrafficType> types) {
+    public List<NetworkVO> findManagedNetworks(List<TrafficType> types) {
 
         SearchBuilder<NetworkVO> searchBuilder = _networksDao.createSearchBuilder();
         searchBuilder.and("trafficType", searchBuilder.entity().getTrafficType(), Op.IN);
-        searchBuilder.and("networkOfferingId", searchBuilder.entity().getNetworkOfferingId(), Op.EQ);
+        searchBuilder.and("networkOfferingId", searchBuilder.entity().getNetworkOfferingId(), Op.IN);
 
         SearchCriteria<NetworkVO> sc = searchBuilder.create();
-        sc.setParameters("networkOfferingId", getOffering().getId());
+        List<Long> offerings = new ArrayList<Long>();
+        offerings.add(getRouterOffering().getId());
+        offerings.add(getPublicRouterOffering().getId());
+        sc.setParameters("networkOfferingId", offerings.toArray());
 
         if (types == null || types.isEmpty()) {
             types = new ArrayList<TrafficType>();
@@ -471,7 +584,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
         }
 
         List<PhysicalNetworkVO> phys_list = _physicalNetworkDao.listAll();
-        final String provider = Network.Provider.JuniperContrail.getName();
+        final String provider = Network.Provider.JuniperContrailRouter.getName();
         for (Iterator<PhysicalNetworkVO> iter = phys_list.iterator(); iter.hasNext();) {
             PhysicalNetworkVO phys = iter.next();
             if (_physProviderDao.findByServiceProvider(phys.getId(), provider) != null) {
@@ -479,12 +592,16 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
                 findInfrastructureNetworks(phys, infraNets);
                 for (NetworkVO net : infraNets) {
                     if (types == null || types.isEmpty()) {
-                        dbNets.add(net);
+                        if (!dbNets.contains(net)) {
+                            dbNets.add(net);
+                        }
                         continue;
                     }
                     for (TrafficType type : types) {
                         if (net.getTrafficType() == type) {
-                            dbNets.add(net);
+                            if (!dbNets.contains(net)) {
+                                dbNets.add(net);
+                            }
                             break;
                         }
                     }
@@ -494,13 +611,19 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
         return dbNets;
     }
 
+    @Override
+    public List<NetworkACLVO> findManagedACLs() {
+        /* contrail vpc is not yet implemented */
+        return null;
+    }
+
     /*
      * Returns list of public ip addresses managed by Juniper VRouter
      */
     @Override
-    public List<IPAddressVO> findJuniperManagedPublicIps() {
+    public List<IPAddressVO> findManagedPublicIps() {
 
-        List<NetworkVO> dbNets = findJuniperManagedNetworks(null);
+        List<NetworkVO> dbNets = findManagedNetworks(null);
 
         if (dbNets == null || dbNets.isEmpty()) {
             s_logger.debug("Juniper managed networks is empty");
@@ -538,7 +661,7 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
         types.add(TrafficType.Storage);
         types.add(TrafficType.Control);
 
-        List<NetworkVO> dbNets = findJuniperManagedNetworks(types);
+        List<NetworkVO> dbNets = findManagedNetworks(types);
         for (NetworkVO net : dbNets) {
 
             VirtualNetworkModel vnModel = getDatabase().lookupVirtualNetwork(null, getCanonicalName(net), net.getTrafficType());
@@ -647,46 +770,27 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
     public VirtualNetworkModel lookupPublicNetworkModel() {
         List<TrafficType> types = new ArrayList<TrafficType>();
         types.add(TrafficType.Public);
-        List<NetworkVO> dbNets = findJuniperManagedNetworks(types);
+        List<NetworkVO> dbNets = findManagedNetworks(types);
         if (dbNets == null) {
             return null;
         }
         NetworkVO net = dbNets.get(0);
 
         VirtualNetworkModel vnModel = getDatabase().lookupVirtualNetwork(net.getUuid(), getCanonicalName(net), TrafficType.Public);
-        return vnModel;
-    }
-
-    @Override
-    public void createPublicNetworks() {
-        List<TrafficType> types = new ArrayList<TrafficType>(Arrays.asList(TrafficType.Public));
-        List<NetworkVO> dbNets = findJuniperManagedNetworks(types);
-        if (dbNets == null) {
-            return;
+        if (vnModel == null) {
+            vnModel = new VirtualNetworkModel(net, net.getUuid(),
+                        getCanonicalName(net), net.getTrafficType());
+            vnModel.setProperties(getModelController(), net);
         }
-        for (NetworkVO net : dbNets) {
-            VirtualNetworkModel vnModel = _database.lookupVirtualNetwork(net.getUuid(), getCanonicalName(net), TrafficType.Public);
-            if (vnModel != null) {
-                continue;
-            }
-            vnModel = new VirtualNetworkModel(net, net.getUuid(), getCanonicalName(net), net.getTrafficType());
-            vnModel.build(_controller, net);
-            try {
-                vnModel.update(_controller);
-            } catch (InternalErrorException ex) {
-                s_logger.warn("virtual-network update", ex);
-                continue;
-            } catch (IOException ex) {
-                s_logger.warn("virtual-network update", ex);
-                continue;
+        try {
+            if (!vnModel.verify(getModelController())) {
+                vnModel.update(getModelController());
             }
-            _database.getVirtualNetworks().add(vnModel);
-
-            // Add the Contrail NetworkElement to the Public network.
-            Map<String, String> providerMap = new HashMap<String, String>();
-            providerMap.put(Service.Connectivity.getName(), Provider.JuniperContrail.getName());
-            _networksDao.update(net.getId(), net, providerMap);
+            getDatabase().getVirtualNetworks().add(vnModel);
+        } catch (Exception ex) {
+            s_logger.warn("virtual-network update: ", ex);
         }
+        return vnModel;
     }
 
     @Override
@@ -775,4 +879,12 @@ public class ContrailManagerImpl extends ManagerBase implements ContrailManager
         }
         return null;
     }
+
+    @Override
+    public boolean isSystemDefaultNetworkPolicy(NetworkPolicy policy) {
+        if (policy.getName().equals("default-network-policy")) {
+            return true;
+        }
+        return false;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cc2b1c49/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java
index e2845b7..66fad70 100644
--- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java
+++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ModelDatabase.java
@@ -20,6 +20,7 @@ package org.apache.cloudstack.network.contrail.management;
 import java.util.TreeSet;
 
 import org.apache.cloudstack.network.contrail.model.ModelObjectBase;
+import org.apache.cloudstack.network.contrail.model.NetworkPolicyModel;
 import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel;
 import org.apache.cloudstack.network.contrail.model.VirtualMachineModel;
 import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel;
@@ -30,6 +31,7 @@ public class ModelDatabase {
     TreeSet<ServiceInstanceModel> _serviceInstanceTable;
     TreeSet<VirtualMachineModel> _vmTable;
     TreeSet<VirtualNetworkModel> _vnTable;
+    TreeSet<NetworkPolicyModel> _policyTable;
 
     public ModelDatabase() {
         initDb();
@@ -39,16 +41,17 @@ public class ModelDatabase {
         _serviceInstanceTable = new TreeSet<ServiceInstanceModel>(new ModelObjectBase.UuidComparator());
         _vmTable = new TreeSet<VirtualMachineModel>(new ModelObjectBase.UuidComparator());
         _vnTable = new TreeSet<VirtualNetworkModel>(new ModelObjectBase.UuidComparator());
+        _policyTable = new TreeSet<NetworkPolicyModel>(new ModelObjectBase.UuidComparator());
     }
 
     public TreeSet<ServiceInstanceModel> getServiceInstances() {
         return _serviceInstanceTable;
     }
 
-    public ServiceInstanceModel lookupServiceInstance(String uuid) {
-        ServiceInstanceModel siKey = new ServiceInstanceModel(uuid);
+    public ServiceInstanceModel lookupServiceInstance(String fqn) {
+        ServiceInstanceModel siKey = new ServiceInstanceModel(fqn);
         ServiceInstanceModel current = _serviceInstanceTable.ceiling(siKey);
-        if (current != null && current.getUuid().equals(uuid)) {
+        if  (current != null && current.getQualifiedName().equals(fqn)) {
             return current;
         }
         return null;
@@ -85,4 +88,17 @@ public class ModelDatabase {
         }
         return null;
     }
+
+    public TreeSet<NetworkPolicyModel> getNetworkPolicys() {
+        return _policyTable;
+    }
+
+    public NetworkPolicyModel lookupNetworkPolicy(String uuid) {
+        NetworkPolicyModel vmKey = new NetworkPolicyModel(uuid, null);
+        NetworkPolicyModel current = _policyTable.ceiling(vmKey);
+        if (current != null && current.getUuid().equals(uuid)) {
+            return current;
+        }
+        return null;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cc2b1c49/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java
index 52fe31e..b1f4718 100644
--- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java
+++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java
@@ -33,6 +33,7 @@ import net.juniper.contrail.api.ApiPropertyBase;
 import net.juniper.contrail.api.ObjectReference;
 import net.juniper.contrail.api.types.FloatingIp;
 import net.juniper.contrail.api.types.FloatingIpPool;
+import net.juniper.contrail.api.types.NetworkPolicy;
 import net.juniper.contrail.api.types.InstanceIp;
 import net.juniper.contrail.api.types.ServiceInstance;
 import net.juniper.contrail.api.types.VirtualMachine;
@@ -45,6 +46,7 @@ import org.springframework.stereotype.Component;
 
 import org.apache.cloudstack.network.contrail.model.FloatingIpModel;
 import org.apache.cloudstack.network.contrail.model.FloatingIpPoolModel;
+import org.apache.cloudstack.network.contrail.model.NetworkPolicyModel;
 import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel;
 import org.apache.cloudstack.network.contrail.model.VMInterfaceModel;
 import org.apache.cloudstack.network.contrail.model.VirtualMachineModel;
@@ -62,6 +64,10 @@ import com.cloud.network.dao.NetworkDao;
 import com.cloud.network.dao.NetworkVO;
 import com.cloud.network.dao.PhysicalNetworkDao;
 import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
+import com.cloud.network.vpc.NetworkACLItemDao;
+import com.cloud.network.vpc.NetworkACLItemVO;
+import com.cloud.network.vpc.NetworkACLVO;
+import com.cloud.network.vpc.dao.NetworkACLDao;
 import com.cloud.projects.ProjectVO;
 import com.cloud.projects.dao.ProjectDao;
 import com.cloud.vm.NicVO;
@@ -90,6 +96,11 @@ public class ServerDBSyncImpl implements ServerDBSync {
     PhysicalNetworkServiceProviderDao _physProviderDao;
     @Inject
     ContrailManager _manager;
+    @Inject
+    NetworkACLItemDao _networkACLItemDao;
+    @Inject
+    NetworkACLDao _networkACLDao;
+
     DBSyncGeneric _dbSync;
     Class<?>[] _vncClasses;
     // Read-Write (true) or Read-Only mode.
@@ -98,8 +109,8 @@ public class ServerDBSyncImpl implements ServerDBSync {
 
     ServerDBSyncImpl() {
         _vncClasses =
-            new Class[] {net.juniper.contrail.api.types.Domain.class, net.juniper.contrail.api.types.Project.class, VirtualNetwork.class, VirtualMachine.class,
-                ServiceInstance.class, FloatingIp.class};
+            new Class[] {net.juniper.contrail.api.types.Domain.class, net.juniper.contrail.api.types.Project.class, NetworkPolicy.class, VirtualNetwork.class,
+                VirtualMachine.class, ServiceInstance.class, FloatingIp.class};
         _dbSync = new DBSyncGeneric(this);
     }
 
@@ -440,7 +451,7 @@ public class ServerDBSyncImpl implements ServerDBSync {
             List<TrafficType> types = new ArrayList<TrafficType>();
             types.add(TrafficType.Public);
             types.add(TrafficType.Guest);
-            List<NetworkVO> dbNets = _manager.findJuniperManagedNetworks(types);
+            List<NetworkVO> dbNets = _manager.findManagedNetworks(types);
 
             List<VirtualNetwork> vList = (List<VirtualNetwork>)api.list(VirtualNetwork.class, null);
             List<VirtualNetwork> vncList = new ArrayList<VirtualNetwork>();
@@ -499,6 +510,16 @@ public class ServerDBSyncImpl implements ServerDBSync {
         }
 
         VirtualNetworkModel vnModel = new VirtualNetworkModel(dbNet, dbNet.getUuid(), _manager.getCanonicalName(dbNet), dbNet.getTrafficType());
+        if (dbNet.getTrafficType() == TrafficType.Guest && dbNet.getNetworkACLId() != null) {
+            NetworkACLVO acl = _networkACLDao.findById(dbNet.getNetworkACLId());
+            NetworkPolicyModel policyModel = _manager.getDatabase().lookupNetworkPolicy(acl.getUuid());
+            if (policyModel == null) {
+                s_logger.error("Network(" + dbNet.getName() + ") has ACL but policy model not created: " +
+                                       acl.getUuid() + ", name: " + acl.getName());
+            } else {
+                vnModel.addToNetworkPolicy(policyModel);
+            }
+        }
         vnModel.build(_manager.getModelController(), dbNet);
 
         if (_rwMode) {
@@ -569,6 +590,16 @@ public class ServerDBSyncImpl implements ServerDBSync {
         VirtualNetworkModel current = _manager.getDatabase().lookupVirtualNetwork(vnet.getUuid(), _manager.getCanonicalName(dbn), dbn.getTrafficType());
 
         VirtualNetworkModel vnModel = new VirtualNetworkModel(dbn, vnet.getUuid(), _manager.getCanonicalName(dbn), dbn.getTrafficType());
+        if (dbn.getTrafficType() == TrafficType.Guest && dbn.getNetworkACLId() != null) {
+            NetworkACLVO acl = _networkACLDao.findById(dbn.getNetworkACLId());
+            NetworkPolicyModel policyModel = _manager.getDatabase().lookupNetworkPolicy(acl.getUuid());
+            if (policyModel == null) {
+                s_logger.error("Network(" + dbn.getName() + ") has ACL but policy model not created: " +
+                                       acl.getUuid() + ", name: " + acl.getName());
+            } else {
+                vnModel.addToNetworkPolicy(policyModel);
+            }
+        }
         vnModel.build(_manager.getModelController(), dbn);
 
         if (_rwMode) {
@@ -589,6 +620,23 @@ public class ServerDBSyncImpl implements ServerDBSync {
             } catch (Exception ex) {
                 s_logger.warn("update virtual-network", ex);
             }
+            if (current != null) {
+                NetworkPolicyModel oldPolicyModel = current.getNetworkPolicyModel();
+                if (oldPolicyModel != vnModel.getNetworkPolicyModel()) {
+                    /*
+                     * if no other VNs are associated with the old policy,
+                     * we could delete it from the Contrail VNC
+                     */
+                    if (oldPolicyModel != null && !oldPolicyModel.hasDescendents()) {
+                        try {
+                            oldPolicyModel.delete(_manager.getModelController());
+                            _manager.getDatabase().getNetworkPolicys().remove(oldPolicyModel);
+                        } catch (IOException e) {
+                            e.printStackTrace();
+                        }
+                    }
+                }
+            }
         } else {
             //compare
             if (current != null && current.compare(_manager.getModelController(), vnModel) == false) {
@@ -780,7 +828,7 @@ public class ServerDBSyncImpl implements ServerDBSync {
 
     public boolean syncFloatingIp() throws Exception {
 
-        List<IPAddressVO> ipList = _manager.findJuniperManagedPublicIps();
+        List<IPAddressVO> ipList = _manager.findManagedPublicIps();
         List<FloatingIp> vncList = _manager.getFloatingIps();
         if (ipList == null) {
             ipList = new ArrayList<IPAddressVO>();
@@ -884,6 +932,164 @@ public class ServerDBSyncImpl implements ServerDBSync {
         return true;
     }
 
+    /*
+     *  Network Policy Synchronization methods
+     */
+    @SuppressWarnings({ "unchecked" })
+    public boolean syncNetworkPolicy() throws Exception {
+        final ApiConnector api = _manager.getApiConnector();
+        try {
+
+            List<NetworkACLVO> dbAcls = _manager.findManagedACLs();
+            if (dbAcls == null) {
+                dbAcls = new ArrayList<NetworkACLVO>();
+            }
+
+            List<NetworkPolicy> pList = (List<NetworkPolicy>) api.list(NetworkPolicy.class, null);
+            List<NetworkPolicy> vncList = new ArrayList<NetworkPolicy>();
+
+            for (NetworkPolicy policy:pList) {
+                if (!_manager.isSystemDefaultNetworkPolicy(policy)) {
+                    vncList.add(policy);
+                }
+            }
+            s_logger.debug("sync Network Policy - DB size: " + dbAcls.size() + " VNC Size: " + vncList.size());
+            return _dbSync.syncGeneric(NetworkPolicy.class, dbAcls, vncList);
+        } catch (Exception ex) {
+            s_logger.warn("sync network-policys", ex);
+            throw ex;
+        }
+    }
+
+    public Comparator<NetworkACLVO> dbComparatorNetworkPolicy() {
+        Comparator<NetworkACLVO> comparator = new Comparator<NetworkACLVO>() {
+            public int compare(NetworkACLVO u1, NetworkACLVO u2) {
+                return u1.getUuid().compareTo(u2.getUuid());
+            }
+        };
+        return comparator;
+    }
+
+    public Comparator<?> vncComparatorNetworkPolicy() {
+        Comparator<?> comparator = new Comparator<NetworkPolicy>() {
+            public int compare(NetworkPolicy u1, NetworkPolicy u2) {
+                return u1.getUuid().compareTo(u2.getUuid());
+            }
+        };
+        return comparator;
+    }
+
+    public void createNetworkPolicy(NetworkACLVO db, StringBuffer syncLogMesg) throws IOException {
+        syncLogMesg.append("Policy# DB: " + db.getName() +
+                "(" + db.getUuid() + "); VNC: none;  action: create\n");
+
+        if (_manager.getDatabase().lookupNetworkPolicy(db.getUuid()) != null) {
+             s_logger.warn("Policy model object is already present in DB: " +
+                                   db.getUuid() + ", name: " + db.getName());
+        }
+        NetworkPolicyModel policyModel = new NetworkPolicyModel(db.getUuid(), db.getName());
+        net.juniper.contrail.api.types.Project project = null;
+        try {
+            project = _manager.getDefaultVncProject();
+        } catch (IOException ex) {
+            s_logger.warn("read project", ex);
+            throw ex;
+        }
+        policyModel.setProject(project);
+        List<NetworkACLItemVO> rules = _networkACLItemDao.listByACL(db.getId());
+        try {
+            policyModel.build(_manager.getModelController(), rules);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        if (_rwMode) {
+            try {
+                if (!policyModel.verify(_manager.getModelController())) {
+                    policyModel.update(_manager.getModelController());
+                }
+            } catch (Exception ex) {
+                s_logger.warn("create network-policy", ex);
+                syncLogMesg.append("Error: Policy# VNC : Unable to create network policy " +
+                    db.getName() + "\n");
+                return;
+            }
+            s_logger.debug("add model " + policyModel.getName());
+            _manager.getDatabase().getNetworkPolicys().add(policyModel);
+            syncLogMesg.append("Policy# VNC: " + db.getUuid() + ", " + policyModel.getName() + " created\n");
+        } else {
+            syncLogMesg.append("Policy# VNC: " + policyModel.getName() + " created \n");
+        }
+    }
+
+    public void deleteNetworkPolicy(NetworkPolicy policy, StringBuffer syncLogMesg) throws IOException {
+        final ApiConnector api = _manager.getApiConnector();
+        if (_manager.isSystemDefaultNetworkPolicy(policy)) {
+            syncLogMesg.append("Policy# System default Network Policy# VNC: " + policy.getName() + " can not be deleted\n");
+            return;
+        }
+        syncLogMesg.append("Policy# DB: none; VNC: " + policy.getName() + "(" + policy.getUuid() + "); action: delete\n");
+        api.delete(policy);
+        syncLogMesg.append("Policy# VNC: " + policy.getName() + " deleted\n");
+    }
+
+    public Integer compareNetworkPolicy(NetworkACLVO dbn, NetworkPolicy policy, StringBuffer syncLogMesg) {
+        if (_manager.isSystemDefaultNetworkPolicy(policy)) {
+            return 1;
+        }
+        return dbn.getUuid().compareTo(policy.getUuid());
+    }
+
+    public Boolean filterNetworkPolicy(NetworkPolicy policy, StringBuffer syncLogMesg)  {
+        if (_manager.isSystemDefaultNetworkPolicy(policy)) {
+            syncLogMesg.append("Policy# VNC: " + policy.getName() + " filtered; action: don't delete\n");
+            return true;
+        }
+        return false;
+    }
+
+    public Boolean equalNetworkPolicy(NetworkACLVO db, NetworkPolicy policy, StringBuffer syncLogMesg) {
+        syncLogMesg.append("Policy# DB: " + db.getName() +
+                "; VNC: " + policy.getName() + "; action: equal\n");
+        NetworkPolicyModel current = _manager.getDatabase().lookupNetworkPolicy(policy.getUuid());
+        NetworkPolicyModel policyModel = new NetworkPolicyModel(db.getUuid(), db.getName());
+        net.juniper.contrail.api.types.Project project = null;
+        try {
+            project = _manager.getDefaultVncProject();
+        } catch (IOException ex) {
+            s_logger.warn("read project", ex);
+        }
+        policyModel.setProject(project);
+        List<NetworkACLItemVO> rules = _networkACLItemDao.listByACL(db.getId());
+        try {
+            policyModel.build(_manager.getModelController(), rules);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        if (_rwMode) {
+            if (current != null) {
+                _manager.getDatabase().getNetworkPolicys().remove(current);
+            }
+            s_logger.debug("add policy model " + policyModel.getName());
+            _manager.getDatabase().getNetworkPolicys().add(policyModel);
+            try {
+                if (!policyModel.verify(_manager.getModelController())) {
+                    policyModel.update(_manager.getModelController());
+                }
+            } catch (Exception ex) {
+                s_logger.warn("update network-policy", ex);
+            }
+        } else {
+            //compare
+            if (current != null && current.compare(_manager.getModelController(), policyModel) == false) {
+                syncLogMesg.append("Policy# DB: " + db.getName() +
+                        "; VNC: " + policy.getName() + "; attributes differ\n");
+                return false;
+            }
+        }
+        return true;
+    }
+
     public Integer compareServiceInstance(ServiceInstanceModel siModel, ServiceInstance siObj, StringBuffer logMsg) {
         String fqn = StringUtils.join(siObj.getQualifiedName(), ':');
         return siModel.getQualifiedName().compareTo(fqn);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cc2b1c49/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java
index 5030bb7..05dcdce 100644
--- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java
+++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java
@@ -87,14 +87,6 @@ public class ServerEventHandlerImpl implements ServerEventHandler {
     public void defaultMessageHandler(String subject, String topic, Object args) {
         s_logger.info("DB Event Received - topic: " + topic + "; subject: " + subject);
 
-        if (subject.equals("VLAN.IP.RANGE.CREATE")) {
-            _manager.createPublicNetworks();
-            return;
-        } else if (subject.equals("VLAN.IP.RANGE.DELETE")) {
-            // TODO
-            return;
-        }
-
         org.apache.cloudstack.framework.events.Event event = (org.apache.cloudstack.framework.events.Event)args;
 
         /* Method name should be on<ClassName><Operation> for example: onDomainCreate */
@@ -244,7 +236,5 @@ public class ServerEventHandlerImpl implements ServerEventHandler {
         _messageBus.subscribe(EventTypes.EVENT_PROJECT_DELETE, MessageDispatcher.getDispatcher(this));
         _messageBus.subscribe(EventTypes.EVENT_DOMAIN_CREATE, MessageDispatcher.getDispatcher(this));
         _messageBus.subscribe(EventTypes.EVENT_DOMAIN_DELETE, MessageDispatcher.getDispatcher(this));
-        _messageBus.subscribe(EventTypes.EVENT_VLAN_IP_RANGE_CREATE, MessageDispatcher.getDispatcher(this));
-        _messageBus.subscribe(EventTypes.EVENT_VLAN_IP_RANGE_DELETE, MessageDispatcher.getDispatcher(this));
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cc2b1c49/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java
index 98be288..9860faf 100644
--- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java
+++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java
@@ -27,12 +27,13 @@ import javax.inject.Inject;
 
 import net.juniper.contrail.api.ApiConnector;
 import net.juniper.contrail.api.types.ServiceInstance;
-import net.juniper.contrail.api.types.VirtualNetwork;
 
 import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.network.contrail.api.response.ServiceInstanceResponse;
 import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel;
 import org.apache.cloudstack.network.contrail.model.VirtualMachineModel;
+import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel;
+
 import org.apache.log4j.Logger;
 
 import com.cloud.api.ApiDBUtils;
@@ -142,17 +143,15 @@ public class ServiceManagerImpl implements ServiceManager {
         }
 
         final ApiConnector api = _manager.getApiConnector();
-        final VirtualNetwork netLeft;
-        try {
-            netLeft = (VirtualNetwork)api.findById(VirtualNetwork.class, left.getUuid());
-        } catch (IOException ex) {
-            throw new CloudRuntimeException("Unable to read virtual-network object", ex);
+        VirtualNetworkModel leftModel = _manager.getDatabase().lookupVirtualNetwork(left.getUuid(),
+                _manager.getCanonicalName(left), left.getTrafficType());
+        if (leftModel == null) {
+            throw new CloudRuntimeException("Unable to read virtual-network object");
         }
-        final VirtualNetwork netRight;
-        try {
-            netRight = (VirtualNetwork)api.findById(VirtualNetwork.class, right.getUuid());
-        } catch (IOException ex) {
-            throw new CloudRuntimeException("Unable to read virtual-network object", ex);
+        VirtualNetworkModel rightModel = _manager.getDatabase().lookupVirtualNetwork(right.getUuid(),
+                _manager.getCanonicalName(right), right.getTrafficType());
+        if (rightModel == null) {
+            throw new CloudRuntimeException("Unable to read virtual-network object");
         }
 
         net.juniper.contrail.api.types.Project project;
@@ -174,7 +173,8 @@ public class ServiceManagerImpl implements ServiceManager {
         }
 
         // 1. Create service-instance.
-        ServiceInstanceModel serviceModel = new ServiceInstanceModel(project, name, template, serviceOffering, netLeft, netRight);
+        ServiceInstanceModel serviceModel = new ServiceInstanceModel(project, name, template, serviceOffering,
+                leftModel, rightModel);
 
         try {
             serviceModel.update(_manager.getModelController());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cc2b1c49/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/NetworkPolicyModel.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/NetworkPolicyModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/NetworkPolicyModel.java
new file mode 100644
index 0000000..8ec2ff7
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/NetworkPolicyModel.java
@@ -0,0 +1,305 @@
+// 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 org.apache.cloudstack.network.contrail.model;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.log4j.Logger;
+
+import com.cloud.network.Networks;
+
+import net.juniper.contrail.api.types.NetworkPolicy;
+import net.juniper.contrail.api.types.PolicyEntriesType;
+import net.juniper.contrail.api.types.PolicyEntriesType.PolicyRuleType;
+import net.juniper.contrail.api.types.Project;
+import net.juniper.contrail.api.ApiConnector;
+import org.apache.cloudstack.network.contrail.management.ContrailManager;
+
+import com.cloud.exception.InternalErrorException;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.network.vpc.NetworkACLItem;
+import com.cloud.network.vpc.NetworkACLItem.Action;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria.Op;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class NetworkPolicyModel extends ModelObjectBase {
+    private static final Logger s_logger = Logger.getLogger(NetworkPolicyModel.class);
+
+    private String _uuid;
+    private String _fqName;
+    private String _name;
+    private Project _project;
+    private NetworkPolicy _policy;
+    PolicyEntriesType _policyMap;
+
+    public NetworkPolicyModel(String uuid, String name) {
+        _uuid = uuid;
+        _name = name;
+    }
+
+     public String getQualifiedName() {
+        return _fqName;
+    }
+
+    public String getName() {
+        return _name;
+    }
+
+    public NetworkVO cidrToNetwork(ModelController controller, String cidr) {
+        SearchBuilder<NetworkVO> searchBuilder = controller.getNetworkDao().createSearchBuilder();
+        searchBuilder.and("trafficType", searchBuilder.entity().getTrafficType(), Op.EQ);
+        searchBuilder.and("cidr", searchBuilder.entity().getCidr(), Op.EQ);
+        searchBuilder.and("networkOfferingId", searchBuilder.entity().getNetworkOfferingId(), Op.EQ);
+
+        SearchCriteria<NetworkVO> sc = searchBuilder.create();
+
+        sc.setParameters("networkOfferingId", controller.getManager().getRouterOffering().getId());
+        sc.setParameters("cidr", cidr);
+        sc.setParameters("trafficType", Networks.TrafficType.Guest);
+
+        List<NetworkVO> dbNets = controller.getNetworkDao().search(sc, null);
+        if (dbNets == null || dbNets.size() == 0) {
+            return null;
+        }
+        if (dbNets.size() > 1) {
+            s_logger.warn("more than one network found with cidr: " + cidr);
+        }
+        return dbNets.get(0);
+    }
+
+    public void build(ModelController controller, List<? extends NetworkACLItem> rules) throws Exception {
+        String projectName = null;
+        if (_project != null) {
+            _fqName = StringUtils.join(_project.getQualifiedName(), ':') + ":" + _name;
+            projectName = StringUtils.join(_project.getQualifiedName(), ':');
+        } else {
+            _fqName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT + ":" + _name;
+            projectName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT;
+        }
+
+        PolicyEntriesType policyMap = new PolicyEntriesType();
+
+        for (NetworkACLItem rule:rules) {
+            if (rule.getState() != NetworkACLItem.State.Active &&
+                 rule.getState() != NetworkACLItem.State.Add)  {
+                 continue;
+            }
+
+            String action = null;
+            if (rule.getAction() == Action.Allow) {
+                action = "pass";
+            } else if (rule.getAction() == Action.Deny) {
+                action = "deny";
+            }
+            List<String> cidrList = rule.getSourceCidrList();
+            String protocol = rule.getProtocol();
+            if (protocol == null || protocol.equalsIgnoreCase("ALL") || protocol.isEmpty()) {
+                protocol = "any";
+            } else {
+                protocol = protocol.toLowerCase();
+            }
+
+            Integer portStart = rule.getSourcePortStart();
+            Integer portEnd = rule.getSourcePortEnd();
+            if (portStart == null) {
+                portStart = 0;
+            }
+            if (portEnd == null) {
+                portEnd = 65535;
+            }
+
+            List<PolicyRuleType.AddressType> srcList = new ArrayList<PolicyRuleType.AddressType>();
+            List<PolicyRuleType.AddressType> dstList = new ArrayList<PolicyRuleType.AddressType>();
+
+            List<PolicyRuleType.PortType> srcPorts = new ArrayList<PolicyRuleType.PortType>();
+            List<PolicyRuleType.PortType> dstPorts = new ArrayList<PolicyRuleType.PortType>();
+
+            if (rule.getTrafficType() == NetworkACLItem.TrafficType.Egress){
+                for (String cidr: cidrList) {
+                    NetworkVO net = cidrToNetwork(controller, cidr);
+                    /*String[] maskInfo = StringUtils.splitByWholeSeparator(cidr, "/");
+                    SubnetType subnet = new SubnetType();
+                    subnet.setIpPrefix(maskInfo[0]);
+                    subnet.setIpPrefixLen(Integer.parseInt(maskInfo[1]));
+                    */
+                    String netName = projectName + ":" + controller.getManager().getCanonicalName(net);
+                    dstList.add(new PolicyRuleType.AddressType(null, netName, null));
+                }
+                dstPorts.add(new PolicyRuleType.PortType(portStart, portEnd));
+                srcList.add(new PolicyRuleType.AddressType(null, "local", null));
+                srcPorts.add(new PolicyRuleType.PortType(0, 65535));
+            } else {
+                for (String cidr: cidrList) {
+                    NetworkVO net = cidrToNetwork(controller, cidr);
+                    String netName = projectName + ":" + controller.getManager().getCanonicalName(net);
+                    dstList.add(new PolicyRuleType.AddressType(null, netName, null));
+                }
+                dstPorts.add(new PolicyRuleType.PortType(portStart, portEnd));
+
+                srcList.add(new PolicyRuleType.AddressType(null, "any", null));
+                srcPorts.add(new PolicyRuleType.PortType(0, 65535));
+            }
+
+            PolicyRuleType vnRule = new PolicyRuleType(
+                    new PolicyRuleType.SequenceType(1, 0), rule.getUuid(), "<>", protocol,
+                    srcList, srcPorts, null, dstList, dstPorts,
+                    new PolicyRuleType.ActionListType(action, null, null, null));
+            policyMap.addPolicyRule(vnRule);
+        }
+        _policyMap = policyMap;
+    }
+
+    /* for service instance policy */
+    public void build(ModelController modelController, String leftVn, String rightVn, String gatewayName,
+            List<String> siList, String action) {
+        if (_project != null) {
+            _fqName = StringUtils.join(_project.getQualifiedName(), ':') + ":" + _name;
+        } else {
+            _fqName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT + ":" + _name;
+        }
+
+        PolicyEntriesType policyMap = new PolicyEntriesType();
+        List<PolicyRuleType.AddressType> srcList = new ArrayList<PolicyRuleType.AddressType>();
+        srcList.add(new PolicyRuleType.AddressType(null, leftVn, null));
+        List<PolicyRuleType.AddressType> dstList = new ArrayList<PolicyRuleType.AddressType>();
+        dstList.add(new PolicyRuleType.AddressType(null, rightVn, null));
+
+        List<PolicyRuleType.PortType> portAny = new ArrayList<PolicyRuleType.PortType>();
+        portAny.add(new PolicyRuleType.PortType(0, 65535));
+
+        PolicyRuleType rule = new PolicyRuleType(
+                new PolicyRuleType.SequenceType(1, 0),  null, "<>", "any",
+                srcList, portAny, null, dstList, portAny,
+                new PolicyRuleType.ActionListType(action, gatewayName, siList, null));
+        policyMap.addPolicyRule(rule);
+        _policyMap = policyMap;
+    }
+
+    public boolean hasPolicyRules() {
+        if (_policyMap != null && _policyMap.getPolicyRule() != null && _policyMap.getPolicyRule().size() > 0) {
+            return true;
+        }
+        return false;
+    }
+
+    @Override
+    public int compareTo(ModelObject o) {
+        NetworkPolicyModel other;
+        try {
+            other = (NetworkPolicyModel) o;
+        } catch (ClassCastException ex) {
+            String clsname = o.getClass().getName();
+            return NetworkPolicyModel.class.getName().compareTo(clsname);
+        }
+        return _uuid.compareTo(other._uuid);
+    }
+
+    @Override
+    public void delete(ModelController controller) throws IOException {
+        ApiConnector api = controller.getApiAccessor();
+        if (_policy != null) {
+            api.delete(_policy);
+            _policy = null;
+        }
+    }
+
+    @Override
+    public void destroy(ModelController controller) throws IOException {
+    }
+
+    public String getUuid() {
+        return _uuid;
+    }
+
+    @Override
+    public void update(ModelController controller) throws InternalErrorException, IOException {
+        ApiConnector api = controller.getApiAccessor();
+        if (_project == null) {
+            s_logger.debug("Project is null for the policy: " + _name);
+            throw new IOException("Project is null for the policy: " + _name);
+        }
+
+        NetworkPolicy policy = _policy;
+
+        if (policy == null) {
+            try {
+                String policyId = api.findByName(NetworkPolicy.class, _project, _name);
+                if (policyId != null) {
+                    policy = _policy = (NetworkPolicy) api.findById(NetworkPolicy.class, policyId);
+                }
+                if (policy == null) {
+                    policy = new NetworkPolicy();
+                    policy.setUuid(_uuid);
+                    policy.setName(_name);
+                    policy.setParent(_project);
+                }
+            } catch (IOException ex) {
+                s_logger.warn("network-policy read", ex);
+                return;
+            }
+        }
+
+        policy.setEntries(_policyMap);
+        if (_policy == null) {
+            try {
+                api.create(policy);
+            } catch (Exception ex) {
+                s_logger.debug("network policy create", ex);
+                throw new CloudRuntimeException("Failed to create network policy", ex);
+            }
+            _policy = policy;
+        } else {
+            try {
+                api.update(policy);
+            } catch (IOException ex) {
+                s_logger.warn("network policy update", ex);
+                throw new CloudRuntimeException("Unable to update network policy", ex);
+            }
+        }
+        for (ModelObject successor: successors()) {
+            successor.update(controller);
+        }
+    }
+
+    @Override
+    public boolean verify(ModelController controller) {
+        return false;
+    }
+
+    @Override
+    public boolean compare(ModelController controller, ModelObject current) {
+        return true;
+    }
+
+    public void setProperties(ModelController controller, List<? extends NetworkACLItem> rules) {
+
+    }
+
+    public void setProject(Project project) {
+        _project = project;
+    }
+
+    public NetworkPolicy getPolicy() {
+        return _policy;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cc2b1c49/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java
index a9bc5c1..0ce22ad 100644
--- a/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java
+++ b/plugins/network-elements/juniper-contrail/src/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java
@@ -20,19 +20,15 @@ package org.apache.cloudstack.network.contrail.model;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.UUID;
 
 import net.juniper.contrail.api.ApiConnector;
 import net.juniper.contrail.api.ObjectReference;
-import net.juniper.contrail.api.types.NetworkPolicy;
-import net.juniper.contrail.api.types.PolicyEntriesType;
-import net.juniper.contrail.api.types.PolicyEntriesType.PolicyRuleType;
 import net.juniper.contrail.api.types.Project;
 import net.juniper.contrail.api.types.ServiceInstance;
 import net.juniper.contrail.api.types.ServiceInstanceType;
 import net.juniper.contrail.api.types.ServiceTemplate;
 import net.juniper.contrail.api.types.ServiceTemplateType;
-import net.juniper.contrail.api.types.VirtualNetwork;
-import net.juniper.contrail.api.types.VirtualNetworkPolicyType;
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
@@ -56,11 +52,11 @@ public class ServiceInstanceModel extends ModelObjectBase {
     private String _templateName;
     private String _templateId;
     private String _templateUrl;
-    private VirtualNetwork _left;
-    private VirtualNetwork _right;
+    private VirtualNetworkModel _left;
+    private VirtualNetworkModel _right;
     private ServiceTemplate _tmpl;
     private ServiceInstance _serviceInstance;
-    private NetworkPolicy _policy;
+    private NetworkPolicyModel _policy;
 
     /**
      * Create a ServiceInstance as result of an API call.
@@ -72,7 +68,7 @@ public class ServiceInstanceModel extends ModelObjectBase {
      * @param left
      * @param right
      */
-    public ServiceInstanceModel(Project project, String name, VirtualMachineTemplate template, ServiceOffering serviceOffering, VirtualNetwork left, VirtualNetwork right) {
+    public ServiceInstanceModel(Project project, String name, VirtualMachineTemplate template, ServiceOffering serviceOffering, VirtualNetworkModel left, VirtualNetworkModel right) {
         String parent_name;
         if (project != null) {
             parent_name = StringUtils.join(project.getQualifiedName(), ':');
@@ -84,8 +80,8 @@ public class ServiceInstanceModel extends ModelObjectBase {
         _mgmtName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT + ":" + ContrailManager.managementNetworkName;
         _left = left;
         _right = right;
-        _leftName = StringUtils.join(left.getQualifiedName(), ":");
-        _rightName = StringUtils.join(right.getQualifiedName(), ":");
+        _leftName = StringUtils.join(left.getVirtualNetwork().getQualifiedName(), ":");
+        _rightName = StringUtils.join(right.getVirtualNetwork().getQualifiedName(), ":");
 
         _templateName = template.getName();
         _templateId = template.getUuid();
@@ -110,28 +106,6 @@ public class ServiceInstanceModel extends ModelObjectBase {
         return _fqName.substring(_fqName.lastIndexOf(':') + 1);
     }
 
-    private void applyNetworkPolicy(ModelController controller, NetworkPolicy policy, VirtualNetwork left, VirtualNetwork right) {
-        left.setNetworkPolicy(policy, new VirtualNetworkPolicyType(new VirtualNetworkPolicyType.SequenceType(1, 0), null));
-        // TODO: network_ipam_refs attr is missing
-        left.clearNetworkIpam();
-        try {
-            ApiConnector api = controller.getApiAccessor();
-            api.update(left);
-        } catch (IOException ex) {
-            throw new CloudRuntimeException("Unable to update virtual-network", ex);
-        }
-
-        right.setNetworkPolicy(policy, new VirtualNetworkPolicyType(new VirtualNetworkPolicyType.SequenceType(1, 0), null));
-        // TODO: network_ipam_refs attr is missing
-        right.clearNetworkIpam();
-        try {
-            ApiConnector api = controller.getApiAccessor();
-            api.update(right);
-        } catch (IOException ex) {
-            throw new CloudRuntimeException("Unable to update virtual-network", ex);
-        }
-    }
-
     /**
      * Recreate the model object from the Contrail API which is the master for this type of object.
      * @param siObj
@@ -151,18 +125,6 @@ public class ServiceInstanceModel extends ModelObjectBase {
                 s_logger.warn("service-template read", ex);
             }
         }
-        try {
-            Project project = (Project)api.findById(Project.class, siObj.getParentUuid());
-            if (project != null) {
-                _projectId = project.getUuid();
-            }
-            String policyId = api.findByName(NetworkPolicy.class, project, siObj.getName());
-            if (policyId != null) {
-                _policy = (NetworkPolicy)api.findById(NetworkPolicy.class, policyId);
-            }
-        } catch (IOException ex) {
-            s_logger.warn("network-policy read", ex);
-        }
     }
 
     @Override
@@ -207,40 +169,52 @@ public class ServiceInstanceModel extends ModelObjectBase {
         return si_obj;
     }
 
-    private NetworkPolicy createServicePolicy(ModelController controller) {
-        NetworkPolicy policy = new NetworkPolicy();
-        policy.setParent(_serviceInstance.getParent());
-        policy.setName(_serviceInstance.getName());
-        PolicyEntriesType policy_map = new PolicyEntriesType();
-        List<PolicyRuleType.AddressType> srcList = new ArrayList<PolicyRuleType.AddressType>();
-        srcList.add(new PolicyRuleType.AddressType(null, _leftName, null));
-        List<PolicyRuleType.AddressType> dstList = new ArrayList<PolicyRuleType.AddressType>();
-        dstList.add(new PolicyRuleType.AddressType(null, _rightName, null));
+    private void clearServicePolicy(ModelController controller) {
+       _left.addToNetworkPolicy(null);
+       _right.addToNetworkPolicy(null);
+       try {
+            controller.getManager().getDatabase().getNetworkPolicys().remove(_policy);
+            _policy.delete(controller.getManager().getModelController());
+            _policy = null;
+        } catch (Exception e) {
+            s_logger.error(e);
+        }
+       try {
+            _left.update(controller.getManager().getModelController());
+            _right.update(controller.getManager().getModelController());
+        } catch (Exception ex) {
+            s_logger.error("virtual-network update for policy delete: ", ex);
+        }
+    }
+
+    private NetworkPolicyModel setServicePolicy(ModelController controller) {
+        NetworkPolicyModel policyModel = new NetworkPolicyModel(UUID.randomUUID().toString(), _serviceInstance.getName());
+        policyModel.setProject((Project)_serviceInstance.getParent());
+        _left.addToNetworkPolicy(policyModel);
+        _right.addToNetworkPolicy(policyModel);
         List<String> siList = new ArrayList<String>();
         siList.add(StringUtils.join(_serviceInstance.getQualifiedName(), ':'));
-        List<PolicyRuleType.PortType> portAny = new ArrayList<PolicyRuleType.PortType>();
-        portAny.add(new PolicyRuleType.PortType(0, 65535));
-
-        PolicyRuleType rule =
-            new PolicyRuleType(new PolicyRuleType.SequenceType(1, 0), /* uuid */null, "<>", "any", srcList, portAny, /* application */null, dstList, portAny,
-                new PolicyRuleType.ActionListType("pass", "in-network", siList, null));
-        policy_map.addPolicyRule(rule);
-        policy.setEntries(policy_map);
-
+       try {
+            policyModel.build(controller.getManager().getModelController(), _leftName, _rightName, "in-network", siList, "pass");
+        } catch (Exception e) {
+            s_logger.error(e);
+            return null;
+        }
         try {
-            ApiConnector api = controller.getApiAccessor();
-            if (!api.create(policy)) {
-                throw new CloudRuntimeException("Unable to create network-policy");
+            if (!policyModel.verify(controller.getManager().getModelController())) {
+                policyModel.update(controller.getManager().getModelController());
             }
-        } catch (IOException ex) {
-            throw new CloudRuntimeException("Unable to create network-policy", ex);
+            controller.getManager().getDatabase().getNetworkPolicys().add(policyModel);
+        } catch (Exception ex) {
+            s_logger.error("network-policy update: ", ex);
         }
-        return policy;
+        return policyModel;
     }
 
     @Override
     public void delete(ModelController controller) throws IOException {
         ApiConnector api = controller.getApiAccessor();
+        clearServicePolicy(controller);
         if (_serviceInstance != null) {
             api.delete(_serviceInstance);
         }
@@ -291,9 +265,7 @@ public class ServiceInstanceModel extends ModelObjectBase {
         }
         _uuid = _serviceInstance.getUuid();
         if (_policy == null) {
-            _policy = createServicePolicy(controller);
-            // TODO: update the network model objects and call update
-            applyNetworkPolicy(controller, _policy, _left, _right);
+            _policy = setServicePolicy(controller);
         }
     }
 


Mime
View raw message