You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ch...@apache.org on 2013/10/08 15:38:37 UTC
[5/6] Contrail network virtualization plugin.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ContrailManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ContrailManagerImpl.java b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ContrailManagerImpl.java
new file mode 100644
index 0000000..271b016
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ContrailManagerImpl.java
@@ -0,0 +1,717 @@
+package net.juniper.contrail.management;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+
+import net.juniper.contrail.api.ApiConnector;
+import net.juniper.contrail.api.ApiConnectorFactory;
+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.VirtualNetwork;
+import net.juniper.contrail.model.FloatingIpModel;
+import net.juniper.contrail.model.FloatingIpPoolModel;
+import net.juniper.contrail.model.ModelController;
+import net.juniper.contrail.model.VirtualNetworkModel;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.configuration.ConfigurationManager;
+import com.cloud.configuration.ConfigurationService;
+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.projects.ProjectVO;
+import com.cloud.user.dao.AccountDao;
+import com.cloud.user.Account;
+import com.cloud.network.Network;
+import com.cloud.network.Network.Provider;
+import com.cloud.network.Network.Service;
+import com.cloud.network.Networks.TrafficType;
+import com.cloud.network.PublicIpAddress;
+import com.cloud.network.dao.IPAddressDao;
+import com.cloud.network.dao.IPAddressVO;
+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.dao.PhysicalNetworkVO;
+import com.cloud.offering.NetworkOffering.State;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.offering.NetworkOffering.Availability;
+import com.cloud.offerings.NetworkOfferingVO;
+import com.cloud.offerings.dao.NetworkOfferingDao;
+import com.cloud.projects.dao.ProjectDao;
+import com.cloud.utils.component.ComponentLifecycle;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria.Op;
+import com.google.common.collect.ImmutableList;
+
+import java.util.Properties;
+
+import com.cloud.utils.PropertiesUtil;
+import com.cloud.vm.VMInstanceVO;
+import com.cloud.vm.dao.NicDao;
+import com.cloud.vm.dao.UserVmDao;
+import com.cloud.vm.dao.VMInstanceDao;
+
+import java.io.File;
+import java.io.FileInputStream;
+
+@Component
+public class ContrailManagerImpl extends ManagerBase implements ContrailManager {
+ @Inject public ConfigurationService _configService;
+ @Inject NetworkOfferingDao _networkOfferingDao;
+
+ @Inject DomainDao _domainDao;
+ @Inject NetworkDao _networksDao;
+ @Inject VMInstanceDao _vmInstanceDao;
+ @Inject ProjectDao _projectDao;
+ @Inject AccountDao _accountDao;
+ @Inject DataCenterDao _dcDao;
+ @Inject PhysicalNetworkDao _physicalNetworkDao;
+ @Inject PhysicalNetworkServiceProviderDao _physProviderDao;
+ @Inject NicDao _nicDao;
+ @Inject ServerDBSync _dbSync;
+ @Inject ServerEventHandler _eventHandler;
+ @Inject IPAddressDao _ipAddressDao;
+ @Inject VlanDao _vlanDao;
+ @Inject UserVmDao _vmDao;
+
+ private static final Logger s_logger = Logger.getLogger(ContrailManager.class);
+
+ private ApiConnector _api;
+
+ private NetworkOffering _offering;
+ private Timer _dbSyncTimer;
+ private int _dbSyncInterval = DB_SYNC_INTERVAL_DEFAULT;
+ private final String configuration = "contrail.properties";
+ private ModelDatabase _database;
+ private ModelController _controller;
+
+ ContrailManagerImpl() {
+ setRunLevel(ComponentLifecycle.RUN_LEVEL_COMPONENT);
+ _database = new ModelDatabase();
+ }
+
+ @Override
+ public boolean start() {
+ /* Start background task */
+ _dbSyncTimer = new Timer("DBSyncTimer");
+ try {
+ _dbSyncTimer.schedule(new DBSyncTask(), 0, _dbSyncInterval);
+ } catch (Exception ex) {
+ s_logger.debug("Unable to start DB Sync timer " + ex.getMessage());
+ s_logger.debug("timer start", ex);
+ }
+ return true;
+ }
+ @Override
+ public boolean stop() {
+ _dbSyncTimer.cancel();
+ return true;
+ }
+
+ public ModelDatabase getDatabase() {
+ return _database;
+ }
+
+ private NetworkOffering LocateOffering() {
+ List<? extends NetworkOffering> offerList = _configService.listNetworkOfferings(TrafficType.Guest, false);
+ for (NetworkOffering offer: offerList) {
+ if (offer.getName().equals(offeringName)) {
+ if (offer.getState() != 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);
+ 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.Guest, null, false, Availability.Optional, null, serviceProviderMap, true,
+ Network.GuestType.Isolated, false, null, false, null, false, true, null, true, 100);
+
+ voffer.setState(State.Enabled);
+ long id = voffer.getId();
+ _networkOfferingDao.update(id, voffer);
+ return _networkOfferingDao.findById(id);
+ }
+
+ private NetworkOffering EnableNetworkOffering(long id) {
+ NetworkOfferingVO offering = _networkOfferingDao.createForUpdate(id);
+ offering.setState(State.Enabled);
+ _networkOfferingDao.update(id, offering);
+ return _networkOfferingDao.findById(id);
+ }
+
+ @Override
+ 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");
+ int port = 0;
+ 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();
+ }
+
+ _controller = new ModelController(this, _api, _vmDao, _networksDao, _nicDao, _vlanDao, _ipAddressDao);
+
+ _offering = LocateOffering();
+
+ _eventHandler.subscribe();
+
+ initializeDefaultVirtualNetworkModels();
+
+ return true;
+ }
+
+ @Override
+ public NetworkOffering getOffering() {
+ return _offering;
+ }
+
+ @Override
+ public String getPhysicalNetworkName(PhysicalNetworkVO phys_net) {
+ String physname = phys_net.getName();
+ physname = physname.replaceAll("\\s", "");
+ physname.replace("_", "");
+ return physname;
+ }
+
+ @Override
+ public String getDomainCanonicalName(DomainVO domain) {
+ if (domain.getId() == Domain.ROOT_DOMAIN) {
+ return VNC_ROOT_DOMAIN;
+ }
+ return domain.getName();
+ }
+
+ @Override
+ public String getProjectCanonicalName(ProjectVO project) {
+ return project.getName();
+ }
+
+ @Override
+ public String getCanonicalName(Network net) {
+ String netname;
+ if (net.getTrafficType() == TrafficType.Guest) {
+ return net.getName();
+ } else if (net.getTrafficType() == TrafficType.Management || net.getTrafficType() == TrafficType.Storage) {
+ return managementNetworkName;
+ } else if (net.getTrafficType() == TrafficType.Control) {
+ return "__link_local__";
+ } else {
+ DataCenter zone = _dcDao.findById(net.getDataCenterId());
+ String zonename = zone.getName();
+ zonename = zonename.replaceAll("\\s", "");
+ zonename = zonename.replace("-", "_");
+ netname = "__" + zonename + "_" + net.getTrafficType().toString() + "__";
+ }
+ return netname;
+ }
+
+ @Override
+ public String getDomainName(long domainId) {
+ if (domainId != Domain.ROOT_DOMAIN) {
+ DomainVO domain = _domainDao.findById(domainId);
+ return domain.getName();
+ }
+ return VNC_ROOT_DOMAIN;
+ }
+
+ @Override
+ public String getProjectName(long accountId) {
+ Account account = _accountDao.findById(accountId);
+ if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
+ ProjectVO project = _projectDao.findByProjectAccountId(account.getId());
+ if (project != null) {
+ return project.getName();
+ }
+ }
+ return VNC_DEFAULT_PROJECT;
+ }
+
+ @Override
+ public String getDefaultPublicNetworkFQN() {
+ String name = VNC_ROOT_DOMAIN + ":" + VNC_DEFAULT_PROJECT + ":" + "__default_Public__";
+ return name;
+ }
+
+ private ProjectVO getProject(long accountId) {
+ Account account = _accountDao.findById(accountId);
+ if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
+ return _projectDao.findByProjectAccountId(account.getId());
+ }
+ return null;
+ }
+
+ @Override
+ public String getProjectId(long domainId, long accountId) throws IOException {
+ ProjectVO project = getProject(accountId);
+ if (project != null) {
+ return project.getUuid();
+ }
+ DomainVO domain = _domainDao.findById(domainId);
+ if (domain.getId() != Domain.ROOT_DOMAIN) {
+ net.juniper.contrail.api.types.Domain vncDomain = (net.juniper.contrail.api.types.Domain)
+ _api.findById(net.juniper.contrail.api.types.Domain.class, domain.getUuid());
+ return _api.findByName(net.juniper.contrail.api.types.Project.class, vncDomain, VNC_DEFAULT_PROJECT);
+ }
+ return null;
+ }
+
+ @Override
+ 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 (net.juniper.contrail.api.types.Project)
+ _api.findById(net.juniper.contrail.api.types.Project.class, projectId);
+ }
+
+ @Override
+ public String getFQN(Network net) {
+ // domain, project, name
+ String fqname = getDomainName(net.getDomainId());
+ fqname += ":" + getProjectName(net.getAccountId()) + ":";
+ return fqname + getCanonicalName(net);
+ }
+
+ public void findInfrastructureNetworks(PhysicalNetworkVO phys, List<NetworkVO> dbList) {
+ final TrafficType[] ttypes = {
+ TrafficType.Control, // maps to __link_local__
+ TrafficType.Management, // maps to ip-fabric
+ TrafficType.Public,
+ TrafficType.Storage // maps to ip-fabric
+ };
+
+ for (int i = 0; i < ttypes.length; i++) {
+ List<NetworkVO> phys_nets;
+ phys_nets = _networksDao.listByZoneAndTrafficType(phys.getDataCenterId(), ttypes[i]);
+ dbList.addAll(phys_nets);
+ }
+
+ }
+
+ public void syncNetworkDB(short syncMode) throws IOException {
+ if (_dbSync.syncAll(syncMode) == ServerDBSync.SYNC_STATE_OUT_OF_SYNC) {
+ if (syncMode == DBSyncGeneric.SYNC_MODE_CHECK) {
+ s_logger.info("# Cloudstack DB & VNC are out of sync #");
+ } else {
+ s_logger.info("# Cloudstack DB & VNC were out of sync, performed re-sync operation #");
+ }
+ } else {
+ s_logger.info("# Cloudstack DB & VNC are in sync #");
+ }
+ }
+
+ public class DBSyncTask extends TimerTask {
+ private short _syncMode = DBSyncGeneric.SYNC_MODE_UPDATE;
+ @Override
+ public void run() {
+ try {
+ s_logger.debug("DB Sync task is running");
+ syncNetworkDB(_syncMode);
+ // Change to check mode
+ _syncMode = DBSyncGeneric.SYNC_MODE_CHECK;
+ } catch (Exception ex) {
+ s_logger.debug(ex);
+ s_logger.info("Unable to sync network db");
+ }
+ }
+ }
+
+
+ @Override
+ 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) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public String findVirtualNetworkId(Network net) throws IOException {
+ if (net.getTrafficType() == TrafficType.Guest) {
+ return net.getUuid();
+ }
+ String netname = getDomainName(net.getDomainId()) + ":" + getProjectName(net.getAccountId()) + ":";
+
+ if (net.getTrafficType() == TrafficType.Control) {
+ netname += "__link_local__";
+ } else if (net.getTrafficType() == TrafficType.Management || net.getTrafficType() == TrafficType.Storage) {
+ netname += managementNetworkName;
+ } else {
+ netname = getFQN(net);
+ }
+ List<String> fqn = ImmutableList.copyOf(StringUtils.split(netname, ':'));
+ return _api.findByName(VirtualNetwork.class, fqn);
+ }
+
+ @Override
+ public VirtualNetwork findDefaultVirtualNetwork(TrafficType trafficType) throws IOException {
+ if (trafficType == TrafficType.Guest ||
+ trafficType == TrafficType.Public) {
+ return null;
+ }
+ String netname = VNC_ROOT_DOMAIN + ":" + VNC_DEFAULT_PROJECT + ":";
+ if (trafficType == TrafficType.Control) {
+ netname += "__link_local__";
+ } else if (trafficType == TrafficType.Management || trafficType == TrafficType.Storage) {
+ netname += managementNetworkName;
+ }
+ return (VirtualNetwork)_api.findByFQN(VirtualNetwork.class, netname);
+ }
+
+ /*
+ * Returns list of networks managed by Juniper VRouter filtered by traffic types
+ */
+ @Override
+ public List<NetworkVO> findJuniperManagedNetworks(List<TrafficType> types) {
+
+ SearchBuilder<NetworkVO> searchBuilder = _networksDao.createSearchBuilder();
+ searchBuilder.and("trafficType", searchBuilder.entity().getTrafficType(), Op.IN);
+ searchBuilder.and("networkOfferingId", searchBuilder.entity().getNetworkOfferingId(), Op.EQ);
+
+ SearchCriteria<NetworkVO> sc = searchBuilder.create();
+ sc.setParameters("networkOfferingId", getOffering().getId());
+
+ 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);
+ types.add(TrafficType.Guest);
+ }
+ sc.setParameters("trafficType", types.toArray());
+
+ List<NetworkVO> dbNets = _networksDao.search(sc, null);
+ if (dbNets == null) {
+ s_logger.debug("no juniper managed networks for the given traffic types: " + types.toString());
+ dbNets = new ArrayList<NetworkVO>();
+ }
+
+ List<PhysicalNetworkVO> phys_list = _physicalNetworkDao.listAll();
+ final String provider = Network.Provider.JuniperContrail.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()) {
+ dbNets.add(net);
+ continue;
+ }
+ for(TrafficType type:types) {
+ if (net.getTrafficType() == type) {
+ dbNets.add(net);
+ break;
+ }
+ }
+ }
+ }
+ }
+ return dbNets;
+ }
+
+ /*
+ * Returns list of public ip addresses managed by Juniper VRouter
+ */
+ @Override
+ public List<IPAddressVO> findJuniperManagedPublicIps() {
+
+ List<NetworkVO> dbNets = findJuniperManagedNetworks(null);
+
+ if (dbNets == null || dbNets.isEmpty()) {
+ s_logger.debug("Juniper managed networks is empty");
+ return null;
+ }
+
+ SearchBuilder<IPAddressVO> searchBuilder = _ipAddressDao.createSearchBuilder();
+ searchBuilder.and("sourceNat", searchBuilder.entity().isSourceNat(), Op.EQ);
+ searchBuilder.and("network", searchBuilder.entity().getAssociatedWithNetworkId(), Op.IN);
+ searchBuilder.and("oneToOneNat", searchBuilder.entity().isOneToOneNat(), Op.EQ);
+ searchBuilder.and("associatedWithVmId", searchBuilder.entity().getAssociatedWithVmId(), Op.NNULL);
+
+ List<Long> netIds = new ArrayList<Long>();
+ for (NetworkVO net:dbNets) {
+ netIds.add(net.getId());
+ }
+
+ SearchCriteria<IPAddressVO> sc = searchBuilder.create();
+ sc.setParameters("oneToOneNat", true);
+ sc.setParameters("sourceNat", false);
+ sc.setParameters("network", netIds.toArray());
+
+ List<IPAddressVO> publicIps = _ipAddressDao.search(sc, null);
+ if (publicIps == null) {
+ s_logger.debug("no public ips");
+ return null;
+ }
+
+ return publicIps;
+ }
+
+ private void initializeDefaultVirtualNetworkModels() {
+ List<TrafficType> types = new ArrayList<TrafficType>();
+ types.add(TrafficType.Management);
+ types.add(TrafficType.Storage);
+ types.add(TrafficType.Control);
+
+ List<NetworkVO> dbNets = findJuniperManagedNetworks(types);
+ for (NetworkVO net:dbNets) {
+
+ VirtualNetworkModel vnModel = getDatabase().lookupVirtualNetwork(null, getCanonicalName(net), net.getTrafficType());
+ if (vnModel == null) {
+ vnModel = new VirtualNetworkModel(net, null, getCanonicalName(net), net.getTrafficType());
+ vnModel.build(getModelController(), net);
+ try {
+ if (!vnModel.verify(getModelController())) {
+ vnModel.update(getModelController());
+ }
+ } catch (Exception ex) {
+ s_logger.warn("virtual-network update: ", ex);
+ }
+ getDatabase().getVirtualNetworks().add(vnModel);
+ }
+ }
+ }
+
+ @Override
+ public boolean isSystemDefaultNetwork(VirtualNetwork vnet) {
+ List<String> fqn = vnet.getQualifiedName();
+ if (fqn.size() < 3) {
+ return false;
+ }
+ List<String> default_parent = vnet.getDefaultParent();
+ int index = 0;
+ for (Iterator<String> iter = default_parent.iterator(); iter.hasNext(); index++) {
+ String piece = iter.next();
+ if (!piece.equals(fqn.get(index))) {
+ return false;
+ }
+ }
+ List<String> default_networks = ImmutableList.of("__link_local__", "default-virtual-network", managementNetworkName);
+ for (Iterator<String> iter = default_networks.iterator(); iter.hasNext();) {
+ String name = iter.next();
+ if (name.equals(fqn.get(index))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isSystemDefaultNetwork(NetworkVO net) {
+ if (net.getTrafficType() == TrafficType.Management || net.getTrafficType() == TrafficType.Storage
+ || net.getTrafficType() == TrafficType.Control) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isSystemRootDomain(net.juniper.contrail.api.types.Domain domain) {
+ if (domain.getName().compareTo(VNC_ROOT_DOMAIN) == 0) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isSystemRootDomain(DomainVO domain) {
+ if (domain.getId() == Domain.ROOT_DOMAIN || domain.getName().compareTo("ROOT") == 0 ||
+ domain.getParent() == null) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isSystemDefaultProject(net.juniper.contrail.api.types.Project project) {
+ if (project.getName().compareTo(VNC_DEFAULT_PROJECT) == 0) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isSystemDefaultProject(ProjectVO project) {
+ return false;
+ }
+
+ @Override
+ public String getVifNameByVmName(String vm_name, Integer device_id) {
+ String vif_name = vm_name + "-" + device_id.toString();
+ return vif_name;
+ }
+
+ @Override
+ public String getVifNameByVmUuid(String vm_uuid, Integer device_id) {
+ VMInstanceVO vm = _vmInstanceDao.findByUuid(vm_uuid);
+ if (vm != null) {
+ return vm.getInstanceName() + "-" + device_id.toString();
+ }
+ return null;
+ }
+
+ @Override
+ public ModelController getModelController() {
+ return _controller;
+ }
+
+ @Override
+ public ApiConnector getApiConnector() {
+ return _api;
+ }
+
+ public VirtualNetworkModel lookupPublicNetworkModel() {
+ List<TrafficType> types = new ArrayList<TrafficType>();
+ types.add(TrafficType.Public);
+ List<NetworkVO> dbNets = findJuniperManagedNetworks(types);
+ if (dbNets == null) {
+ return null;
+ }
+ NetworkVO net = dbNets.get(0);
+
+ VirtualNetworkModel vnModel = getDatabase().lookupVirtualNetwork(net.getUuid(), getCanonicalName(net), TrafficType.Public);
+ return vnModel;
+ }
+
+ public boolean createFloatingIp(PublicIpAddress ip) {
+ VirtualNetworkModel vnModel = lookupPublicNetworkModel();
+ assert vnModel != null : "public network vn model is null";
+ FloatingIpPoolModel fipPoolModel = vnModel.getFipPoolModel();
+
+ /* create only, no updates */
+ if (fipPoolModel == null) {
+ fipPoolModel = new FloatingIpPoolModel();
+ fipPoolModel.addToVirtualNetwork(vnModel);
+ fipPoolModel.build(getModelController());
+ try {
+ fipPoolModel.update(getModelController());
+ vnModel.setFipPoolModel(fipPoolModel);
+ } catch (Exception ex) {
+ s_logger.warn("floating-ip-pool create: ", ex);
+ return false;
+ }
+ }
+
+ FloatingIpModel fipModel = fipPoolModel.getFloatingIpModel(ip.getUuid());
+ /* create only, no updates*/
+ if (fipModel == null) {
+ fipModel = new FloatingIpModel(ip.getUuid());
+ fipModel.addToFloatingIpPool(fipPoolModel);
+ fipModel.build(getModelController(), ip);
+ try {
+ fipModel.update(getModelController());
+ } catch (Exception ex) {
+ s_logger.warn("floating-ip create: ", ex);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public boolean deleteFloatingIp(PublicIpAddress ip) {
+ VirtualNetworkModel vnModel = lookupPublicNetworkModel();
+ assert vnModel != null : "public network model is null";
+ FloatingIpPoolModel fipPoolModel = vnModel.getFipPoolModel();
+ FloatingIpModel fipModel = fipPoolModel.getFloatingIpModel(ip.getUuid());
+ if (fipModel != null) {
+ try {
+ fipModel.destroy(getModelController());
+ } catch (IOException ex) {
+ s_logger.warn("floating ip delete", ex);
+ return false;
+ }
+ fipPoolModel.removeSuccessor(fipModel);
+ if (!fipPoolModel.hasDescendents()) {
+ try {
+ fipPoolModel.delete(getModelController());
+ vnModel.setFipPoolModel(null);
+ } catch (IOException e) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<FloatingIp> getFloatingIps() {
+ String fipPoolName = getDefaultPublicNetworkFQN() + ":PublicIpPool";
+ FloatingIpPool fipPool = null;
+ try {
+ fipPool = (FloatingIpPool)_api.findByFQN(FloatingIpPool.class, fipPoolName);
+ } catch (Exception ex) {
+ s_logger.debug(ex);
+ }
+ if (fipPool == null) {
+ return null;
+ }
+ List<ObjectReference<ApiPropertyBase>> ips = fipPool.getFloatingIps();
+ if (ips != null) {
+ try {
+ return (List<FloatingIp>) _api.getObjects(FloatingIp.class, ips);
+ } catch(IOException ex) {
+ s_logger.debug(ex);
+ return null;
+ }
+ }
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/DBSyncGeneric.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/DBSyncGeneric.java b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/DBSyncGeneric.java
new file mode 100644
index 0000000..54e2e14
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/DBSyncGeneric.java
@@ -0,0 +1,305 @@
+package net.juniper.contrail.management;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+
+import org.apache.cloudstack.api.Identity;
+
+import net.juniper.contrail.api.ApiObjectBase;
+
+import org.apache.log4j.Logger;
+
+public class DBSyncGeneric {
+
+ private static final Logger s_logger = Logger.getLogger(DBSyncGeneric.class);
+
+ /* for each synchronization VNC class, following methods
+ * needs to be defined.
+ * For e.q : VirtualNetwork class should have createMethodPrefix+"VirtualNetwork" etc
+ */
+ private final String createMethodPrefix = "create";
+ private final String deleteMethodPrefix = "delete";
+ private final String compareMethodPrefix = "compare";
+ private final String filterMethodPrefix = "filter";
+ private final String equalMethodPrefix = "equal";
+ private final String syncMethodPrefix = "sync";
+ /* default db, vnc comparators are implemented based on uuid values,
+ * if user defined comparators are required, then only add these methods
+ */
+ private final String dbComparatorMethodPrefix = "dbComparator";
+ private final String vncComparatorMethodPrefix = "vncComparator";
+
+ /* sync methods implementation object, if implemented in seperate class
+ * set the scope object
+ */
+ private Object _scope;
+ private HashMap<String, Method> _methodMap;
+ private short _syncMode;
+
+ public static final short SYNC_MODE_UPDATE = 0;
+ public static final short SYNC_MODE_CHECK = 1;
+
+ public DBSyncGeneric(Object scope) {
+ this._scope = scope;
+ this._syncMode = SYNC_MODE_UPDATE;
+ setMethodMap();
+ }
+
+ public DBSyncGeneric() {
+ this._scope = this;
+ this._syncMode = SYNC_MODE_UPDATE;
+ setMethodMap();
+ }
+
+ public void setSyncMode(short mode) {
+ this._syncMode = mode;
+ }
+
+ public short getSyncMode() {
+ return this._syncMode;
+ }
+
+ public void setScope(Object scope) {
+ this._scope = scope;
+ setMethodMap();
+ }
+
+ public void setMethodMap() {
+ _methodMap = new HashMap<String, Method>();
+ Method methods[] = _scope.getClass().getMethods();
+ for (int i = 0; i < methods.length; i++) {
+ _methodMap.put(methods[i].getName(), methods[i]);
+ }
+ }
+
+ public static String getClassName(Class<?> cls) {
+ String clsname = cls.getName();
+ int loc = clsname.lastIndexOf('.');
+ if (loc > 0) {
+ clsname = clsname.substring(loc + 1);
+ }
+ return clsname;
+ }
+
+ /*
+ * This API can be used to sync a particular vnc class
+ */
+ public Boolean sync(Class<?> cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
+ String syncMethod = syncMethodPrefix + getClassName(cls);
+ Method method = _methodMap.get(syncMethod);
+ if (method == null) throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + syncMethod);
+ return (Boolean)method.invoke(_scope, parameters);
+ }
+
+ private void create(Class<?> cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
+ String createMethod = createMethodPrefix + getClassName(cls);
+ Method method = _methodMap.get(createMethod);
+ if (method == null) throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + createMethod);
+ method.invoke(_scope, parameters);
+ }
+
+ private void delete(Class<?> cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
+ String deleteMethod = deleteMethodPrefix + getClassName(cls);
+ Method method = _methodMap.get(deleteMethod);
+ if (method == null) throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + deleteMethod);
+ method.invoke(_scope, parameters);
+ }
+
+ private Integer compare(Class<?> cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
+ String compareMethod = compareMethodPrefix + getClassName(cls);
+ Method method = _methodMap.get(compareMethod);
+ if (method == null) throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + compareMethod);
+ return (Integer)method.invoke(_scope, parameters);
+ }
+
+ private Boolean filter(Class<?> cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
+ String filterMethod = filterMethodPrefix + getClassName(cls);
+ Method method = _methodMap.get(filterMethod);
+ if (method == null) {
+ s_logger.debug("Method not implemented: " + getClassName(_scope.getClass()) + ":" + filterMethod);
+ return false;
+ }
+ return (Boolean)method.invoke(_scope, parameters);
+ }
+
+ private Boolean equal(Class<?> cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
+ String equalMethod = equalMethodPrefix + getClassName(cls);
+ Method method = _methodMap.get(equalMethod);
+ if (method == null) {
+ s_logger.debug("Method not implemented: " + getClassName(_scope.getClass()) + ":" + equalMethod);
+ return true;
+ }
+ return (Boolean)method.invoke(_scope, parameters);
+ }
+
+ @SuppressWarnings("rawtypes")
+ private Comparator dbComparator(Class<?> cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
+ String dbComparatorMethod = dbComparatorMethodPrefix + getClassName(cls);
+ Method method = _methodMap.get(dbComparatorMethod);
+ if (method == null) return dbComparatorDefault();
+ return (Comparator)method.invoke(_scope, parameters);
+ }
+
+ @SuppressWarnings("rawtypes")
+ private Comparator vncComparator(Class<?> cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
+ String vncComparatorMethod = vncComparatorMethodPrefix + getClassName(cls);
+ Method method = _methodMap.get(vncComparatorMethod);
+ if (method == null) return vncComparatorDefault();
+ return (Comparator)method.invoke(_scope, parameters);
+ }
+
+
+ @SuppressWarnings("rawtypes")
+ public Comparator dbComparatorDefault() {
+ Comparator comparator = new Comparator<Identity>() {
+ public int compare(Identity u1, Identity u2) {
+ return u1.getUuid().compareTo(u2.getUuid());
+ }
+ };
+ return comparator;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public Comparator vncComparatorDefault() {
+ Comparator comparator = new Comparator<ApiObjectBase>() {
+ public int compare(ApiObjectBase u1, ApiObjectBase u2) {
+ return u1.getUuid().compareTo(u2.getUuid());
+ }
+ };
+ return comparator;
+ }
+
+
+ public static class SyncStats {
+ public int create;
+ public int delete;
+ public int equal;
+ public int diff;
+ public int filter;
+ public StringBuffer logMsg;
+ SyncStats() {
+ logMsg = new StringBuffer();
+ }
+ void log(String str) {
+ logMsg.append(str);
+ logMsg.append('\n');
+ }
+ public boolean isSynchronized() {
+ return create == 0 && delete == 0 && diff == 0;
+ }
+ public String toString() {
+ StringBuffer str = new StringBuffer();
+ str.append("create: " + create);
+ str.append(", delete: " + delete);
+ if (filter > 0) {
+ str.append(", filter: " + filter);
+ }
+ str.append(", equal: " + equal);
+ str.append(", diff:" + diff);
+ return str.toString();
+ }
+ }
+
+ public void syncCollections(Class<?> cls, Collection<?> lhsList, Collection<?> rhsList, boolean modifyMode,
+ SyncStats stats) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
+ java.util.Iterator<?> lhsIter = lhsList.iterator();
+ java.util.Iterator<?> rhsIter = rhsList.iterator();
+
+ Object lhsItem = lhsIter.hasNext() ? lhsIter.next() : null;
+ Object rhsItem = rhsIter.hasNext() ? rhsIter.next() : null;
+
+ while (lhsItem != null && rhsItem != null) {
+ Integer cmp = this.compare(cls, lhsItem, rhsItem, stats.logMsg);
+ if (cmp < 0) {
+ // Create
+ if (modifyMode) {
+ this.create(cls, lhsItem, stats.logMsg);
+ }
+ stats.create++;
+ lhsItem = lhsIter.hasNext() ? lhsIter.next() : null;
+ } else if (cmp > 0) {
+ // Delete
+ if (!this.filter(cls, rhsItem, stats.logMsg)) {
+ if (modifyMode) {
+ this.delete(cls, rhsItem, stats.logMsg);
+ }
+ stats.delete++;
+ } else {
+ stats.filter++;
+ }
+ rhsItem = rhsIter.hasNext() ? rhsIter.next() : null;
+ } else {
+ // Equal
+ if (this.equal(cls, lhsItem, rhsItem, stats.logMsg)) {
+ stats.equal++;
+ } else {
+ stats.diff++;
+ }
+ lhsItem = lhsIter.hasNext() ? lhsIter.next() : null;
+ rhsItem = rhsIter.hasNext() ? rhsIter.next() : null;
+ }
+ }
+
+ while (lhsItem != null) {
+ // Create
+ if (modifyMode) {
+ this.create(cls, lhsItem, stats.logMsg);
+ }
+ stats.create++;
+ lhsItem = lhsIter.hasNext() ? lhsIter.next() : null;
+ }
+
+ while (rhsItem != null) {
+ // Delete
+ if (!this.filter(cls, rhsItem, stats.logMsg)) {
+ if (modifyMode) {
+ this.delete(cls, rhsItem, stats.logMsg);
+ }
+ stats.delete++;
+ } else {
+ stats.filter++;
+ }
+ rhsItem = rhsIter.hasNext() ? rhsIter.next() : null;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public boolean syncGeneric(Class<?> cls, List<?> dbList, List<?> vncList) throws Exception {
+ SyncStats stats = new SyncStats();
+ stats.log("Sync log for <" + getClassName(cls) + ">");
+
+ s_logger.debug("Generic db sync : " + getClassName(cls));
+
+ java.util.Collections.sort(dbList, this.dbComparator(cls));
+ java.util.Collections.sort(vncList, this.vncComparator(cls));
+
+ syncCollections(cls, dbList, vncList, _syncMode != SYNC_MODE_CHECK, stats);
+
+ if (_syncMode != SYNC_MODE_CHECK) {
+ s_logger.debug("Sync stats<" + getClassName(cls) + ">: " + stats.toString());
+ s_logger.debug(stats.logMsg);
+ s_logger.debug("Generic db sync : " + getClassName(cls) + " done");
+ } else {
+ s_logger.debug("Sync state checking stats<" + getClassName(cls) + ">: " + stats.toString());
+ if (!stats.isSynchronized()) {
+ s_logger.debug("DB and VNC objects out of sync is detected : " + getClassName(cls));
+ s_logger.debug("Log message: \n" + stats.logMsg);
+ } else {
+ s_logger.debug("DB and VNC objects are in sync : " + getClassName(cls));
+ }
+ }
+
+ /* return value of this method indicates state of the db & vnc before sync
+ * false: out of sync, true: in sync;
+ * it does not indicate whether sync operation is performed or not;
+ * Actual sync is done only if _syncMode is UPDATE
+ */
+ return stats.isSynchronized();
+ }
+
+}
+
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/EventUtils.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/EventUtils.java b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/EventUtils.java
new file mode 100644
index 0000000..445a2cf
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/EventUtils.java
@@ -0,0 +1,104 @@
+
+package net.juniper.contrail.management;
+
+import com.cloud.event.ActionEvent;
+import com.cloud.event.Event;
+import com.cloud.event.EventCategory;
+import com.cloud.event.EventTypes;
+import com.cloud.server.ManagementServer;
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.component.ComponentMethodInterceptor;
+
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.framework.messagebus.MessageBusBase;
+import org.apache.cloudstack.framework.messagebus.MessageBus;
+import org.apache.log4j.Logger;
+import org.springframework.beans.factory.NoSuchBeanDefinitionException;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+
+@Component
+public class EventUtils {
+ private static final Logger s_logger = Logger.getLogger(EventUtils.class);
+
+ protected static MessageBus _messageBus = null;
+
+ public EventUtils() {
+ }
+
+ private static void publishOnMessageBus(String eventCategory,
+ String eventType, String details, Event.State state) {
+
+ if (state != com.cloud.event.Event.State.Completed) {
+ return;
+ }
+
+ try {
+ _messageBus = (MessageBus)ComponentContext.getComponent(MessageBusBase.class);
+ } catch(NoSuchBeanDefinitionException nbe) {
+ return; // no provider is configured to provide events bus, so just return
+ }
+
+ org.apache.cloudstack.framework.events.Event event = new org.apache.cloudstack.framework.events.Event(
+ ManagementServer.Name,
+ eventCategory,
+ eventType,
+ EventTypes.getEntityForEvent(eventType), null);
+
+ Map<String, String> eventDescription = new HashMap<String, String>();
+ eventDescription.put("event", eventType);
+ eventDescription.put("status", state.toString());
+ eventDescription.put("details", details);
+ event.setDescription(eventDescription);
+ try {
+ _messageBus.publish(EventTypes.getEntityForEvent(eventType), eventType, null, event);
+ } catch (Exception e) {
+ s_logger.warn("Failed to publish action event on the the event bus.");
+ }
+
+ }
+
+ public static class EventInterceptor implements ComponentMethodInterceptor {
+
+ private static final Logger s_logger = Logger.getLogger(EventInterceptor.class);
+
+ public EventInterceptor() {
+
+ }
+
+ @Override
+ public Object interceptStart(Method method, Object target) {
+ return null;
+ }
+
+ @Override
+ public void interceptComplete(Method method, Object target, Object event) {
+ ActionEvent actionEvent = method.getAnnotation(ActionEvent.class);
+ if (actionEvent != null) {
+ CallContext ctx = CallContext.current();
+ if (!actionEvent.create()) {
+ publishOnMessageBus(EventCategory.ACTION_EVENT.getName(),
+ actionEvent.eventType(), ctx.getEventDetails(), com.cloud.event.Event.State.Completed);
+ }
+ }
+ }
+
+ @Override
+ public void interceptException(Method method, Object target, Object event) {
+ s_logger.debug("interceptException");
+ }
+
+ @Override
+ public boolean needToIntercept(Method method) {
+ ActionEvent actionEvent = method.getAnnotation(ActionEvent.class);
+ if (actionEvent != null) {
+ return true;
+ }
+
+ return false;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ManagementNetworkGuru.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ManagementNetworkGuru.java b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ManagementNetworkGuru.java
new file mode 100644
index 0000000..3c23016
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ManagementNetworkGuru.java
@@ -0,0 +1,100 @@
+package net.juniper.contrail.management;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.naming.ConfigurationException;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.deploy.DeploymentPlan;
+import com.cloud.network.Network;
+import com.cloud.network.Networks.BroadcastDomainType;
+import com.cloud.network.Networks.Mode;
+import com.cloud.network.Networks.TrafficType;
+import com.cloud.network.dao.NetworkVO;
+import com.cloud.offering.NetworkOffering;
+import com.cloud.user.Account;
+import com.cloud.utils.PropertiesUtil;
+
+/**
+ * ManagementNetworkGuru
+ *
+ * Replace the default management network strategy (PodBasedNetworkGuru) by using a Isolated network for management
+ * traffic.
+ *
+ * @author roque
+ *
+ */
+@Component
+public class ManagementNetworkGuru extends ContrailGuru {
+ private static final Logger s_logger = Logger.getLogger(ManagementNetworkGuru.class);
+ private static final TrafficType[] _trafficTypes = {TrafficType.Management};
+
+ private final String configuration = "contrail.properties";
+ private String _mgmt_cidr;
+ private String _mgmt_gateway;
+
+ @Override
+ public String getName() {
+ return "ManagementNetworkGuru";
+ }
+
+ @Override
+ 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));
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ throw new ConfigurationException(ex.getMessage());
+ }
+ _mgmt_cidr = configProps.getProperty("management.cidr");
+ _mgmt_gateway = configProps.getProperty("management.gateway");
+ s_logger.info("Management network " + _mgmt_cidr + " gateway: " + _mgmt_gateway);
+ return true;
+ }
+
+ @Override
+ public TrafficType[] getSupportedTrafficType() {
+ return _trafficTypes;
+ }
+
+ @Override
+ public boolean isMyTrafficType(TrafficType type) {
+ for (TrafficType t : _trafficTypes) {
+ if (t == type) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean canHandle(NetworkOffering offering) {
+ TrafficType type = offering.getTrafficType();
+ return (isMyTrafficType(type));
+ }
+
+ @Override
+ public Network design(NetworkOffering offering, DeploymentPlan plan,
+ Network userSpecified, Account owner) {
+
+ if (!canHandle(offering)) {
+ return null;
+ }
+ NetworkVO network = new NetworkVO(offering.getTrafficType(), Mode.Dhcp, BroadcastDomainType.Lswitch,
+ offering.getId(), Network.State.Allocated, plan.getDataCenterId(), plan.getPhysicalNetworkId());
+ if (_mgmt_cidr != null) {
+ network.setCidr(_mgmt_cidr);
+ network.setGateway(_mgmt_gateway);
+ }
+ s_logger.debug("Allocated network " + userSpecified.getName() +
+ (network.getCidr() == null ? "" : " subnet: " + network.getCidr()));
+ return network;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ModelDatabase.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ModelDatabase.java b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ModelDatabase.java
new file mode 100644
index 0000000..90c67cc
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ModelDatabase.java
@@ -0,0 +1,72 @@
+package net.juniper.contrail.management;
+
+import java.util.TreeSet;
+
+import com.cloud.network.Networks.TrafficType;
+
+import net.juniper.contrail.model.ModelObjectBase;
+import net.juniper.contrail.model.ServiceInstanceModel;
+import net.juniper.contrail.model.VirtualMachineModel;
+import net.juniper.contrail.model.VirtualNetworkModel;
+
+public class ModelDatabase {
+ TreeSet<ServiceInstanceModel> _serviceInstanceTable;
+ TreeSet<VirtualMachineModel> _vmTable;
+ TreeSet<VirtualNetworkModel> _vnTable;
+
+ ModelDatabase() {
+ initDb();
+ }
+
+ public void initDb() {
+ _serviceInstanceTable = new TreeSet<ServiceInstanceModel>(new ModelObjectBase.UuidComparator());
+ _vmTable = new TreeSet<VirtualMachineModel>(new ModelObjectBase.UuidComparator());
+ _vnTable = new TreeSet<VirtualNetworkModel>(new ModelObjectBase.UuidComparator());
+ }
+
+ public TreeSet<ServiceInstanceModel> getServiceInstances() {
+ return _serviceInstanceTable;
+ }
+
+ public ServiceInstanceModel lookupServiceInstance(String uuid) {
+ ServiceInstanceModel siKey = new ServiceInstanceModel(uuid);
+ ServiceInstanceModel current = _serviceInstanceTable.ceiling(siKey);
+ if (current != null && current.getUuid().equals(uuid)) {
+ return current;
+ }
+ return null;
+ }
+
+ public TreeSet<VirtualMachineModel> getVirtualMachines() {
+ return _vmTable;
+ }
+
+ public VirtualMachineModel lookupVirtualMachine(String uuid) {
+ VirtualMachineModel vmKey = new VirtualMachineModel(null, uuid);
+ VirtualMachineModel current = _vmTable.ceiling(vmKey);
+ if (current != null && current.getUuid().equals(uuid)) {
+ return current;
+ }
+ return null;
+ }
+
+ public TreeSet<VirtualNetworkModel> getVirtualNetworks() {
+ return _vnTable;
+ }
+
+ public VirtualNetworkModel lookupVirtualNetwork(String uuid, String name, TrafficType ttype) {
+ VirtualNetworkModel vnKey = new VirtualNetworkModel(null, uuid, name, ttype);
+ VirtualNetworkModel current = _vnTable.ceiling(vnKey);
+ if (current != null) {
+ if (ttype == TrafficType.Management || ttype == TrafficType.Storage
+ || ttype == TrafficType.Control) {
+ if (current.getName().equals(name)) {
+ return current;
+ }
+ } else if (current.getUuid().equals(uuid)) {
+ return current;
+ }
+ }
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7099686b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ServerDBSync.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ServerDBSync.java b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ServerDBSync.java
new file mode 100644
index 0000000..3571312
--- /dev/null
+++ b/plugins/network-elements/juniper-contrail/src/net/juniper/contrail/management/ServerDBSync.java
@@ -0,0 +1,22 @@
+package net.juniper.contrail.management;
+
+import java.io.IOException;
+
+import com.cloud.domain.DomainVO;
+import com.cloud.projects.ProjectVO;
+
+public interface ServerDBSync {
+
+
+ public final static short SYNC_STATE_IN_SYNC = 0;
+ public final static short SYNC_STATE_OUT_OF_SYNC = 1;
+ public final static short SYNC_STATE_UNKNOWN = -1;
+ /*
+ * API for syncing all classes of vnc objects with cloudstack
+ * Sync cloudstack and vnc objects.
+ */
+ public short syncAll(short syncMode);
+ public void syncClass(Class<?> cls);
+ public void createProject(ProjectVO project, StringBuffer syncLogMesg) throws IOException;
+ public void createDomain(DomainVO domain, StringBuffer logMesg)throws IOException;
+}